title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python Remove Duplicates from a List - GeeksforGeeks
19 Dec, 2020 The job is simple. We need to take a list, with duplicate elements in it and generate another list which only contains the element without the duplicates in them. Examples: Input : [2, 4, 10, 20, 5, 2, 20, 4] Output : [2, 4, 10, 20, 5] Input : [28, 42, 28, 16, 90, 42, 42, 28] Output : [28, 42, 16, 90] We can use not in on list to find out the duplicate items. We create a result list and insert only those that are not already not in. Python3 # Python code to remove duplicate elementsdef Remove(duplicate): final_list = [] for num in duplicate: if num not in final_list: final_list.append(num) return final_list # Driver Codeduplicate = [2, 4, 10, 20, 5, 2, 20, 4]print(Remove(duplicate)) Output: [2, 4, 10, 20, 5] Easy Implementation: A quick way to do the above using set data structure from the python standard library (Python 3.x implementation is given below) Python3 duplicate = [2, 4, 10, 20, 5, 2, 20, 4]print(list(set(duplicate))) Output: [2, 4, 10, 20, 5] codeslord sathiya1622 Python list-programs python-list Python python-list 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": 26485, "s": 26457, "text": "\n19 Dec, 2020" }, { "code": null, "e": 26648, "s": 26485, "text": "The job is simple. We need to take a list, with duplicate elements in it and generate another list which only contains the element without the duplicates in them." }, { "code": null, "e": 26660, "s": 26648, "text": "Examples: " }, { "code": null, "e": 26791, "s": 26660, "text": "Input : [2, 4, 10, 20, 5, 2, 20, 4]\nOutput : [2, 4, 10, 20, 5]\n\nInput : [28, 42, 28, 16, 90, 42, 42, 28]\nOutput : [28, 42, 16, 90]" }, { "code": null, "e": 26926, "s": 26791, "text": "We can use not in on list to find out the duplicate items. We create a result list and insert only those that are not already not in. " }, { "code": null, "e": 26934, "s": 26926, "text": "Python3" }, { "code": "# Python code to remove duplicate elementsdef Remove(duplicate): final_list = [] for num in duplicate: if num not in final_list: final_list.append(num) return final_list # Driver Codeduplicate = [2, 4, 10, 20, 5, 2, 20, 4]print(Remove(duplicate))", "e": 27212, "s": 26934, "text": null }, { "code": null, "e": 27222, "s": 27212, "text": "Output: " }, { "code": null, "e": 27240, "s": 27222, "text": "[2, 4, 10, 20, 5]" }, { "code": null, "e": 27261, "s": 27240, "text": "Easy Implementation:" }, { "code": null, "e": 27392, "s": 27261, "text": "A quick way to do the above using set data structure from the python standard library (Python 3.x implementation is given below) " }, { "code": null, "e": 27400, "s": 27392, "text": "Python3" }, { "code": "duplicate = [2, 4, 10, 20, 5, 2, 20, 4]print(list(set(duplicate)))", "e": 27467, "s": 27400, "text": null }, { "code": null, "e": 27477, "s": 27467, "text": "Output: " }, { "code": null, "e": 27496, "s": 27477, "text": "[2, 4, 10, 20, 5] " }, { "code": null, "e": 27506, "s": 27496, "text": "codeslord" }, { "code": null, "e": 27518, "s": 27506, "text": "sathiya1622" }, { "code": null, "e": 27539, "s": 27518, "text": "Python list-programs" }, { "code": null, "e": 27551, "s": 27539, "text": "python-list" }, { "code": null, "e": 27558, "s": 27551, "text": "Python" }, { "code": null, "e": 27570, "s": 27558, "text": "python-list" }, { "code": null, "e": 27668, "s": 27570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27686, "s": 27668, "text": "Python Dictionary" }, { "code": null, "e": 27721, "s": 27686, "text": "Read a file line by line in Python" }, { "code": null, "e": 27753, "s": 27721, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27775, "s": 27753, "text": "Enumerate() in Python" }, { "code": null, "e": 27817, "s": 27775, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27847, "s": 27817, "text": "Iterate over a list in Python" }, { "code": null, "e": 27873, "s": 27847, "text": "Python String | replace()" }, { "code": null, "e": 27902, "s": 27873, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27946, "s": 27902, "text": "Reading and Writing to text files in Python" } ]
An Uncommon representation of array elements - GeeksforGeeks
09 Nov, 2020 Consider the below program. int main( ){ int arr[2] = {0,1}; printf("First Element = %d\n",arr[0]); getchar(); return 0;} Pretty Simple program.. huh... Output will be 0. Now if you replace arr[0] with 0[arr], the output would be same. Because compiler converts the array operation in pointers before accessing the array elements. e.g. arr[0] would be *(arr + 0) and therefore 0[arr] would be *(0 + arr) and you know that both *(arr + 0) and *(0 + arr) are same.YouTubeGeeksforGeeks507K subscribersAn Uncommon representation of array elements | 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 / 4:17•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Uw_TtJQyrwk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Please write comments if you find anything incorrect in the above article. C-Pointers C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Substring in C++ Core Dump (Segmentation fault) in C/C++ rand() and srand() in C/C++ fork() in C Converting Strings to Numbers in C/C++ std::string class in C++ Enumeration (or enum) in C Command line arguments in C/C++
[ { "code": null, "e": 25985, "s": 25957, "text": "\n09 Nov, 2020" }, { "code": null, "e": 26013, "s": 25985, "text": "Consider the below program." }, { "code": "int main( ){ int arr[2] = {0,1}; printf(\"First Element = %d\\n\",arr[0]); getchar(); return 0;}", "e": 26111, "s": 26013, "text": null }, { "code": null, "e": 26160, "s": 26111, "text": "Pretty Simple program.. huh... Output will be 0." }, { "code": null, "e": 26320, "s": 26160, "text": "Now if you replace arr[0] with 0[arr], the output would be same. Because compiler converts the array operation in pointers before accessing the array elements." }, { "code": null, "e": 27294, "s": 26320, "text": "e.g. arr[0] would be *(arr + 0) and therefore 0[arr] would be *(0 + arr) and you know that both *(arr + 0) and *(0 + arr) are same.YouTubeGeeksforGeeks507K subscribersAn Uncommon representation of array elements | 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 / 4:17•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Uw_TtJQyrwk\" 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": 27369, "s": 27294, "text": "Please write comments if you find anything incorrect in the above article." }, { "code": null, "e": 27380, "s": 27369, "text": "C-Pointers" }, { "code": null, "e": 27391, "s": 27380, "text": "C Language" }, { "code": null, "e": 27489, "s": 27391, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27524, "s": 27489, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27570, "s": 27524, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 27587, "s": 27570, "text": "Substring in C++" }, { "code": null, "e": 27627, "s": 27587, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 27655, "s": 27627, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27667, "s": 27655, "text": "fork() in C" }, { "code": null, "e": 27706, "s": 27667, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 27731, "s": 27706, "text": "std::string class in C++" }, { "code": null, "e": 27758, "s": 27731, "text": "Enumeration (or enum) in C" } ]
XMPP Protocol - GeeksforGeeks
21 Mar, 2018 XMPP is a short form for Extensible Messaging Presence Protocol. It’s protocol for streaming XML elements over a network in order to exchange messages and presence information in close to real time. This protocol is mostly used by instant messaging applications like WhatsApp. Let’s dive into each character of word XMPP: X : It means eXtensible. XMPP is a open source project which can be changed or extended according to the need. M : XMPP is designed for sending messages in real time. It has very efficient push mechanism compared to other protocols. P : It determines whether you are online/offline/busy. It indicates the state. P : XMPP is a protocol, that is, a set of standards that allow systems to communicate with each other. These are the basic requirements of any Instant Messenger which are fulfilled by XMPP: Send and receive messages with other users.Check and share presence statusManage subscriptions to and from other users.Manage contact listBlock communications(receive message, sharing presence status, etc) to specific users. Send and receive messages with other users. Check and share presence status Manage subscriptions to and from other users. Manage contact list Block communications(receive message, sharing presence status, etc) to specific users. Other XMPP features: Decentralised –XMPP is based on client-server architecture, i.e. clients don’t communicate directly, they do it with the help of server as intermediary. It is decentralised means there is no centralised XMPP server just like email, anyone can run their own XMPP server. Each XMPP client is identified by JID (Jabber ID). #JID { user, server, resource } For example, I’m a whatsApp user and I’m identified by my mobile number, so user = "8767898790" server = "whatsapp.com" resource = "mobile" JID : "[email protected]/mobile" resource is used in case the application support mobile as well as desktop or web application, so it can be optional in case a Instant Messenger Application support only single kind of resource. XMPP implementation – The original protocol for XMPP is Transmission Control Protocol, using open ended XML streams over long lived TCP connections. In some cases, there are restricted firewalls, XMPP(port 5222) is blocked, so it can’t be used for web applications and users behind restricted firewalls, to overcome this, XMPP community also developed a HTTP transport.And as the client uses HTTP, most firewalls allow clients to fetch and post messages without any problem. Thus, in scenarios where the TCP port used by XMPP is blocked, a server can listen on the normal HTTP port and the traffic should pass without problems. References:xmpp.orgXMPP wiki Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML and XML Web technologies-HTML and XML Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to apply style to parent if it has child with CSS? Difference Between PUT and PATCH Request How to execute PHP code using command line ? REST API (Introduction) How to redirect to another page in ReactJS ?
[ { "code": null, "e": 26195, "s": 26167, "text": "\n21 Mar, 2018" }, { "code": null, "e": 26472, "s": 26195, "text": "XMPP is a short form for Extensible Messaging Presence Protocol. It’s protocol for streaming XML elements over a network in order to exchange messages and presence information in close to real time. This protocol is mostly used by instant messaging applications like WhatsApp." }, { "code": null, "e": 26517, "s": 26472, "text": "Let’s dive into each character of word XMPP:" }, { "code": null, "e": 26628, "s": 26517, "text": "X : It means eXtensible. XMPP is a open source project which can be changed or extended according to the need." }, { "code": null, "e": 26750, "s": 26628, "text": "M : XMPP is designed for sending messages in real time. It has very efficient push mechanism compared to other protocols." }, { "code": null, "e": 26829, "s": 26750, "text": "P : It determines whether you are online/offline/busy. It indicates the state." }, { "code": null, "e": 26932, "s": 26829, "text": "P : XMPP is a protocol, that is, a set of standards that allow systems to communicate with each other." }, { "code": null, "e": 27019, "s": 26932, "text": "These are the basic requirements of any Instant Messenger which are fulfilled by XMPP:" }, { "code": null, "e": 27244, "s": 27019, "text": "Send and receive messages with other users.Check and share presence statusManage subscriptions to and from other users.Manage contact listBlock communications(receive message, sharing presence status, etc) to specific users." }, { "code": null, "e": 27288, "s": 27244, "text": "Send and receive messages with other users." }, { "code": null, "e": 27320, "s": 27288, "text": "Check and share presence status" }, { "code": null, "e": 27366, "s": 27320, "text": "Manage subscriptions to and from other users." }, { "code": null, "e": 27386, "s": 27366, "text": "Manage contact list" }, { "code": null, "e": 27473, "s": 27386, "text": "Block communications(receive message, sharing presence status, etc) to specific users." }, { "code": null, "e": 27494, "s": 27473, "text": "Other XMPP features:" }, { "code": null, "e": 27764, "s": 27494, "text": "Decentralised –XMPP is based on client-server architecture, i.e. clients don’t communicate directly, they do it with the help of server as intermediary. It is decentralised means there is no centralised XMPP server just like email, anyone can run their own XMPP server." }, { "code": null, "e": 27815, "s": 27764, "text": "Each XMPP client is identified by JID (Jabber ID)." }, { "code": null, "e": 27858, "s": 27815, "text": "#JID\n {\n user,\n server,\n resource\n}\n" }, { "code": null, "e": 27934, "s": 27858, "text": "For example, I’m a whatsApp user and I’m identified by my mobile number, so" }, { "code": null, "e": 28051, "s": 27934, "text": " user = \"8767898790\"\n server = \"whatsapp.com\"\n resource = \"mobile\"\n\n JID : \"[email protected]/mobile\"\n" }, { "code": null, "e": 28246, "s": 28051, "text": "resource is used in case the application support mobile as well as desktop or web application, so it can be optional in case a Instant Messenger Application support only single kind of resource." }, { "code": null, "e": 28268, "s": 28246, "text": "XMPP implementation –" }, { "code": null, "e": 28395, "s": 28268, "text": "The original protocol for XMPP is Transmission Control Protocol, using open ended XML streams over long lived TCP connections." }, { "code": null, "e": 28874, "s": 28395, "text": "In some cases, there are restricted firewalls, XMPP(port 5222) is blocked, so it can’t be used for web applications and users behind restricted firewalls, to overcome this, XMPP community also developed a HTTP transport.And as the client uses HTTP, most firewalls allow clients to fetch and post messages without any problem. Thus, in scenarios where the TCP port used by XMPP is blocked, a server can listen on the normal HTTP port and the traffic should pass without problems." }, { "code": null, "e": 28903, "s": 28874, "text": "References:xmpp.orgXMPP wiki" }, { "code": null, "e": 29040, "s": 28903, "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": 29053, "s": 29040, "text": "HTML and XML" }, { "code": null, "e": 29083, "s": 29053, "text": "Web technologies-HTML and XML" }, { "code": null, "e": 29100, "s": 29083, "text": "Web Technologies" }, { "code": null, "e": 29198, "s": 29100, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29238, "s": 29198, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29283, "s": 29238, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29326, "s": 29283, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29387, "s": 29326, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29459, "s": 29387, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29514, "s": 29459, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 29555, "s": 29514, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29600, "s": 29555, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 29624, "s": 29600, "text": "REST API (Introduction)" } ]
Apex - Classes
A class is a template or blueprint from which objects are created. An object is an instance of a class. This is the standard definition of Class. Apex Classes are similar to Java Classes. For example, InvoiceProcessor class describes the class which has all the methods and actions that can be performed on the Invoice. If you create an instance of this class, then it will represent the single invoice which is currently in context. You can create class in Apex from the Developer Console, Force.com Eclipse IDE and from Apex Class detail page as well. Follow these steps to create an Apex class from the Developer Console − Step 1 − Go to Name and click on the Developer Console. Step 2 − Click on File ⇒ New and then click on the Apex class. Follow these steps to create a class from Force.com IDE − Step 1 − Open Force.com Eclipse IDE Step 2 − Create a New Project by clicking on File ⇒ New ⇒ Apex Class. Step 3 − Provide the Name for the Class and click on OK. Once this is done, the new class will be created. Follow these steps to create a class from Apex Class Detail Page − Step 1 − Click on Name ⇒ Setup. Step 2 − Search for 'Apex Class' and click on the link. It will open the Apex Class details page. Step 3 − Click on 'New' and then provide the Name for class and then click Save. Below is the sample structure for Apex class definition. Syntax private | public | global [virtual | abstract | with sharing | without sharing] class ClassName [implements InterfaceNameList] [extends ClassName] { // Classs Body } This definition uses a combination of access modifiers, sharing modes, class name and class body. We will look at all these options further. Example Following is a sample structure for Apex class definition − public class MySampleApexClass { //Class definition and body public static Integer myValue = 0; //Class Member variable public static String myString = ''; //Class Member variable public static Integer getCalculatedValue () { // Method definition and body // do some calculation myValue = myValue+10; return myValue; } } If you declare the access modifier as 'Private', then this class will be known only locally and you cannot access this class outside of that particular piece. By default, classes have this modifier. If you declare the class as 'Public' then this implies that this class is accessible to your organization and your defined namespace. Normally, most of the Apex classes are defined with this keyword. If you declare the class as 'global' then this will be accessible by all apex codes irrespective of your organization. If you have method defined with web service keyword, then you must declare the containing class with global keyword. Let us now discuss the different modes of sharing. This is a special feature of Apex Classes in Salesforce. When a class is specified with 'With Sharing' keyword then it has following implications: When the class will get executed, it will respect the User's access settings and profile permission. Suppose, User's action has triggered the record update for 30 records, but user has access to only 20 records and 10 records are not accessible. Then, if the class is performing the action to update the records, only 20 records will be updated to which the user has access and rest of 10 records will not be updated. This is also called as the User mode. Even if the User does not have access to 10 records out of 30, all the 30 records will be updated as the Class is running in the System mode, i.e., it has been defined with Without Sharing keyword. This is called the System Mode. If you use the 'virtual' keyword, then it indicates that this class can be extended and overrides are allowed. If the methods need to be overridden, then the classes should be declared with the virtual keyword. If you declare the class as 'abstract', then it will only contain the signature of method and not the actual implementation. Syntax [public | private | protected | global] [final] [static] data_type variable_name [= value] In the above syntax − Variable data type and variable name are mandatory Access modifiers and value are optional. Example public static final Integer myvalue; 14 Lectures 2 hours Vijay Thapa 7 Lectures 2 hours Uplatz 29 Lectures 6 hours Ramnarayan Ramakrishnan 49 Lectures 3 hours Ali Saleh Ali 10 Lectures 4 hours Soham Ghosh 48 Lectures 4.5 hours GUHARAJANM Print Add Notes Bookmark this page
[ { "code": null, "e": 2240, "s": 2052, "text": "A class is a template or blueprint from which objects are created. An object is an instance of a class. This is the standard definition of Class. Apex Classes are similar to Java Classes." }, { "code": null, "e": 2486, "s": 2240, "text": "For example, InvoiceProcessor class describes the class which has all the methods and actions that can be performed on the Invoice. If you create an instance of this class, then it will represent the single invoice which is currently in context." }, { "code": null, "e": 2606, "s": 2486, "text": "You can create class in Apex from the Developer Console, Force.com Eclipse IDE and from Apex Class detail page as well." }, { "code": null, "e": 2678, "s": 2606, "text": "Follow these steps to create an Apex class from the Developer Console −" }, { "code": null, "e": 2734, "s": 2678, "text": "Step 1 − Go to Name and click on the Developer Console." }, { "code": null, "e": 2797, "s": 2734, "text": "Step 2 − Click on File ⇒ New and then click on the Apex class." }, { "code": null, "e": 2855, "s": 2797, "text": "Follow these steps to create a class from Force.com IDE −" }, { "code": null, "e": 2891, "s": 2855, "text": "Step 1 − Open Force.com Eclipse IDE" }, { "code": null, "e": 2961, "s": 2891, "text": "Step 2 − Create a New Project by clicking on File ⇒ New ⇒ Apex Class." }, { "code": null, "e": 3018, "s": 2961, "text": "Step 3 − Provide the Name for the Class and click on OK." }, { "code": null, "e": 3068, "s": 3018, "text": "Once this is done, the new class will be created." }, { "code": null, "e": 3135, "s": 3068, "text": "Follow these steps to create a class from Apex Class Detail Page −" }, { "code": null, "e": 3167, "s": 3135, "text": "Step 1 − Click on Name ⇒ Setup." }, { "code": null, "e": 3265, "s": 3167, "text": "Step 2 − Search for 'Apex Class' and click on the link. It will open the Apex Class details\npage." }, { "code": null, "e": 3346, "s": 3265, "text": "Step 3 − Click on 'New' and then provide the Name for class and then click Save." }, { "code": null, "e": 3403, "s": 3346, "text": "Below is the sample structure for Apex class definition." }, { "code": null, "e": 3410, "s": 3403, "text": "Syntax" }, { "code": null, "e": 3580, "s": 3410, "text": "private | public | global\n[virtual | abstract | with sharing | without sharing]\nclass ClassName [implements InterfaceNameList] [extends ClassName] {\n // Classs Body\n}\n" }, { "code": null, "e": 3721, "s": 3580, "text": "This definition uses a combination of access modifiers, sharing modes, class name and class body. We will look at all these options further." }, { "code": null, "e": 3729, "s": 3721, "text": "Example" }, { "code": null, "e": 3789, "s": 3729, "text": "Following is a sample structure for Apex class definition −" }, { "code": null, "e": 4151, "s": 3789, "text": "public class MySampleApexClass { //Class definition and body\n public static Integer myValue = 0; //Class Member variable\n public static String myString = ''; //Class Member variable\n \n public static Integer getCalculatedValue () {\n // Method definition and body\n // do some calculation\n myValue = myValue+10;\n return myValue;\n }\n}" }, { "code": null, "e": 4350, "s": 4151, "text": "If you declare the access modifier as 'Private', then this class will be known only locally and you cannot access this class outside of that particular piece. By default, classes have this modifier." }, { "code": null, "e": 4550, "s": 4350, "text": "If you declare the class as 'Public' then this implies that this class is accessible to your organization and your defined namespace. Normally, most of the Apex classes are defined with this keyword." }, { "code": null, "e": 4786, "s": 4550, "text": "If you declare the class as 'global' then this will be accessible by all apex codes irrespective of your organization. If you have method defined with web service keyword, then you must declare the containing class with global keyword." }, { "code": null, "e": 4837, "s": 4786, "text": "Let us now discuss the different modes of sharing." }, { "code": null, "e": 5440, "s": 4837, "text": "This is a special feature of Apex Classes in Salesforce. When a class is specified with 'With Sharing' keyword then it has following implications: When the class will get executed, it will respect the User's access settings and profile permission. Suppose, User's action has triggered the record update for 30 records, but user has access to only 20 records and 10 records are not accessible. Then, if the class is performing the action to update the records, only 20 records will be updated to which the user has access and rest of 10 records will not be updated. This is also called as the User mode." }, { "code": null, "e": 5670, "s": 5440, "text": "Even if the User does not have access to 10 records out of 30, all the 30 records will be updated as the Class is running in the System mode, i.e., it has been defined with Without Sharing keyword. This is called the System Mode." }, { "code": null, "e": 5881, "s": 5670, "text": "If you use the 'virtual' keyword, then it indicates that this class can be extended and overrides are allowed. If the methods need to be overridden, then the classes should be declared with the virtual keyword." }, { "code": null, "e": 6006, "s": 5881, "text": "If you declare the class as 'abstract', then it will only contain the signature of method and not the actual implementation." }, { "code": null, "e": 6013, "s": 6006, "text": "Syntax" }, { "code": null, "e": 6105, "s": 6013, "text": "[public | private | protected | global] [final] [static] data_type\nvariable_name [= value]\n" }, { "code": null, "e": 6127, "s": 6105, "text": "In the above syntax −" }, { "code": null, "e": 6178, "s": 6127, "text": "Variable data type and variable name are mandatory" }, { "code": null, "e": 6219, "s": 6178, "text": "Access modifiers and value are optional." }, { "code": null, "e": 6227, "s": 6219, "text": "Example" }, { "code": null, "e": 6264, "s": 6227, "text": "public static final Integer myvalue;" }, { "code": null, "e": 6297, "s": 6264, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 6310, "s": 6297, "text": " Vijay Thapa" }, { "code": null, "e": 6342, "s": 6310, "text": "\n 7 Lectures \n 2 hours \n" }, { "code": null, "e": 6350, "s": 6342, "text": " Uplatz" }, { "code": null, "e": 6383, "s": 6350, "text": "\n 29 Lectures \n 6 hours \n" }, { "code": null, "e": 6408, "s": 6383, "text": " Ramnarayan Ramakrishnan" }, { "code": null, "e": 6441, "s": 6408, "text": "\n 49 Lectures \n 3 hours \n" }, { "code": null, "e": 6456, "s": 6441, "text": " Ali Saleh Ali" }, { "code": null, "e": 6489, "s": 6456, "text": "\n 10 Lectures \n 4 hours \n" }, { "code": null, "e": 6502, "s": 6489, "text": " Soham Ghosh" }, { "code": null, "e": 6537, "s": 6502, "text": "\n 48 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6549, "s": 6537, "text": " GUHARAJANM" }, { "code": null, "e": 6556, "s": 6549, "text": " Print" }, { "code": null, "e": 6567, "s": 6556, "text": " Add Notes" } ]
Make an image responsive with Bootstrap
To make an image responsive in Bootstrap, add a class .img-responsive to the <img> tag. This class applies max-width: 100%; and height: auto; to the image so that it scales nicely to the parent element. The following is how you can simply make an image responsive − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <img src = "https://www.tutorialspoint.com/python/images/python_data_science.jpg" class = "img-responsive" alt = "Online Training"> </body> </html>
[ { "code": null, "e": 1265, "s": 1062, "text": "To make an image responsive in Bootstrap, add a class .img-responsive to the <img> tag. This class applies max-width: 100%; and height: auto; to the image so that it scales nicely to the parent element." }, { "code": null, "e": 1328, "s": 1265, "text": "The following is how you can simply make an image responsive −" }, { "code": null, "e": 1339, "s": 1328, "text": " Live Demo" }, { "code": null, "e": 1781, "s": 1339, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <img src = \"https://www.tutorialspoint.com/python/images/python_data_science.jpg\" class = \"img-responsive\" alt = \"Online Training\">\n </body>\n</html>" } ]
Python - Next N elements from K value - GeeksforGeeks
11 Oct, 2020 Given a List, get next N values from occurrence of K value in List. Input : test_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9], N = 1, K = 4 Output : [6, 7, 2] Explanation : All successive elements to 4 are extracted as N = 1. Input : test_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9], N = 2, K = 7 Output : [8, 4, 2, 1] Explanation : Two elements after each occurrence of 7 are extracted. Method #1 : Using list comprehension + slicing In this we extract all the indices using list comprehension, and then loop is employed to append the elements and join in as single string from the desired K value occurrences in List. Python3 # Python3 code to demonstrate working of# Next N elements of K value# Using list comprehension + slicing # initializing listtest_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9] # printing original listprint("The original list is : " + str(test_list)) # initializing KK = 4 # initializing NN = 2 # getting indices of Ktemp = [idx for idx in range(len(test_list)) if test_list[idx] == K] # getting next N elements from K using loopres = []for ele in temp: # appending slice res.extend(test_list[ele + 1: ele + N + 1]) # printing resultprint("Constructed Result List : " + str(res)) The original list is : [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9] Constructed Result List : [6, 7, 7, 2, 2, 3] Method #2 : Using filter() + lambda + loop This is similar to above method, difference being filtering of indices is performed using filter() and lambda functions. Python3 # Python3 code to demonstrate working of# Next N elements of K value# Using filter() + lambda + loop # initializing listtest_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9] # printing original listprint("The original list is : " + str(test_list)) # initializing KK = 4 # initializing NN = 2 # getting indices of K# using filter() and lambdatemp = list(filter(lambda ele: test_list[ele] == K, range(len(test_list)))) # getting next N elements from K using loopres = []for ele in temp: # appending slice res.extend(test_list[ele + 1: ele + N + 1]) # printing resultprint("Constructed Result List : " + str(res)) The original list is : [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9] Constructed Result List : [6, 7, 7, 2, 2, 3] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Check if element exists in list in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 24212, "s": 24184, "text": "\n11 Oct, 2020" }, { "code": null, "e": 24280, "s": 24212, "text": "Given a List, get next N values from occurrence of K value in List." }, { "code": null, "e": 24443, "s": 24280, "text": "Input : test_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9], N = 1, K = 4 Output : [6, 7, 2] Explanation : All successive elements to 4 are extracted as N = 1." }, { "code": null, "e": 24612, "s": 24443, "text": "Input : test_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9], N = 2, K = 7 Output : [8, 4, 2, 1] Explanation : Two elements after each occurrence of 7 are extracted. " }, { "code": null, "e": 24660, "s": 24612, "text": "Method #1 : Using list comprehension + slicing " }, { "code": null, "e": 24845, "s": 24660, "text": "In this we extract all the indices using list comprehension, and then loop is employed to append the elements and join in as single string from the desired K value occurrences in List." }, { "code": null, "e": 24853, "s": 24845, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Next N elements of K value# Using list comprehension + slicing # initializing listtest_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing KK = 4 # initializing NN = 2 # getting indices of Ktemp = [idx for idx in range(len(test_list)) if test_list[idx] == K] # getting next N elements from K using loopres = []for ele in temp: # appending slice res.extend(test_list[ele + 1: ele + N + 1]) # printing resultprint(\"Constructed Result List : \" + str(res))", "e": 25450, "s": 24853, "text": null }, { "code": null, "e": 25563, "s": 25450, "text": "The original list is : [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9]\nConstructed Result List : [6, 7, 7, 2, 2, 3]\n\n" }, { "code": null, "e": 25606, "s": 25563, "text": "Method #2 : Using filter() + lambda + loop" }, { "code": null, "e": 25727, "s": 25606, "text": "This is similar to above method, difference being filtering of indices is performed using filter() and lambda functions." }, { "code": null, "e": 25735, "s": 25727, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Next N elements of K value# Using filter() + lambda + loop # initializing listtest_list = [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing KK = 4 # initializing NN = 2 # getting indices of K# using filter() and lambdatemp = list(filter(lambda ele: test_list[ele] == K, range(len(test_list)))) # getting next N elements from K using loopres = []for ele in temp: # appending slice res.extend(test_list[ele + 1: ele + N + 1]) # printing resultprint(\"Constructed Result List : \" + str(res))", "e": 26362, "s": 25735, "text": null }, { "code": null, "e": 26475, "s": 26362, "text": "The original list is : [3, 4, 6, 7, 8, 4, 7, 2, 1, 8, 4, 2, 3, 9]\nConstructed Result List : [6, 7, 7, 2, 2, 3]\n\n" }, { "code": null, "e": 26496, "s": 26475, "text": "Python list-programs" }, { "code": null, "e": 26503, "s": 26496, "text": "Python" }, { "code": null, "e": 26519, "s": 26503, "text": "Python Programs" }, { "code": null, "e": 26617, "s": 26519, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26626, "s": 26617, "text": "Comments" }, { "code": null, "e": 26639, "s": 26626, "text": "Old Comments" }, { "code": null, "e": 26671, "s": 26639, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26726, "s": 26671, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26782, "s": 26726, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26821, "s": 26782, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26863, "s": 26821, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26885, "s": 26863, "text": "Defaultdict in Python" }, { "code": null, "e": 26924, "s": 26885, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26970, "s": 26924, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27008, "s": 26970, "text": "Python | Convert a list to dictionary" } ]
Create Dashboards in Python for Data Science Projects | Towards Data Science
I don’t have to convince you why we need an interactive dashboard. But what most people don’t know is that they don’t have to buy expensive licenses of Tableau or PowerBI. You don’t have to enroll in a JavaScript course either. Dash apps allow you to build interactive dashboards purely in Python. Interestingly, it could reach heights that popular BI platforms can not. Also, you can host it on your servers and your terms. BI Platforms such as Tableau and PowerBI do a fantastic job. It allows even non-technical managers to do data exploration themselves. I don’t have complaints about them. They are excellent tools to perform analysis on read-only datasets. But in large data science project, you’ll have to perform complex actions. For instance, you have to trigger a backend function and start the model retraining. In such cases, my best solution was to build a web app from scratch. JavaScript data visualization libraries such as HighCharts are excellent tools for this. They have callbacks for almost every possible user action. I use them to send data back to the server and control it better. But this wasn’t a walk in the park. My data science team is exceptional in Python and R but not in JavaScript. Not on web frameworks such as Django either. And that’s not enough; to build modern web apps, you need frontend web frameworks such as React. As we progressed, we realized the harsh truth. Every new technology in our stack inflates the difficulty exponentially. And we were fortunate to find Dash. If you’re looking for a lightweight alternative, check out Streamlit. Read along if you need a flexible, complete Python dashboarding solution. Now, this is how I create dazzling dashboards in Python. Yes, building dashboards in Dash is that simple. Install Pandas and dash with the following command, then start the timer. pip install dash pandas In your project directory, create a file called app.py with the below content. Showtime! let’s run the dashboard with the following command: python app.py You’ll see it starting a server at port 8050. If you visit http://127.0.0.1:8050 on your browser, you’d see the dashboard that looks like the following: If you’ve created a similar app using JavaScript libraries, you’d appreciate the difference. Dash saves a ton of time by eliminating an incredible amount of boilerplate code. Even popular BI tools have lots of prework to get to this point. Awesome. That’s quite a thing for inspiring you to build dashboards. But you might have realized that it’s not dazzling yet. In the following sections, we’ll discuss how we can improve the layout; add interactions and callbacks to the widgets, and; style the app further. With this, you can create the dazzling dashboard you need. Browse the Plottly Dash gallery for more of such dashboards for inspiration. Dash follows an HTML-like element hierarchy. You can attach any of Dash’s HTML components or Core components to the layout property of the app. The layout property is the root of a Dash app’s element hierarchy. Core components are a pre-configured set of widgets such as dropdowns and sliders. Dash’s HTML components cover almost every HTML element available. To create a heading, you can use html.H1 and html.Pto create a paragraph. The children attribute allows you to nest one HTML component within another. In the above code, we’ve included three core components — two dropdowns and a slider. These controller elements allow us to filter the chart data and create interactivity in the next section. Dash’s core components have callbacks to control the response for a user action. This feature is remarkable of why Dash apps outshine popular BI platforms. You can use this call back to control a chart re-rendering or to trigger a heavy analysis too. Check out my article on performing massive computation to use Dash apps along with Celery. Here in this post, we use callbacks to filter the chart data. The callback function is annotated with the @app.callback decorator. The first argument of this decorator is the Output component in the element tree. We need to specify the id of that element and the property we need to change. This property will change to the return value of the callback function. Then the decorated will accept any number of input arguments. Each will be tied to a core component in the same way we attached the output component. We can specify the id of the element and the property that emits the change value. Usually, this would be ‘value.’ Each input in the decorator should have a respective argument in the callback function’s definition. Finally, we moved the figure component inside the callback function. Every time we run the callback function, it creates a new figure instance and updates the UI. You can use the inline styling options available in Dash app. But with little CSS, you could have spectacular results. In-dash, you can style elements in three different ways. Every Dash component accepts a style argument. You can pass a dictionary and style any element. This is the most convenient way to style a Dash app. Alternatively, you can pass a class name attribute to any Dash component and use a separate CSS file to style it. You should place this CSS file inside an asset folder in your project directory. Dash will automatically pick it and apply its styles to the components. You can also use stylesheets from the internet. For instance, dash has this preconfigured stylesheet that comes with convenient utility classes. You can specify the style sheet and use its class names in elements to make them beautiful. Here is the complete styled source code of the application. We’ve used a local stylesheet and organized the HTML in a way to support styling. You can find the complete code and the local stylesheet in this GitHub repository. Your web app refreshes as you update your code with the above. And it may look like the below — your first version of a dazzling dashboard. plotly, Dash apps are an incredible tool for Python developers. Since most data science teams are not specializing in JavaScript, building dashboards with Dash saves a ton of their time. We can use Tableau, PowerBI, and similar BI platforms for data exploration and visualization. But Dash apps outshine them as they tightly integrate with the backend code. In this article, we explored the surface of Dash apps. I trust this would’ve given you the kickstart to build outstanding dashboards without worrying about scary technology stacks. As a next step, I strongly recommend exploring Dash’s documentation page and their example gallery. Thanks for the read, friend. It seems you and I have lots of common interests. Do check out my personal blog too. Say Hi to me on LinkedIn, Twitter, and Medium. I’ll break the ice for you. Not a Medium member yet? Please use this link to become a member because, at no extra cost for you, I earn a small commission for referring you.
[ { "code": null, "e": 399, "s": 171, "text": "I don’t have to convince you why we need an interactive dashboard. But what most people don’t know is that they don’t have to buy expensive licenses of Tableau or PowerBI. You don’t have to enroll in a JavaScript course either." }, { "code": null, "e": 596, "s": 399, "text": "Dash apps allow you to build interactive dashboards purely in Python. Interestingly, it could reach heights that popular BI platforms can not. Also, you can host it on your servers and your terms." }, { "code": null, "e": 766, "s": 596, "text": "BI Platforms such as Tableau and PowerBI do a fantastic job. It allows even non-technical managers to do data exploration themselves. I don’t have complaints about them." }, { "code": null, "e": 994, "s": 766, "text": "They are excellent tools to perform analysis on read-only datasets. But in large data science project, you’ll have to perform complex actions. For instance, you have to trigger a backend function and start the model retraining." }, { "code": null, "e": 1277, "s": 994, "text": "In such cases, my best solution was to build a web app from scratch. JavaScript data visualization libraries such as HighCharts are excellent tools for this. They have callbacks for almost every possible user action. I use them to send data back to the server and control it better." }, { "code": null, "e": 1530, "s": 1277, "text": "But this wasn’t a walk in the park. My data science team is exceptional in Python and R but not in JavaScript. Not on web frameworks such as Django either. And that’s not enough; to build modern web apps, you need frontend web frameworks such as React." }, { "code": null, "e": 1650, "s": 1530, "text": "As we progressed, we realized the harsh truth. Every new technology in our stack inflates the difficulty exponentially." }, { "code": null, "e": 1686, "s": 1650, "text": "And we were fortunate to find Dash." }, { "code": null, "e": 1830, "s": 1686, "text": "If you’re looking for a lightweight alternative, check out Streamlit. Read along if you need a flexible, complete Python dashboarding solution." }, { "code": null, "e": 1887, "s": 1830, "text": "Now, this is how I create dazzling dashboards in Python." }, { "code": null, "e": 2010, "s": 1887, "text": "Yes, building dashboards in Dash is that simple. Install Pandas and dash with the following command, then start the timer." }, { "code": null, "e": 2034, "s": 2010, "text": "pip install dash pandas" }, { "code": null, "e": 2113, "s": 2034, "text": "In your project directory, create a file called app.py with the below content." }, { "code": null, "e": 2175, "s": 2113, "text": "Showtime! let’s run the dashboard with the following command:" }, { "code": null, "e": 2189, "s": 2175, "text": "python app.py" }, { "code": null, "e": 2342, "s": 2189, "text": "You’ll see it starting a server at port 8050. If you visit http://127.0.0.1:8050 on your browser, you’d see the dashboard that looks like the following:" }, { "code": null, "e": 2582, "s": 2342, "text": "If you’ve created a similar app using JavaScript libraries, you’d appreciate the difference. Dash saves a ton of time by eliminating an incredible amount of boilerplate code. Even popular BI tools have lots of prework to get to this point." }, { "code": null, "e": 2752, "s": 2582, "text": "Awesome. That’s quite a thing for inspiring you to build dashboards. But you might have realized that it’s not dazzling yet. In the following sections, we’ll discuss how" }, { "code": null, "e": 2779, "s": 2752, "text": "we can improve the layout;" }, { "code": null, "e": 2831, "s": 2779, "text": "add interactions and callbacks to the widgets, and;" }, { "code": null, "e": 2854, "s": 2831, "text": "style the app further." }, { "code": null, "e": 2990, "s": 2854, "text": "With this, you can create the dazzling dashboard you need. Browse the Plottly Dash gallery for more of such dashboards for inspiration." }, { "code": null, "e": 3201, "s": 2990, "text": "Dash follows an HTML-like element hierarchy. You can attach any of Dash’s HTML components or Core components to the layout property of the app. The layout property is the root of a Dash app’s element hierarchy." }, { "code": null, "e": 3284, "s": 3201, "text": "Core components are a pre-configured set of widgets such as dropdowns and sliders." }, { "code": null, "e": 3501, "s": 3284, "text": "Dash’s HTML components cover almost every HTML element available. To create a heading, you can use html.H1 and html.Pto create a paragraph. The children attribute allows you to nest one HTML component within another." }, { "code": null, "e": 3693, "s": 3501, "text": "In the above code, we’ve included three core components — two dropdowns and a slider. These controller elements allow us to filter the chart data and create interactivity in the next section." }, { "code": null, "e": 3849, "s": 3693, "text": "Dash’s core components have callbacks to control the response for a user action. This feature is remarkable of why Dash apps outshine popular BI platforms." }, { "code": null, "e": 4035, "s": 3849, "text": "You can use this call back to control a chart re-rendering or to trigger a heavy analysis too. Check out my article on performing massive computation to use Dash apps along with Celery." }, { "code": null, "e": 4097, "s": 4035, "text": "Here in this post, we use callbacks to filter the chart data." }, { "code": null, "e": 4398, "s": 4097, "text": "The callback function is annotated with the @app.callback decorator. The first argument of this decorator is the Output component in the element tree. We need to specify the id of that element and the property we need to change. This property will change to the return value of the callback function." }, { "code": null, "e": 4663, "s": 4398, "text": "Then the decorated will accept any number of input arguments. Each will be tied to a core component in the same way we attached the output component. We can specify the id of the element and the property that emits the change value. Usually, this would be ‘value.’" }, { "code": null, "e": 4764, "s": 4663, "text": "Each input in the decorator should have a respective argument in the callback function’s definition." }, { "code": null, "e": 4927, "s": 4764, "text": "Finally, we moved the figure component inside the callback function. Every time we run the callback function, it creates a new figure instance and updates the UI." }, { "code": null, "e": 5046, "s": 4927, "text": "You can use the inline styling options available in Dash app. But with little CSS, you could have spectacular results." }, { "code": null, "e": 5103, "s": 5046, "text": "In-dash, you can style elements in three different ways." }, { "code": null, "e": 5252, "s": 5103, "text": "Every Dash component accepts a style argument. You can pass a dictionary and style any element. This is the most convenient way to style a Dash app." }, { "code": null, "e": 5519, "s": 5252, "text": "Alternatively, you can pass a class name attribute to any Dash component and use a separate CSS file to style it. You should place this CSS file inside an asset folder in your project directory. Dash will automatically pick it and apply its styles to the components." }, { "code": null, "e": 5756, "s": 5519, "text": "You can also use stylesheets from the internet. For instance, dash has this preconfigured stylesheet that comes with convenient utility classes. You can specify the style sheet and use its class names in elements to make them beautiful." }, { "code": null, "e": 5981, "s": 5756, "text": "Here is the complete styled source code of the application. We’ve used a local stylesheet and organized the HTML in a way to support styling. You can find the complete code and the local stylesheet in this GitHub repository." }, { "code": null, "e": 6121, "s": 5981, "text": "Your web app refreshes as you update your code with the above. And it may look like the below — your first version of a dazzling dashboard." }, { "code": null, "e": 6308, "s": 6121, "text": "plotly, Dash apps are an incredible tool for Python developers. Since most data science teams are not specializing in JavaScript, building dashboards with Dash saves a ton of their time." }, { "code": null, "e": 6479, "s": 6308, "text": "We can use Tableau, PowerBI, and similar BI platforms for data exploration and visualization. But Dash apps outshine them as they tightly integrate with the backend code." }, { "code": null, "e": 6660, "s": 6479, "text": "In this article, we explored the surface of Dash apps. I trust this would’ve given you the kickstart to build outstanding dashboards without worrying about scary technology stacks." }, { "code": null, "e": 6760, "s": 6660, "text": "As a next step, I strongly recommend exploring Dash’s documentation page and their example gallery." }, { "code": null, "e": 6874, "s": 6760, "text": "Thanks for the read, friend. It seems you and I have lots of common interests. Do check out my personal blog too." }, { "code": null, "e": 6949, "s": 6874, "text": "Say Hi to me on LinkedIn, Twitter, and Medium. I’ll break the ice for you." } ]
Create a list with random values in R - GeeksforGeeks
02 Sep, 2021 In this article, we are going to see how to create a list with random values in R programming language. The list can store data of multiple data type. A List can store multiple R objects like different types of atomic vectors such as character, numeric, logical. We can create a list using list() function. We need to pass vector(s) as parameters. Syntax : list_variable = list( vector 1,vector 2, . . . . , vector n ) We can generate random values using the sample function: Syntax : sample( vector , size=value , replace=T or F , prob=c(probability values for the vector) ) Note : Here prob is not mandatory to pass . prob refers the probability of values to be repeated . Example 1: With replace as FALSE R # creating a list with sample functionlst1 = list(sample(1 : 10, size = 10, replace = F)) # printing the list variableprint(lst1) Output : [[1]] [1] 7 4 9 1 2 3 10 6 8 5 Explanation : In the first step, we have created a list using the sample function for generating random values. In the sample function, we have taken vectors with 1 to 10 values as the first parameter. As the second parameter, we have taken size=10. Since we have taken size=10 it will generate 10 random values from the vector As the third parameter, we have taken replace=F. So, no value will be repeated. Finally, printing the list variable. Example 2: With replace as TRUE The main point here to remember is if we want to assign replace=FALSE, size is always less than or equal to vector size, otherwise, execution will be halted. R # creating a list with sample functionlst1 = list(sample(1 : 10, size = 15, replace = T)) # printing the list variableprint(lst1) Output : [[1]] [1] 1 7 8 7 10 2 3 7 8 1 9 7 9 1 1 Example 3: With prob attribute R # creating a list with sample functionlst1 = list(sample(1 : 5, size = 15, replace = T, prob = c(0.02, 0.2, 0.25, 0.5, 0.9))) # printing the list variableprint(lst1) Output : [[1]] [1] 3 3 5 5 5 4 4 4 3 5 4 4 3 2 5 Code explanation : In the fourth parameter, we have taken the prob attribute and assigned some probabilities for the vector values. The first value in the prob represents the probability for the first value of the vector. likewise v1=> p1 , v2 => p2. . . . . . vn => pn . Here v represents vector and p represents prob. In the output, we can observe that 1 is not there. Because we have given probability as 0.02 . Due to less probability, it is not generated by the r interpreter. Other than 1 all the values are generated and repeated since they have a greater probability as compared to 1. surindertarika1234 simmytarika5 R List-Programs R-List R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n02 Sep, 2021" }, { "code": null, "e": 25346, "s": 25242, "text": "In this article, we are going to see how to create a list with random values in R programming language." }, { "code": null, "e": 25590, "s": 25346, "text": "The list can store data of multiple data type. A List can store multiple R objects like different types of atomic vectors such as character, numeric, logical. We can create a list using list() function. We need to pass vector(s) as parameters." }, { "code": null, "e": 25661, "s": 25590, "text": "Syntax : list_variable = list( vector 1,vector 2, . . . . , vector n )" }, { "code": null, "e": 25718, "s": 25661, "text": "We can generate random values using the sample function:" }, { "code": null, "e": 25818, "s": 25718, "text": "Syntax : sample( vector , size=value , replace=T or F , prob=c(probability values for the vector) )" }, { "code": null, "e": 25917, "s": 25818, "text": "Note : Here prob is not mandatory to pass . prob refers the probability of values to be repeated ." }, { "code": null, "e": 25950, "s": 25917, "text": "Example 1: With replace as FALSE" }, { "code": null, "e": 25952, "s": 25950, "text": "R" }, { "code": "# creating a list with sample functionlst1 = list(sample(1 : 10, size = 10, replace = F)) # printing the list variableprint(lst1)", "e": 26082, "s": 25952, "text": null }, { "code": null, "e": 26091, "s": 26082, "text": "Output :" }, { "code": null, "e": 26132, "s": 26091, "text": "[[1]]\n [1] 7 4 9 1 2 3 10 6 8 5" }, { "code": null, "e": 26147, "s": 26132, "text": "Explanation : " }, { "code": null, "e": 26245, "s": 26147, "text": "In the first step, we have created a list using the sample function for generating random values." }, { "code": null, "e": 26335, "s": 26245, "text": "In the sample function, we have taken vectors with 1 to 10 values as the first parameter." }, { "code": null, "e": 26461, "s": 26335, "text": "As the second parameter, we have taken size=10. Since we have taken size=10 it will generate 10 random values from the vector" }, { "code": null, "e": 26541, "s": 26461, "text": "As the third parameter, we have taken replace=F. So, no value will be repeated." }, { "code": null, "e": 26578, "s": 26541, "text": "Finally, printing the list variable." }, { "code": null, "e": 26610, "s": 26578, "text": "Example 2: With replace as TRUE" }, { "code": null, "e": 26768, "s": 26610, "text": "The main point here to remember is if we want to assign replace=FALSE, size is always less than or equal to vector size, otherwise, execution will be halted." }, { "code": null, "e": 26770, "s": 26768, "text": "R" }, { "code": "# creating a list with sample functionlst1 = list(sample(1 : 10, size = 15, replace = T)) # printing the list variableprint(lst1)", "e": 26900, "s": 26770, "text": null }, { "code": null, "e": 26909, "s": 26900, "text": "Output :" }, { "code": null, "e": 26965, "s": 26909, "text": "[[1]]\n [1] 1 7 8 7 10 2 3 7 8 1 9 7 9 1 1" }, { "code": null, "e": 26997, "s": 26965, "text": "Example 3: With prob attribute " }, { "code": null, "e": 26999, "s": 26997, "text": "R" }, { "code": "# creating a list with sample functionlst1 = list(sample(1 : 5, size = 15, replace = T, prob = c(0.02, 0.2, 0.25, 0.5, 0.9))) # printing the list variableprint(lst1)", "e": 27201, "s": 26999, "text": null }, { "code": null, "e": 27210, "s": 27201, "text": "Output :" }, { "code": null, "e": 27251, "s": 27210, "text": "[[1]]\n [1] 3 3 5 5 5 4 4 4 3 5 4 4 3 2 5" }, { "code": null, "e": 27270, "s": 27251, "text": "Code explanation :" }, { "code": null, "e": 27571, "s": 27270, "text": "In the fourth parameter, we have taken the prob attribute and assigned some probabilities for the vector values. The first value in the prob represents the probability for the first value of the vector. likewise v1=> p1 , v2 => p2. . . . . . vn => pn . Here v represents vector and p represents prob." }, { "code": null, "e": 27844, "s": 27571, "text": "In the output, we can observe that 1 is not there. Because we have given probability as 0.02 . Due to less probability, it is not generated by the r interpreter. Other than 1 all the values are generated and repeated since they have a greater probability as compared to 1." }, { "code": null, "e": 27863, "s": 27844, "text": "surindertarika1234" }, { "code": null, "e": 27876, "s": 27863, "text": "simmytarika5" }, { "code": null, "e": 27892, "s": 27876, "text": "R List-Programs" }, { "code": null, "e": 27899, "s": 27892, "text": "R-List" }, { "code": null, "e": 27910, "s": 27899, "text": "R Language" }, { "code": null, "e": 27921, "s": 27910, "text": "R Programs" }, { "code": null, "e": 28019, "s": 27921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28071, "s": 28019, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28109, "s": 28071, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28144, "s": 28109, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28202, "s": 28144, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28251, "s": 28202, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28309, "s": 28251, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28358, "s": 28309, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28408, "s": 28358, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28451, "s": 28408, "text": "Replace Specific Characters in String in R" } ]
Python | Pattern Generation using time() module - GeeksforGeeks
08 Jun, 2020 This article aims to print patterns using the time() module in python.Examples: Input :5Output :5 patterns using time with 5 rows Input :4Output :5 patterns using time with 4 rows, but for diamond if youwill enter even number of rows, it will automatically do (row+1) Code : Python program to generate patterns # Print triangles by giving the number of stars: # For Diamond, an odd number of stars will give a better result,# If the number is even then for diamond pattern,# it will automatically do (row + 1): import time n = 5 print("----------Right Angled Triangle Type 1----------") def right_angle_triangle1(n): for i in range(1, n + 1): for j in range(i): time.sleep(0.05) print("*", end ="") print() right_angle_triangle1(n) print() print("----------Right Angled Triangle Type 2----------") def right_angle_triangle2(n): for i in range(1, n + 1): for j in range(n-i): time.sleep(0.05) print(" ", end ="") for k in range(i): time.sleep(0.05) print("*", end ="") print()right_angle_triangle2(n) print() print("----------Equilateral Triangle----------") def equilateral_triangle(n): for i in range(1, n + 1): for j in range(n-i): time.sleep(0.05) print(" ", end ="") for k in range(2 * i-1): time.sleep(0.05) print("*", end ="") print()equilateral_triangle(n) print() print("----------Square----------") def square(n): for i in range(1, n + 1): for j in range(1, n + 1): time.sleep(0.05) print("*", end ="") print()square(n) print() print("----------Diamond----------") def diamond(n): cell = n//2 + 1 for i in range(1, cell + 1): for j in range(cell-i): time.sleep(0.05) print(" ", end ="") for k in range(2 * i-1): time.sleep(0.05) print("*", end ="") print() for i in range(cell-1, 0, -1): for j in range(cell-i): time.sleep(0.05) print(" ", end ="") for k in range(2 * i-1): time.sleep(0.05) print("*", end ="") print()diamond(n) Output : ----------Right Angled Triangle Type 1---------- * ** *** **** ***** ----------Right Angled Triangle Type 2---------- * ** *** **** ***** ----------Equilateral Triangle---------- * *** ***** ******* ********* ----------Square---------- ***** ***** ***** ***** ***** ----------Diamond---------- * *** ***** *** * nidhi_biet pattern-printing Articles Python Python Programs pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GTest Framework HQL | Introduction Asymptotic Notations and how to calculate them How to use gotoxy() in codeblocks? Dockerizing a simple Django app Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read JSON file using Python
[ { "code": null, "e": 24517, "s": 24489, "text": "\n08 Jun, 2020" }, { "code": null, "e": 24597, "s": 24517, "text": "This article aims to print patterns using the time() module in python.Examples:" }, { "code": null, "e": 24647, "s": 24597, "text": "Input :5Output :5 patterns using time with 5 rows" }, { "code": null, "e": 24785, "s": 24647, "text": "Input :4Output :5 patterns using time with 4 rows, but for diamond if youwill enter even number of rows, it will automatically do (row+1)" }, { "code": null, "e": 24828, "s": 24785, "text": "Code : Python program to generate patterns" }, { "code": "# Print triangles by giving the number of stars: # For Diamond, an odd number of stars will give a better result,# If the number is even then for diamond pattern,# it will automatically do (row + 1): import time n = 5 print(\"----------Right Angled Triangle Type 1----------\") def right_angle_triangle1(n): for i in range(1, n + 1): for j in range(i): time.sleep(0.05) print(\"*\", end =\"\") print() right_angle_triangle1(n) print() print(\"----------Right Angled Triangle Type 2----------\") def right_angle_triangle2(n): for i in range(1, n + 1): for j in range(n-i): time.sleep(0.05) print(\" \", end =\"\") for k in range(i): time.sleep(0.05) print(\"*\", end =\"\") print()right_angle_triangle2(n) print() print(\"----------Equilateral Triangle----------\") def equilateral_triangle(n): for i in range(1, n + 1): for j in range(n-i): time.sleep(0.05) print(\" \", end =\"\") for k in range(2 * i-1): time.sleep(0.05) print(\"*\", end =\"\") print()equilateral_triangle(n) print() print(\"----------Square----------\") def square(n): for i in range(1, n + 1): for j in range(1, n + 1): time.sleep(0.05) print(\"*\", end =\"\") print()square(n) print() print(\"----------Diamond----------\") def diamond(n): cell = n//2 + 1 for i in range(1, cell + 1): for j in range(cell-i): time.sleep(0.05) print(\" \", end =\"\") for k in range(2 * i-1): time.sleep(0.05) print(\"*\", end =\"\") print() for i in range(cell-1, 0, -1): for j in range(cell-i): time.sleep(0.05) print(\" \", end =\"\") for k in range(2 * i-1): time.sleep(0.05) print(\"*\", end =\"\") print()diamond(n)", "e": 26783, "s": 24828, "text": null }, { "code": null, "e": 26792, "s": 26783, "text": "Output :" }, { "code": null, "e": 27135, "s": 26792, "text": "----------Right Angled Triangle Type 1----------\n*\n**\n***\n****\n*****\n\n----------Right Angled Triangle Type 2----------\n *\n **\n ***\n ****\n*****\n\n----------Equilateral Triangle----------\n *\n ***\n *****\n *******\n*********\n\n----------Square----------\n*****\n*****\n*****\n*****\n*****\n\n----------Diamond----------\n *\n ***\n*****\n ***\n *\n" }, { "code": null, "e": 27146, "s": 27135, "text": "nidhi_biet" }, { "code": null, "e": 27163, "s": 27146, "text": "pattern-printing" }, { "code": null, "e": 27172, "s": 27163, "text": "Articles" }, { "code": null, "e": 27179, "s": 27172, "text": "Python" }, { "code": null, "e": 27195, "s": 27179, "text": "Python Programs" }, { "code": null, "e": 27212, "s": 27195, "text": "pattern-printing" }, { "code": null, "e": 27310, "s": 27212, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27319, "s": 27310, "text": "Comments" }, { "code": null, "e": 27332, "s": 27319, "text": "Old Comments" }, { "code": null, "e": 27348, "s": 27332, "text": "GTest Framework" }, { "code": null, "e": 27367, "s": 27348, "text": "HQL | Introduction" }, { "code": null, "e": 27414, "s": 27367, "text": "Asymptotic Notations and how to calculate them" }, { "code": null, "e": 27449, "s": 27414, "text": "How to use gotoxy() in codeblocks?" }, { "code": null, "e": 27481, "s": 27449, "text": "Dockerizing a simple Django app" }, { "code": null, "e": 27531, "s": 27481, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27553, "s": 27531, "text": "Python map() function" }, { "code": null, "e": 27597, "s": 27553, "text": "How to get column names in Pandas dataframe" } ]
Tryit Editor v3.6 - Show React
import ReactDOM from "react-dom/client"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import Layout from "./pages/Layout"; import Home from "./pages/Home"; import Blogs from "./pages/Blogs"; import Contact from "./pages/Contact"; import NoPage from "./pages/NoPage"; export default function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Layout />}> <Route index element={<Home />} /> <Route path="blogs" element={<Blogs />} /> <Route path="contact" element={<Contact />} /> <Route path="*" element={<NoPage />} /> </Route> </Routes> </BrowserRouter> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<App />); <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
[ { "code": null, "e": 771, "s": 0, "text": "\nimport ReactDOM from \"react-dom/client\";\nimport { BrowserRouter, Routes, Route } from \"react-router-dom\";\nimport Layout from \"./pages/Layout\";\nimport Home from \"./pages/Home\";\nimport Blogs from \"./pages/Blogs\";\nimport Contact from \"./pages/Contact\";\nimport NoPage from \"./pages/NoPage\";\n\nexport default function App() {\n return (\n <BrowserRouter>\n <Routes>\n <Route path=\"/\" element={<Layout />}>\n <Route index element={<Home />} />\n <Route path=\"blogs\" element={<Blogs />} />\n <Route path=\"contact\" element={<Contact />} />\n <Route path=\"*\" element={<NoPage />} />\n </Route>\n </Routes>\n </BrowserRouter>\n );\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(<App />);\n\n" } ]
A data structure for n elements and O(1) operations - GeeksforGeeks
08 May, 2017 Propose a data structure for the following:The data structure would hold elements from 0 to n-1. There is no order on the elements (no ascending/descending order requirement) The complexity of the operations should be as follows:* Insertion of an element – O(1)* Deletion of an element – O(1)* Finding an element – O(1) We strongly recommend to minimize the browser and try this yourself first. A boolean array works here. Array will have value ‘true’ at ith index if i is present, and ‘false’ if absent. Initialization:We create an array of size n and initialize all elements as absent. void initialize(int n){ bool A[n]; for (int i = 0; i<n; i++) A[i] = {0}; // or A[n] = {false};} Insertion of an element: void insert(unsigned i){ /* set the value at index i to true */ A[i] = 1; // Or A[i] = true;} Deletion of an element: void delete(unsigned i){ /* make the value at index i to 0 */ A[i] = 0; // Or A[i] = false;} Finding an element: // Returns true if 'i' is present, else falsebool find(unsigned i){ return A[i];} As an exercise, change the data structure so that it holds values from 1 to n instead of 0 to n-1. This article is contributed by Sachin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Building Heap from Array Reversal algorithm for array rotation Program to find sum of elements in a given array Move all negative numbers to beginning and positive to end with constant extra space Find duplicates in O(n) time and O(1) extra space | Set 1 Count pairs with given sum Next Greater Element Remove duplicates from sorted array
[ { "code": null, "e": 24820, "s": 24792, "text": "\n08 May, 2017" }, { "code": null, "e": 24995, "s": 24820, "text": "Propose a data structure for the following:The data structure would hold elements from 0 to n-1. There is no order on the elements (no ascending/descending order requirement)" }, { "code": null, "e": 25140, "s": 24995, "text": "The complexity of the operations should be as follows:* Insertion of an element – O(1)* Deletion of an element – O(1)* Finding an element – O(1)" }, { "code": null, "e": 25215, "s": 25140, "text": "We strongly recommend to minimize the browser and try this yourself first." }, { "code": null, "e": 25325, "s": 25215, "text": "A boolean array works here. Array will have value ‘true’ at ith index if i is present, and ‘false’ if absent." }, { "code": null, "e": 25408, "s": 25325, "text": "Initialization:We create an array of size n and initialize all elements as absent." }, { "code": "void initialize(int n){ bool A[n]; for (int i = 0; i<n; i++) A[i] = {0}; // or A[n] = {false};}", "e": 25509, "s": 25408, "text": null }, { "code": null, "e": 25534, "s": 25509, "text": "Insertion of an element:" }, { "code": "void insert(unsigned i){ /* set the value at index i to true */ A[i] = 1; // Or A[i] = true;}", "e": 25632, "s": 25534, "text": null }, { "code": null, "e": 25656, "s": 25632, "text": "Deletion of an element:" }, { "code": "void delete(unsigned i){ /* make the value at index i to 0 */ A[i] = 0; // Or A[i] = false;}", "e": 25752, "s": 25656, "text": null }, { "code": null, "e": 25772, "s": 25752, "text": "Finding an element:" }, { "code": "// Returns true if 'i' is present, else falsebool find(unsigned i){ return A[i];}", "e": 25857, "s": 25772, "text": null }, { "code": null, "e": 25956, "s": 25857, "text": "As an exercise, change the data structure so that it holds values from 1 to n instead of 0 to n-1." }, { "code": null, "e": 26119, "s": 25956, "text": "This article is contributed by Sachin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 26126, "s": 26119, "text": "Arrays" }, { "code": null, "e": 26133, "s": 26126, "text": "Arrays" }, { "code": null, "e": 26231, "s": 26133, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26256, "s": 26231, "text": "Window Sliding Technique" }, { "code": null, "e": 26276, "s": 26256, "text": "Trapping Rain Water" }, { "code": null, "e": 26301, "s": 26276, "text": "Building Heap from Array" }, { "code": null, "e": 26339, "s": 26301, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 26388, "s": 26339, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 26473, "s": 26388, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 26531, "s": 26473, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 26558, "s": 26531, "text": "Count pairs with given sum" }, { "code": null, "e": 26579, "s": 26558, "text": "Next Greater Element" } ]
Algorithms from Scratch: Decision Tree | by Kurtis Pykes | Towards Data Science
Those of you familiar with my earlier writings would recall that I once wrote an overview of the Random Forest algorithm. A solid foundation on Decision trees is a prerequisite to understanding the inner workings of Random Forest; The Random forest builds multiple Decision tree’s and outputs the average over the predictions of each tree for regression problems, and in classification problems it outputs the relative majority of the predictions from each tree. towardsdatascience.com To build on the above story, I will be focusing much more on the Decision tree learning algorithm as it is a fundamental algorithm in the Machine Learning space. Many models base their structure on the Decision tree model such as the Random Forest and Gradient Boosted tree’s. Additionally, I will be doing a Python implementation of this algorithm from scratch to further expand our intuition on what is happening within our algorithm. Parametric Models: Used to make inferences about population parameters, however these inferences are not valid if all assumptions are not met. Non-Parametric Models: Do not assume that the data or population have any characteristic structure. Popular due to its intelligibility and simplicity, the Decision tree is one of the easiest algorithms to visualize and interpret which is handy when presenting results to a non-technical audience, as is often required in industry. If we simply consider a tree in a flowchart-like state, from root to leaves where the path to a leaf from the root defines decision rules on the features, then we already have a good level of intuition required to understand Decision tree learning. Unlike the first two algorithms we covered in the Algorithms from Scratch series (Linear Regression and Logistic Regression), the Decision tree algorithm is a non-parametric algorithm meaning that it does not make an assumption about the data or population. This does have an effect on our model since we are trading bias for variance in the model during training making the Decision tree much more prone to overfitting. In the field of Machine Learning there are two main Decision tree models. The one we use depends on the type of target variable we are attempting to predict: Classification Tree: A tree model employed to predict a target variable that takes a discrete value. Thereby, the leaf node represents a class and the branches represent conjunctions of the features that lead to those class labels. Regression Tree: A tree model employed to predict a target variable that takes a continuous value. Contrary to the classification tree, in the Regression tree, each leaf node contains a continuous value (i.e. a house price); The branches represent conjunctions of the features that lead to each continuous variable. Note: An umbrella term to refer to both procedures is Classification and Regression Tree (CART), first introduced by Breiman et al. in 1984. In Figure 1 we can see the structure that is followed by CART algorithms. Though this structure is set for both trees, there are some subtle differences between classification and regression trees such as the output from each tree; The classification tree returns mode class of the leaf node and the regression tree returns the mean. Another significant difference between the two algorithms is the criterion that we try to minimize when partitioning the feature space. Generally, we want to select the feature, j, and split-point, s, that best splits the feature space into 2 regions, but how this is measured in a regression tree and classification tree differs as is shown in Figure 2. Note: We will be building a Decision tree classifier with gini impurity as the criterion for the split. Consider all possible splits of feature j and split point sHaving found the best split, partition the data into 2 resulting regionsRepeat 1 and 2 until stopping criterion is reached Consider all possible splits of feature j and split point s Having found the best split, partition the data into 2 resulting regions Repeat 1 and 2 until stopping criterion is reached The pseudocode above demonstrates a phenomena known as recursion in computer science: A method of solving a problem where the solution depends on solutions to smaller instances of the same problem (Source: Wikipedia), and Binary splitting hence in some illustrations step 1 — 2 is referred to as recursive binary splitting. For this implementation we will be leveraging the following frameworks: NumPy (linear algebra and data manipulation) Pandas (data manipulation) Sci-kit Learn (machine learning) Graphviz (graph visualization software) View the full code here... github.com import numpy as np import pandas as pd import graphvizfrom sklearn.metrics import accuracy_scorefrom sklearn.datasets import load_irisfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.tree import export_graphvizfrom sklearn.model_selection import train_test_split The dataset we will use is the iris dataset from Scikit learn — See Documentation # loading the data setdataset = load_iris(as_frame=True)df= pd.DataFrame(data= dataset.data)# adding the target and target names to dataframetarget_zip= dict(zip(set(dataset.target), dataset.target_names))df["target"] = dataset.targetdf["target_names"] = df["target"].map(target_zip)print(df.shape)df.head()(150, 6) # Seperating to X and Y X = df.iloc[:, :4]y = df.iloc[:, -1]# splitting training and testX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, shuffle=True, random_state=24)dt = DecisionTreeClassifier()dt.fit(X_train, y_train)DecisionTreeClassifier()dot_data = export_graphviz(dt, out_file=None, feature_names=X.columns, class_names=dataset.target_names, filled=True, rounded=True, special_characters=True) graph = graphviz.Source(dot_data) graph sklearn_y_preds = dt.predict(X_test)print(f"Sklearn Implementation:\nACCURACY: {accuracy_score(y_test, sklearn_y_preds)}")Sklearn Implementation:ACCURACY: 0.9473684210526315 We are going to need to split our data into true and false index in response to the decision rule at a specific branch. If the condition of the decision rule is met, we say that branch is true (which we will denote as the left) and false (denoted as right). def partition(data, column, value): """ Partition the data into left (indicating True) and right (indicating false). Inputs data: The data to partition Outputs left: index of values that meet condition right: index of values that fail to meet the condition """ left = data[data[column] <= value].index right = data[data[column] > value].index return left, right To check if our function works correctly, we will perform a split on all of the data and pass it the best column and value manually to see if our data is separated with respect to the graph above. # performing a split on the root nodeleft_idx, right_idx = partition(X_train, "petal length (cm)", 2.45)print("[petal length (cm) <= 2.45]")# print results --> left_idx = 38 setosa | right index = 42 versicolor, 32 virginica print(f"left_idx: {dict(zip(np.unique(y_train.loc[left_idx], return_counts=True)[0], np.unique(y_train.loc[left_idx], return_counts=True)[1]))}\n\right_idx: {dict(zip(np.unique(y_train.loc[right_idx], return_counts=True)[0], np.unique(y_train.loc[right_idx], return_counts=True)[1]))}")[petal length (cm) <= 2.45]left_idx: {'setosa': 38}right_idx: {'versicolor': 42, 'virginica': 32} Perfect! Next, we need a criterion that we want to minimize. In this implementation we will be minimizing the gini impurity using a function called gini_impurity. Without getting to technical gini impurity simply measures how mixed our data is at a node; To help grasp this concept think of gold. When gold is impure it refers to the mixture of other substances within it, however when it is pure we can say there are 0 impurities (this isn't exactly true as refined gold up to 99.99% pure so technically there are still some impurities). The ideal is to nodes that are pure meaning that the target labels are separated into separate nodes. — To go into the technical details of gini impurity see here def gini_impurity(label, label_idx): """ A measure of how often a randomly chosen element from the set would be incorrectly labelled if it was randomly labelled according to the distribution of labels in the subset (Soure: Wikipedia) Inputs label: The class label available at current node Outputs impurity: The gini impurity of the node """ # the unique labels and counts in the data unique_label, unique_label_count = np.unique(label.loc[label_idx], return_counts=True) impurity = 1.0 for i in range(len(unique_label)): p_i = unique_label_count[i] / sum(unique_label_count) impurity -= p_i ** 2 return impurity If you scroll back up to Figure 4, you will see that the impurity at the root node is 0.663. Therefore, to determine whether our gini_impurity function is working correctly, we should see this number on output # Gini impurity of the first nodeimpurity = gini_impurity(y_train, y_train.index)impurity`0.6626275510204082 Great! To split at a feature (and value) we need to a way of quantifying what would result in the best outcome if we were to split at that point. Information gain is a useful way to quantify what feature and feature value to split on at each node. For each node of the tree, the information value “represents the expected amount of information that would be needed to specify whether a new instance should be classified yes or no, given that the example reached that node”. (Source: Wikipedia) def information_gain(label, left_idx, right_idx, impurity): """ For each node of the tree, the information gain "represents the expected amount of information that would be needed to specify whether a new instance should be classified yes or no, given that the example reached that node. (Source: Wikipedia) Inputs left: The values that met the conditions of the current node right: The values that failed to meet the conditions of the current noode gini_impurity: the uncertainty at the current node Outputs info_gain: The information gain at the node """ p = float(len(left_idx)) / (len(left_idx) + len(right_idx)) info_gain = impurity - p * gini_impurity(label, left_idx) - (1 - p) * gini_impurity(label, right_idx) return info_gain The best first split is the one that provides the most information gain. This process is repeated for each impure node until the tree is complete. (Source: Wikipedia) Based on the above statement, we can now see why petal length (cm) with the value 2.45 was selected as the first split. # testing info gain of the first split at root nodeinfo_gain = information_gain(y_train, left_idx, right_idx, impurity)info_gain0.33830322669608387# testing a random feature and value to see the information gainleft_idx, right_idx = partition(X_train, "petal width (cm)", 1.65)impurity = gini_impurity(y_train, y_train.index)info_gain = information_gain(y_train, left_idx, right_idx, impurity)info_gain0.25446843371494937 The above helper functions are now going to be brought into play. We had to manually select the feature and value before right? The next function will now automatically search the feature space and find the feature and feature value the best splits the data. def find_best_split(df, label, idx): """ Splits the data on the best column and value Input df: the training data label: the target label idx: the index of the data Output: best_gain: the max information gain best_col: the column that produced best information gain best_val: the value of the column that produced best information gain """ best_gain = 0 best_col = None best_value = None df = df.loc[idx] # converting training data to pandas dataframe label_idx = label.loc[idx].index # getting the index of the labels impurity = gini_impurity(label, label_idx) # determining the impurity at the current node # go through the columns and store the unique values in each column (no point testing on the same value twice) for col in df.columns: unique_values = set(df[col]) # loop thorugh each value and partition the data into true (left_index) and false (right_index) for value in unique_values: left_idx, right_idx = partition(df, col, value) # ignore if the index is empty (meaning there was no features that met the decision rule) if len(left_idx) == 0 or len(right_idx) == 0: continue # determine the info gain at the node info_gain = information_gain(label, left_idx, right_idx, impurity) # if the info gain is higher then our current best gain then that becomes the best gain if info_gain > best_gain: best_gain, best_col, best_value = info_gain, col, value return best_gain, best_col, best_valuefind_best_split(X_train, y_train, y_train.index)(0.33830322669608387, 'petal length (cm)', 1.9) Great, we have all the components we need for our algorithm to work. However, the above functions on only perform one split on our training data (the stump/root). # helper function to count valuesdef count(label, idx): """ Function that counts the unique values Input label: target labels idx: index of rows Output dict_label_count: Dictionary of label and counts """ unique_label, unique_label_counts = np.unique(label.loc[idx], return_counts=True) dict_label_count = dict(zip(unique_label, unique_label_counts)) return dict_label_count# check counts at first node to check it aligns with sci-kit learncount(y_train, y_train.index){'setosa': 38, 'versicolor': 42, 'virginica': 32} Here are some classes that we will use to store specific data from our Decision tree and print our tree. # https://github.com/random-forests/tutorials/blob/master/decision_tree.ipynbclass Leaf: """ A Leaf node classifies data. This holds a dictionary of class (e.g., "Apple") -> number of times it appears in the rows from the training data that reach this leaf. """ def __init__(self, label, idx): self.predictions = count(label, idx)# https://github.com/random-forests/tutorials/blob/master/decision_tree.ipynbclass Decision_Node: """ A Decision Node asks a question. This holds a reference to the question, and to the two child nodes. """ def __init__(self, column, value, true_branch, false_branch): self.column = column self.value = value self.true_branch = true_branch self.false_branch = false_branch# https://github.com/random-forests/tutorials/blob/master/decision_tree.ipynbdef print_tree(node, spacing=""): """ World's most elegant tree printing function. Input node: the tree node spacing: used to space creating tree like structure """ # Base case: we've reached a leaf if isinstance(node, Leaf): print (spacing + "Predict", node.predictions) return # Print the col and value at this node print(spacing + f"[{node.column} <= {node.value}]") # Call this function recursively on the true branch print (spacing + '--> True:') print_tree(node.true_branch, spacing + " ") # Call this function recursively on the false branch print (spacing + '--> False:') print_tree(node.false_branch, spacing + " ") For the algorithm to work we will need the splits to happen recursively until we meet a stopping criterion — in this case it’s until each leaf node is pure. def build_tree(df, label, idx): """ Recursively Builds the tree until is leaf is pure. Input df: the training data label: the target labels idx: the indexes Output best_col: the best column best_value: the value of the column that minimizes impurity true_branch: the true branch false_branch: the false branch """ best_gain, best_col, best_value = find_best_split(df, label, idx) if best_gain == 0: return Leaf(label, label.loc[idx].index) left_idx, right_idx = partition(df.loc[idx], best_col, best_value) true_branch = build_tree(df, label, left_idx) false_branch = build_tree(df, label, right_idx) return Decision_Node(best_col, best_value, true_branch, false_branch)my_tree = build_tree(X_train, y_train, X_train.index)print_tree(my_tree)[petal length (cm) <= 1.9]--> True: Predict {'setosa': 38}--> False: [petal width (cm) <= 1.6] --> True: [petal length (cm) <= 4.9] --> True: Predict {'versicolor': 40} --> False: [sepal length (cm) <= 6.0] --> True: [sepal width (cm) <= 2.2] --> True: Predict {'virginica': 1} --> False: Predict {'versicolor': 1} --> False: Predict {'virginica': 2} --> False: [petal length (cm) <= 4.8] --> True: [sepal width (cm) <= 3.0] --> True: Predict {'virginica': 3} --> False: Predict {'versicolor': 1} --> False: Predict {'virginica': 26} Super! Now you’ve seen how to implement a Decision tree from scratch and we have trained it on our training data. It does not stop there though, the purpose of building the algorithm in the first place is to automate the classification of new observations. The next section is dedicated to inference... def predict(test_data, tree): """ Classify unseen examples Inputs test_data: Unseen observation tree: tree that has been trained on training data Output The prediction of the observation. """ # Check if we are at a leaf node if isinstance(tree, Leaf): return max(tree.predictions) # the current feature_name and value feature_name, feature_value = tree.column, tree.value # pass the observation through the nodes recursively if test_data[feature_name] <= feature_value: return predict(test_data, tree.true_branch) else: return predict(test_data, tree.false_branch) To check if our function is operating correctly I will use one example observation. # taking one instance to test function example, example_target = X_test.iloc[6], y_test.iloc[6]example, example_target(sepal length (cm) 5.3 sepal width (cm) 3.7 petal length (cm) 1.5 petal width (cm) 0.2 predictions setosa Name: 48, dtype: object, 'setosa') When we apply our predict function to the example we should hope that the observation traverses the tree accordingly and outputs setosa, lets check... # if working correctly should output setosapredict(example, my_tree)'setosa' Supreme!! However, that is just to one example. If we want to apply this function to every observation in our test set we can use df.apply — see Documentation # create a new col of predictionsX_test["predictions"] = X_test.apply(predict, axis=1, args=(my_tree,)) Okay, here comes the moment of truth. We need to check if our algorithm returns the same predictions as the scikit learn model as a way of checking if we have implemented our algorithm correctly. We do this by simply doing sklearn_y_preds == X_true["predictions"] which returns a boolean array for each observation — in our case they are all true. print(f"Sklearn Implementation:\nACCURACY: {accuracy_score(y_test, sklearn_y_preds)}\n\n\My Implementation:\nACCURACY: {accuracy_score(y_test, X_test['predictions'])}")Sklearn Implementation:ACCURACY: 0.9736842105263158My Implementation:ACCURACY: 0.9736842105263158 Simple and easy to interpret Able to handle both numerical and categorical data Requires little data preparation Performs well with large datasets Built in feature selection Instability of trees (Changing something in the data can change everything) Lack of smoothness (Particular issue for regression problems) Prone to overfitting Establishing a good foundation of Decision trees will go a long way in understanding many other important Machine Learning algorithms. It is a very powerful algorithm that is often used as an ensemble model to win various Data Science competitions. Although its very easy to conceptualize, the decision tree is quite difficult to construct from scratch, hence why I’d always advocate for using established Machine Learning frameworks whenever possible. Thank you for reading to the end of the article! If you’d like to keep in contact with me, I am most accessible on LinkedIn.
[ { "code": null, "e": 635, "s": 172, "text": "Those of you familiar with my earlier writings would recall that I once wrote an overview of the Random Forest algorithm. A solid foundation on Decision trees is a prerequisite to understanding the inner workings of Random Forest; The Random forest builds multiple Decision tree’s and outputs the average over the predictions of each tree for regression problems, and in classification problems it outputs the relative majority of the predictions from each tree." }, { "code": null, "e": 658, "s": 635, "text": "towardsdatascience.com" }, { "code": null, "e": 1095, "s": 658, "text": "To build on the above story, I will be focusing much more on the Decision tree learning algorithm as it is a fundamental algorithm in the Machine Learning space. Many models base their structure on the Decision tree model such as the Random Forest and Gradient Boosted tree’s. Additionally, I will be doing a Python implementation of this algorithm from scratch to further expand our intuition on what is happening within our algorithm." }, { "code": null, "e": 1238, "s": 1095, "text": "Parametric Models: Used to make inferences about population parameters, however these inferences are not valid if all assumptions are not met." }, { "code": null, "e": 1338, "s": 1238, "text": "Non-Parametric Models: Do not assume that the data or population have any characteristic structure." }, { "code": null, "e": 1818, "s": 1338, "text": "Popular due to its intelligibility and simplicity, the Decision tree is one of the easiest algorithms to visualize and interpret which is handy when presenting results to a non-technical audience, as is often required in industry. If we simply consider a tree in a flowchart-like state, from root to leaves where the path to a leaf from the root defines decision rules on the features, then we already have a good level of intuition required to understand Decision tree learning." }, { "code": null, "e": 2239, "s": 1818, "text": "Unlike the first two algorithms we covered in the Algorithms from Scratch series (Linear Regression and Logistic Regression), the Decision tree algorithm is a non-parametric algorithm meaning that it does not make an assumption about the data or population. This does have an effect on our model since we are trading bias for variance in the model during training making the Decision tree much more prone to overfitting." }, { "code": null, "e": 2397, "s": 2239, "text": "In the field of Machine Learning there are two main Decision tree models. The one we use depends on the type of target variable we are attempting to predict:" }, { "code": null, "e": 2629, "s": 2397, "text": "Classification Tree: A tree model employed to predict a target variable that takes a discrete value. Thereby, the leaf node represents a class and the branches represent conjunctions of the features that lead to those class labels." }, { "code": null, "e": 2945, "s": 2629, "text": "Regression Tree: A tree model employed to predict a target variable that takes a continuous value. Contrary to the classification tree, in the Regression tree, each leaf node contains a continuous value (i.e. a house price); The branches represent conjunctions of the features that lead to each continuous variable." }, { "code": null, "e": 3086, "s": 2945, "text": "Note: An umbrella term to refer to both procedures is Classification and Regression Tree (CART), first introduced by Breiman et al. in 1984." }, { "code": null, "e": 3420, "s": 3086, "text": "In Figure 1 we can see the structure that is followed by CART algorithms. Though this structure is set for both trees, there are some subtle differences between classification and regression trees such as the output from each tree; The classification tree returns mode class of the leaf node and the regression tree returns the mean." }, { "code": null, "e": 3775, "s": 3420, "text": "Another significant difference between the two algorithms is the criterion that we try to minimize when partitioning the feature space. Generally, we want to select the feature, j, and split-point, s, that best splits the feature space into 2 regions, but how this is measured in a regression tree and classification tree differs as is shown in Figure 2." }, { "code": null, "e": 3879, "s": 3775, "text": "Note: We will be building a Decision tree classifier with gini impurity as the criterion for the split." }, { "code": null, "e": 4061, "s": 3879, "text": "Consider all possible splits of feature j and split point sHaving found the best split, partition the data into 2 resulting regionsRepeat 1 and 2 until stopping criterion is reached" }, { "code": null, "e": 4121, "s": 4061, "text": "Consider all possible splits of feature j and split point s" }, { "code": null, "e": 4194, "s": 4121, "text": "Having found the best split, partition the data into 2 resulting regions" }, { "code": null, "e": 4245, "s": 4194, "text": "Repeat 1 and 2 until stopping criterion is reached" }, { "code": null, "e": 4569, "s": 4245, "text": "The pseudocode above demonstrates a phenomena known as recursion in computer science: A method of solving a problem where the solution depends on solutions to smaller instances of the same problem (Source: Wikipedia), and Binary splitting hence in some illustrations step 1 — 2 is referred to as recursive binary splitting." }, { "code": null, "e": 4641, "s": 4569, "text": "For this implementation we will be leveraging the following frameworks:" }, { "code": null, "e": 4686, "s": 4641, "text": "NumPy (linear algebra and data manipulation)" }, { "code": null, "e": 4713, "s": 4686, "text": "Pandas (data manipulation)" }, { "code": null, "e": 4746, "s": 4713, "text": "Sci-kit Learn (machine learning)" }, { "code": null, "e": 4786, "s": 4746, "text": "Graphviz (graph visualization software)" }, { "code": null, "e": 4813, "s": 4786, "text": "View the full code here..." }, { "code": null, "e": 4824, "s": 4813, "text": "github.com" }, { "code": null, "e": 5098, "s": 4824, "text": "import numpy as np import pandas as pd import graphvizfrom sklearn.metrics import accuracy_scorefrom sklearn.datasets import load_irisfrom sklearn.tree import DecisionTreeClassifierfrom sklearn.tree import export_graphvizfrom sklearn.model_selection import train_test_split" }, { "code": null, "e": 5180, "s": 5098, "text": "The dataset we will use is the iris dataset from Scikit learn — See Documentation" }, { "code": null, "e": 5496, "s": 5180, "text": "# loading the data setdataset = load_iris(as_frame=True)df= pd.DataFrame(data= dataset.data)# adding the target and target names to dataframetarget_zip= dict(zip(set(dataset.target), dataset.target_names))df[\"target\"] = dataset.targetdf[\"target_names\"] = df[\"target\"].map(target_zip)print(df.shape)df.head()(150, 6)" }, { "code": null, "e": 6077, "s": 5496, "text": "# Seperating to X and Y X = df.iloc[:, :4]y = df.iloc[:, -1]# splitting training and testX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, shuffle=True, random_state=24)dt = DecisionTreeClassifier()dt.fit(X_train, y_train)DecisionTreeClassifier()dot_data = export_graphviz(dt, out_file=None, feature_names=X.columns, class_names=dataset.target_names, filled=True, rounded=True, special_characters=True) graph = graphviz.Source(dot_data) graph" }, { "code": null, "e": 6251, "s": 6077, "text": "sklearn_y_preds = dt.predict(X_test)print(f\"Sklearn Implementation:\\nACCURACY: {accuracy_score(y_test, sklearn_y_preds)}\")Sklearn Implementation:ACCURACY: 0.9473684210526315" }, { "code": null, "e": 6509, "s": 6251, "text": "We are going to need to split our data into true and false index in response to the decision rule at a specific branch. If the condition of the decision rule is met, we say that branch is true (which we will denote as the left) and false (denoted as right)." }, { "code": null, "e": 6914, "s": 6509, "text": "def partition(data, column, value): \"\"\" Partition the data into left (indicating True) and right (indicating false). Inputs data: The data to partition Outputs left: index of values that meet condition right: index of values that fail to meet the condition \"\"\" left = data[data[column] <= value].index right = data[data[column] > value].index return left, right" }, { "code": null, "e": 7111, "s": 6914, "text": "To check if our function works correctly, we will perform a split on all of the data and pass it the best column and value manually to see if our data is separated with respect to the graph above." }, { "code": null, "e": 7720, "s": 7111, "text": "# performing a split on the root nodeleft_idx, right_idx = partition(X_train, \"petal length (cm)\", 2.45)print(\"[petal length (cm) <= 2.45]\")# print results --> left_idx = 38 setosa | right index = 42 versicolor, 32 virginica print(f\"left_idx: {dict(zip(np.unique(y_train.loc[left_idx], return_counts=True)[0], np.unique(y_train.loc[left_idx], return_counts=True)[1]))}\\n\\right_idx: {dict(zip(np.unique(y_train.loc[right_idx], return_counts=True)[0], np.unique(y_train.loc[right_idx], return_counts=True)[1]))}\")[petal length (cm) <= 2.45]left_idx: {'setosa': 38}right_idx: {'versicolor': 42, 'virginica': 32}" }, { "code": null, "e": 7729, "s": 7720, "text": "Perfect!" }, { "code": null, "e": 8259, "s": 7729, "text": "Next, we need a criterion that we want to minimize. In this implementation we will be minimizing the gini impurity using a function called gini_impurity. Without getting to technical gini impurity simply measures how mixed our data is at a node; To help grasp this concept think of gold. When gold is impure it refers to the mixture of other substances within it, however when it is pure we can say there are 0 impurities (this isn't exactly true as refined gold up to 99.99% pure so technically there are still some impurities)." }, { "code": null, "e": 8422, "s": 8259, "text": "The ideal is to nodes that are pure meaning that the target labels are separated into separate nodes. — To go into the technical details of gini impurity see here" }, { "code": null, "e": 9102, "s": 8422, "text": "def gini_impurity(label, label_idx): \"\"\" A measure of how often a randomly chosen element from the set would be incorrectly labelled if it was randomly labelled according to the distribution of labels in the subset (Soure: Wikipedia) Inputs label: The class label available at current node Outputs impurity: The gini impurity of the node \"\"\" # the unique labels and counts in the data unique_label, unique_label_count = np.unique(label.loc[label_idx], return_counts=True) impurity = 1.0 for i in range(len(unique_label)): p_i = unique_label_count[i] / sum(unique_label_count) impurity -= p_i ** 2 return impurity" }, { "code": null, "e": 9312, "s": 9102, "text": "If you scroll back up to Figure 4, you will see that the impurity at the root node is 0.663. Therefore, to determine whether our gini_impurity function is working correctly, we should see this number on output" }, { "code": null, "e": 9421, "s": 9312, "text": "# Gini impurity of the first nodeimpurity = gini_impurity(y_train, y_train.index)impurity`0.6626275510204082" }, { "code": null, "e": 9428, "s": 9421, "text": "Great!" }, { "code": null, "e": 9915, "s": 9428, "text": "To split at a feature (and value) we need to a way of quantifying what would result in the best outcome if we were to split at that point. Information gain is a useful way to quantify what feature and feature value to split on at each node. For each node of the tree, the information value “represents the expected amount of information that would be needed to specify whether a new instance should be classified yes or no, given that the example reached that node”. (Source: Wikipedia)" }, { "code": null, "e": 10709, "s": 9915, "text": "def information_gain(label, left_idx, right_idx, impurity): \"\"\" For each node of the tree, the information gain \"represents the expected amount of information that would be needed to specify whether a new instance should be classified yes or no, given that the example reached that node. (Source: Wikipedia) Inputs left: The values that met the conditions of the current node right: The values that failed to meet the conditions of the current noode gini_impurity: the uncertainty at the current node Outputs info_gain: The information gain at the node \"\"\" p = float(len(left_idx)) / (len(left_idx) + len(right_idx)) info_gain = impurity - p * gini_impurity(label, left_idx) - (1 - p) * gini_impurity(label, right_idx) return info_gain" }, { "code": null, "e": 10876, "s": 10709, "text": "The best first split is the one that provides the most information gain. This process is repeated for each impure node until the tree is complete. (Source: Wikipedia)" }, { "code": null, "e": 10996, "s": 10876, "text": "Based on the above statement, we can now see why petal length (cm) with the value 2.45 was selected as the first split." }, { "code": null, "e": 11418, "s": 10996, "text": "# testing info gain of the first split at root nodeinfo_gain = information_gain(y_train, left_idx, right_idx, impurity)info_gain0.33830322669608387# testing a random feature and value to see the information gainleft_idx, right_idx = partition(X_train, \"petal width (cm)\", 1.65)impurity = gini_impurity(y_train, y_train.index)info_gain = information_gain(y_train, left_idx, right_idx, impurity)info_gain0.25446843371494937" }, { "code": null, "e": 11677, "s": 11418, "text": "The above helper functions are now going to be brought into play. We had to manually select the feature and value before right? The next function will now automatically search the feature space and find the feature and feature value the best splits the data." }, { "code": null, "e": 13411, "s": 11677, "text": "def find_best_split(df, label, idx): \"\"\" Splits the data on the best column and value Input df: the training data label: the target label idx: the index of the data Output: best_gain: the max information gain best_col: the column that produced best information gain best_val: the value of the column that produced best information gain \"\"\" best_gain = 0 best_col = None best_value = None df = df.loc[idx] # converting training data to pandas dataframe label_idx = label.loc[idx].index # getting the index of the labels impurity = gini_impurity(label, label_idx) # determining the impurity at the current node # go through the columns and store the unique values in each column (no point testing on the same value twice) for col in df.columns: unique_values = set(df[col]) # loop thorugh each value and partition the data into true (left_index) and false (right_index) for value in unique_values: left_idx, right_idx = partition(df, col, value) # ignore if the index is empty (meaning there was no features that met the decision rule) if len(left_idx) == 0 or len(right_idx) == 0: continue # determine the info gain at the node info_gain = information_gain(label, left_idx, right_idx, impurity) # if the info gain is higher then our current best gain then that becomes the best gain if info_gain > best_gain: best_gain, best_col, best_value = info_gain, col, value return best_gain, best_col, best_valuefind_best_split(X_train, y_train, y_train.index)(0.33830322669608387, 'petal length (cm)', 1.9)" }, { "code": null, "e": 13574, "s": 13411, "text": "Great, we have all the components we need for our algorithm to work. However, the above functions on only perform one split on our training data (the stump/root)." }, { "code": null, "e": 14139, "s": 13574, "text": "# helper function to count valuesdef count(label, idx): \"\"\" Function that counts the unique values Input label: target labels idx: index of rows Output dict_label_count: Dictionary of label and counts \"\"\" unique_label, unique_label_counts = np.unique(label.loc[idx], return_counts=True) dict_label_count = dict(zip(unique_label, unique_label_counts)) return dict_label_count# check counts at first node to check it aligns with sci-kit learncount(y_train, y_train.index){'setosa': 38, 'versicolor': 42, 'virginica': 32}" }, { "code": null, "e": 14244, "s": 14139, "text": "Here are some classes that we will use to store specific data from our Decision tree and print our tree." }, { "code": null, "e": 15852, "s": 14244, "text": "# https://github.com/random-forests/tutorials/blob/master/decision_tree.ipynbclass Leaf: \"\"\" A Leaf node classifies data. This holds a dictionary of class (e.g., \"Apple\") -> number of times it appears in the rows from the training data that reach this leaf. \"\"\" def __init__(self, label, idx): self.predictions = count(label, idx)# https://github.com/random-forests/tutorials/blob/master/decision_tree.ipynbclass Decision_Node: \"\"\" A Decision Node asks a question. This holds a reference to the question, and to the two child nodes. \"\"\" def __init__(self, column, value, true_branch, false_branch): self.column = column self.value = value self.true_branch = true_branch self.false_branch = false_branch# https://github.com/random-forests/tutorials/blob/master/decision_tree.ipynbdef print_tree(node, spacing=\"\"): \"\"\" World's most elegant tree printing function. Input node: the tree node spacing: used to space creating tree like structure \"\"\" # Base case: we've reached a leaf if isinstance(node, Leaf): print (spacing + \"Predict\", node.predictions) return # Print the col and value at this node print(spacing + f\"[{node.column} <= {node.value}]\") # Call this function recursively on the true branch print (spacing + '--> True:') print_tree(node.true_branch, spacing + \" \") # Call this function recursively on the false branch print (spacing + '--> False:') print_tree(node.false_branch, spacing + \" \")" }, { "code": null, "e": 16009, "s": 15852, "text": "For the algorithm to work we will need the splits to happen recursively until we meet a stopping criterion — in this case it’s until each leaf node is pure." }, { "code": null, "e": 17505, "s": 16009, "text": "def build_tree(df, label, idx): \"\"\" Recursively Builds the tree until is leaf is pure. Input df: the training data label: the target labels idx: the indexes Output best_col: the best column best_value: the value of the column that minimizes impurity true_branch: the true branch false_branch: the false branch \"\"\" best_gain, best_col, best_value = find_best_split(df, label, idx) if best_gain == 0: return Leaf(label, label.loc[idx].index) left_idx, right_idx = partition(df.loc[idx], best_col, best_value) true_branch = build_tree(df, label, left_idx) false_branch = build_tree(df, label, right_idx) return Decision_Node(best_col, best_value, true_branch, false_branch)my_tree = build_tree(X_train, y_train, X_train.index)print_tree(my_tree)[petal length (cm) <= 1.9]--> True: Predict {'setosa': 38}--> False: [petal width (cm) <= 1.6] --> True: [petal length (cm) <= 4.9] --> True: Predict {'versicolor': 40} --> False: [sepal length (cm) <= 6.0] --> True: [sepal width (cm) <= 2.2] --> True: Predict {'virginica': 1} --> False: Predict {'versicolor': 1} --> False: Predict {'virginica': 2} --> False: [petal length (cm) <= 4.8] --> True: [sepal width (cm) <= 3.0] --> True: Predict {'virginica': 3} --> False: Predict {'versicolor': 1} --> False: Predict {'virginica': 26}" }, { "code": null, "e": 17808, "s": 17505, "text": "Super! Now you’ve seen how to implement a Decision tree from scratch and we have trained it on our training data. It does not stop there though, the purpose of building the algorithm in the first place is to automate the classification of new observations. The next section is dedicated to inference..." }, { "code": null, "e": 18471, "s": 17808, "text": "def predict(test_data, tree): \"\"\" Classify unseen examples Inputs test_data: Unseen observation tree: tree that has been trained on training data Output The prediction of the observation. \"\"\" # Check if we are at a leaf node if isinstance(tree, Leaf): return max(tree.predictions) # the current feature_name and value feature_name, feature_value = tree.column, tree.value # pass the observation through the nodes recursively if test_data[feature_name] <= feature_value: return predict(test_data, tree.true_branch) else: return predict(test_data, tree.false_branch)" }, { "code": null, "e": 18555, "s": 18471, "text": "To check if our function is operating correctly I will use one example observation." }, { "code": null, "e": 18849, "s": 18555, "text": "# taking one instance to test function example, example_target = X_test.iloc[6], y_test.iloc[6]example, example_target(sepal length (cm) 5.3 sepal width (cm) 3.7 petal length (cm) 1.5 petal width (cm) 0.2 predictions setosa Name: 48, dtype: object, 'setosa')" }, { "code": null, "e": 19000, "s": 18849, "text": "When we apply our predict function to the example we should hope that the observation traverses the tree accordingly and outputs setosa, lets check..." }, { "code": null, "e": 19077, "s": 19000, "text": "# if working correctly should output setosapredict(example, my_tree)'setosa'" }, { "code": null, "e": 19236, "s": 19077, "text": "Supreme!! However, that is just to one example. If we want to apply this function to every observation in our test set we can use df.apply — see Documentation" }, { "code": null, "e": 19340, "s": 19236, "text": "# create a new col of predictionsX_test[\"predictions\"] = X_test.apply(predict, axis=1, args=(my_tree,))" }, { "code": null, "e": 19688, "s": 19340, "text": "Okay, here comes the moment of truth. We need to check if our algorithm returns the same predictions as the scikit learn model as a way of checking if we have implemented our algorithm correctly. We do this by simply doing sklearn_y_preds == X_true[\"predictions\"] which returns a boolean array for each observation — in our case they are all true." }, { "code": null, "e": 19954, "s": 19688, "text": "print(f\"Sklearn Implementation:\\nACCURACY: {accuracy_score(y_test, sklearn_y_preds)}\\n\\n\\My Implementation:\\nACCURACY: {accuracy_score(y_test, X_test['predictions'])}\")Sklearn Implementation:ACCURACY: 0.9736842105263158My Implementation:ACCURACY: 0.9736842105263158" }, { "code": null, "e": 19983, "s": 19954, "text": "Simple and easy to interpret" }, { "code": null, "e": 20034, "s": 19983, "text": "Able to handle both numerical and categorical data" }, { "code": null, "e": 20067, "s": 20034, "text": "Requires little data preparation" }, { "code": null, "e": 20101, "s": 20067, "text": "Performs well with large datasets" }, { "code": null, "e": 20128, "s": 20101, "text": "Built in feature selection" }, { "code": null, "e": 20204, "s": 20128, "text": "Instability of trees (Changing something in the data can change everything)" }, { "code": null, "e": 20266, "s": 20204, "text": "Lack of smoothness (Particular issue for regression problems)" }, { "code": null, "e": 20287, "s": 20266, "text": "Prone to overfitting" }, { "code": null, "e": 20740, "s": 20287, "text": "Establishing a good foundation of Decision trees will go a long way in understanding many other important Machine Learning algorithms. It is a very powerful algorithm that is often used as an ensemble model to win various Data Science competitions. Although its very easy to conceptualize, the decision tree is quite difficult to construct from scratch, hence why I’d always advocate for using established Machine Learning frameworks whenever possible." } ]
How to catch OverflowError Exception in Python?
When an arithmetic operation exceeds the limits of the variable type, an OverflowError is raised. Long integers allocate more space as values grow, so they end up raising MemoryError. Floating point exception handling is not standardized, however. Regular integers are converted to long values as needed. Given code is rewritten to catch exception as follows i=1 try: f = 3.0**i for i in range(100): print i, f f = f ** 2 except OverflowError as err: print 'Overflowed after ', f, err We get following OverflowError as output as follows C:/Users/TutorialsPoint1/~scratch_1.py Floating point values: 0 3.0 1 9.0 2 81.0 3 6561.0 4 43046721.0 5 1.85302018885e+15 6 3.43368382029e+30 7 1.17901845777e+61 8 1.39008452377e+122 9 1.93233498323e+244 Overflowed after 1.93233498323e+244 (34, 'Result too large')
[ { "code": null, "e": 1367, "s": 1062, "text": "When an arithmetic operation exceeds the limits of the variable type, an OverflowError is raised. Long integers allocate more space as values grow, so they end up raising MemoryError. Floating point exception handling is not standardized, however. Regular integers are converted to long values as needed." }, { "code": null, "e": 1421, "s": 1367, "text": "Given code is rewritten to catch exception as follows" }, { "code": null, "e": 1547, "s": 1421, "text": "i=1\ntry:\nf = 3.0**i\nfor i in range(100):\nprint i, f\nf = f ** 2\nexcept OverflowError as err:\nprint 'Overflowed after ', f, err" }, { "code": null, "e": 1599, "s": 1547, "text": "We get following OverflowError as output as follows" }, { "code": null, "e": 1867, "s": 1599, "text": "C:/Users/TutorialsPoint1/~scratch_1.py\nFloating point values:\n0 3.0\n1 9.0\n2 81.0\n3 6561.0\n4 43046721.0\n5 1.85302018885e+15\n6 3.43368382029e+30\n7 1.17901845777e+61\n8 1.39008452377e+122\n9 1.93233498323e+244\nOverflowed after 1.93233498323e+244 (34, 'Result too large')\n\n" } ]
How to use Boto3 to paginate through all objects of a S3 bucket present in AWS Glue
Problem Statement: Use boto3 library in Python to paginate through all objects of a S3 bucket from AWS Glue Data Catalog that is created in your account Step 1: Import boto3 and botocore exceptions to handle exceptions. Step 1: Import boto3 and botocore exceptions to handle exceptions. Step 2: max_items, page_size and starting_token are the optional parameters for this function, while bucket_name is the required parameter.max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination.page_size denotes the size of each page.starting_token helps to paginate, and it uses last key from a previous response. Step 2: max_items, page_size and starting_token are the optional parameters for this function, while bucket_name is the required parameter. max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination. max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination. page_size denotes the size of each page. page_size denotes the size of each page. starting_token helps to paginate, and it uses last key from a previous response. starting_token helps to paginate, and it uses last key from a previous response. Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session. Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session. Step 4: Create an AWS client for S3. Step 4: Create an AWS client for S3. Step 5: Create a paginator object that contains details of object versions of a S3 bucket using list_objects. Step 5: Create a paginator object that contains details of object versions of a S3 bucket using list_objects. Step 6: Call the paginate function and pass the max_items, page_size and starting_token as PaginationConfig parameter, while bucket_name as Bucket parameter. Step 6: Call the paginate function and pass the max_items, page_size and starting_token as PaginationConfig parameter, while bucket_name as Bucket parameter. Step 7: It returns the number of records based on max_size and page_size. Step 7: It returns the number of records based on max_size and page_size. Step 8: Handle the generic exception if something went wrong while paginating. Step 8: Handle the generic exception if something went wrong while paginating. Use the following code to paginate through all objects of a S3 bucket created in user account − import boto3 from botocore.exceptions import ClientError def paginate_through_all_objects_s3_bucket(bucket_name, max_items=None:int,page_size=None:int, starting_token=None:string): session = boto3.session.Session() s3_client = session.client('s3') try: paginator = s3_client.get_paginator('list_objects') response = paginator.paginate(Bucket=bucket_name, PaginationConfig={ 'MaxItems':max_items, 'PageSize':page_size, 'StartingToken':starting_token} ) return response except ClientError as e: raise Exception("boto3 client error in paginate_through_all_objects_s3_bucket: " + e.__str__()) except Exception as e: raise Exception("Unexpected error in paginate_through_all_objects_s3_bucket: " + e.__str__()) #1st Run a = paginate_through_all_objects_s3_bucket('s3-test-bucket',2,5) print(*a) #2nd Run for items in a: next_token = items['Contents'][max_items-1]['Key'] b = paginate_through_all_objects_s3_bucket('s3-test-bucket',2,5,next_token) print(*b) #1st Run {'ResponseMetadata': {'RequestId': '5AE5VF7RK', 'HostId': **************', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': **************', 'x-amz-request-id': '5AE5VF7RK', 'date': 'Sat, 03 Apr 2021 07:33:28 GMT', 'x-amz-bucket-region': 'us-east-1', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': True, 'Marker': '', 'Contents': [{'Key': 'analytics-s3i/param.json', 'LastModified': datetime.datetime(2020, 10, 29, 19, 50, 55, tzinfo=tzutc()), 'ETag': '"e6f6b8e02"', 'Size': 1554, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************0'}}, {'Key': 'analytics-s3i/params.json', 'LastModified': datetime.datetime(2021, 3, 10, 20, 10, 47, tzinfo=tzutc()), 'ETag': '"22a4bf70c1ed2612"', 'Size': 1756, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************************************'}}], 'Name': 's3-test-bucket', 'Prefix': '', 'MaxKeys': 5, 'EncodingType': 'url', 'CommonPrefixes': None} #2nd Run {'ResponseMetadata': {'RequestId': '5AEAWX', 'HostId': 'Uc********************************', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': *****************************', 'x-amz-request-id': '5AEAWX', 'date': 'Sat, 03 Apr 2021 07:33:28 GMT', 'x-amz-bucket-region': 'us-east-1', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': True, 'Marker': 'analytics-s3i/params.json', 'Contents': [{'Key': 'analytics-s3i/template.json', 'LastModified': datetime.datetime(2020, 10, 29, 19, 50, 55, tzinfo=tzutc()), 'ETag': '"3af411f"', 'Size': 21334, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************'}}, {'Key': 'analytics-s3i2/param.json', 'LastModified': datetime.datetime(2020, 11, 20, 17, 32, 45, tzinfo=tzutc()), 'ETag': '"04c29cf86888f99"', 'Size': 1695, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************'}}], 'Name': 's3-test-bucket', 'Prefix': '', 'MaxKeys': 5, 'EncodingType': 'url', 'CommonPrefixes': None}
[ { "code": null, "e": 1215, "s": 1062, "text": "Problem Statement: Use boto3 library in Python to paginate through all objects of a S3 bucket from AWS Glue Data Catalog that is created in your account" }, { "code": null, "e": 1282, "s": 1215, "text": "Step 1: Import boto3 and botocore exceptions to handle exceptions." }, { "code": null, "e": 1349, "s": 1282, "text": "Step 1: Import boto3 and botocore exceptions to handle exceptions." }, { "code": null, "e": 1784, "s": 1349, "text": "Step 2:\nmax_items, page_size and starting_token are the optional parameters for this function, while bucket_name is the required parameter.max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination.page_size denotes the size of each page.starting_token helps to paginate, and it uses last key from a previous response." }, { "code": null, "e": 1924, "s": 1784, "text": "Step 2:\nmax_items, page_size and starting_token are the optional parameters for this function, while bucket_name is the required parameter." }, { "code": null, "e": 2100, "s": 1924, "text": "max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination." }, { "code": null, "e": 2276, "s": 2100, "text": "max_items denote the total number of records to return. If the number of available records > max_items, then a NextToken will be provided in the response to resume pagination." }, { "code": null, "e": 2317, "s": 2276, "text": "page_size denotes the size of each page." }, { "code": null, "e": 2358, "s": 2317, "text": "page_size denotes the size of each page." }, { "code": null, "e": 2439, "s": 2358, "text": "starting_token helps to paginate, and it uses last key from a previous response." }, { "code": null, "e": 2520, "s": 2439, "text": "starting_token helps to paginate, and it uses last key from a previous response." }, { "code": null, "e": 2715, "s": 2520, "text": "Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session." }, { "code": null, "e": 2910, "s": 2715, "text": "Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session." }, { "code": null, "e": 2947, "s": 2910, "text": "Step 4: Create an AWS client for S3." }, { "code": null, "e": 2984, "s": 2947, "text": "Step 4: Create an AWS client for S3." }, { "code": null, "e": 3094, "s": 2984, "text": "Step 5: Create a paginator object that contains details of object versions of a S3 bucket using list_objects." }, { "code": null, "e": 3204, "s": 3094, "text": "Step 5: Create a paginator object that contains details of object versions of a S3 bucket using list_objects." }, { "code": null, "e": 3362, "s": 3204, "text": "Step 6: Call the paginate function and pass the max_items, page_size and starting_token as PaginationConfig parameter, while bucket_name as Bucket parameter." }, { "code": null, "e": 3520, "s": 3362, "text": "Step 6: Call the paginate function and pass the max_items, page_size and starting_token as PaginationConfig parameter, while bucket_name as Bucket parameter." }, { "code": null, "e": 3594, "s": 3520, "text": "Step 7: It returns the number of records based on max_size and page_size." }, { "code": null, "e": 3668, "s": 3594, "text": "Step 7: It returns the number of records based on max_size and page_size." }, { "code": null, "e": 3747, "s": 3668, "text": "Step 8: Handle the generic exception if something went wrong while paginating." }, { "code": null, "e": 3826, "s": 3747, "text": "Step 8: Handle the generic exception if something went wrong while paginating." }, { "code": null, "e": 3922, "s": 3826, "text": "Use the following code to paginate through all objects of a S3 bucket created in user account −" }, { "code": null, "e": 4948, "s": 3922, "text": "import boto3\nfrom botocore.exceptions import ClientError\n\ndef paginate_through_all_objects_s3_bucket(bucket_name, max_items=None:int,page_size=None:int, starting_token=None:string):\n session = boto3.session.Session()\n s3_client = session.client('s3')\n try:\n paginator = s3_client.get_paginator('list_objects')\n response = paginator.paginate(Bucket=bucket_name, PaginationConfig={\n 'MaxItems':max_items,\n 'PageSize':page_size,\n 'StartingToken':starting_token}\n )\n return response\n except ClientError as e:\n raise Exception(\"boto3 client error in paginate_through_all_objects_s3_bucket: \" + e.__str__())\n except Exception as e:\n raise Exception(\"Unexpected error in paginate_through_all_objects_s3_bucket: \" + e.__str__())\n\n#1st Run\na = paginate_through_all_objects_s3_bucket('s3-test-bucket',2,5)\nprint(*a)\n#2nd Run\nfor items in a:\nnext_token = items['Contents'][max_items-1]['Key']\nb = paginate_through_all_objects_s3_bucket('s3-test-bucket',2,5,next_token)\nprint(*b)" }, { "code": null, "e": 7135, "s": 4948, "text": "#1st Run\n{'ResponseMetadata': {'RequestId': '5AE5VF7RK', 'HostId': **************', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': **************', 'x-amz-request-id': '5AE5VF7RK', 'date': 'Sat, 03 Apr 2021 07:33:28 GMT', 'x-amz-bucket-region': 'us-east-1', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': True, 'Marker': '',\n'Contents': [{'Key': 'analytics-s3i/param.json', 'LastModified': datetime.datetime(2020, 10, 29, 19, 50, 55, tzinfo=tzutc()), 'ETag': '\"e6f6b8e02\"', 'Size': 1554, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************0'}}, {'Key': 'analytics-s3i/params.json', 'LastModified': datetime.datetime(2021, 3, 10, 20, 10, 47, tzinfo=tzutc()), 'ETag': '\"22a4bf70c1ed2612\"', 'Size': 1756, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************************************'}}], 'Name': 's3-test-bucket', 'Prefix': '', 'MaxKeys': 5, 'EncodingType': 'url', 'CommonPrefixes': None}\n\n#2nd Run\n{'ResponseMetadata': {'RequestId': '5AEAWX', 'HostId': 'Uc********************************', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amz-id-2': *****************************', 'x-amz-request-id': '5AEAWX', 'date': 'Sat, 03 Apr 2021 07:33:28 GMT', 'x-amz-bucket-region': 'us-east-1', 'content-type': 'application/xml', 'transfer-encoding': 'chunked', 'server': 'AmazonS3'}, 'RetryAttempts': 0}, 'IsTruncated': True, 'Marker': 'analytics-s3i/params.json',\n'Contents': [{'Key': 'analytics-s3i/template.json', 'LastModified': datetime.datetime(2020, 10, 29, 19, 50, 55, tzinfo=tzutc()), 'ETag': '\"3af411f\"', 'Size': 21334, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************'}}, {'Key': 'analytics-s3i2/param.json', 'LastModified': datetime.datetime(2020, 11, 20, 17, 32, 45, tzinfo=tzutc()), 'ETag': '\"04c29cf86888f99\"', 'Size': 1695, 'StorageClass': 'STANDARD', 'Owner': {'DisplayName': 'AWS.Development', 'ID': '92************************'}}], 'Name': 's3-test-bucket', 'Prefix': '', 'MaxKeys': 5, 'EncodingType': 'url', 'CommonPrefixes': None}" } ]
Handling Multi-Collinearity in ML Models | by Vishwa Pardeshi | Towards Data Science
Multiple linear regression models are used to model relationship between response/dependent variables and explanatory/independent variables. However, several problems such as multi-collinearity, correlation of variance of error terms, non-linearity impact the model’s interpretability. In this article, multi-collinearity, its effects and techniques to deal with it will be discussed. When the explanatory variables which are assumed to be independent of each other are revealed to be closely related to each other, this correlation is referred to as collinearity. When this correlation is observed for two or more explanatory variables, it is known multi-collinearity. Multi-collinearity is particularly undesirable because it impacts the interpretability of linear regression models. Linear regression model not only help establish the presence/absence of a relationship between the response and explanatory variables, it helps identify the individual effect of each explanatory variables on the response variable. Hence, due to the presence of multi-collinearity, it is difficult to isolate these individual effects. In other words, multi-collinearity can be viewed as a phenomenon where two or more explanatory variables are highly linearly related to each other to the extent that an explanatory variable can be predicted from another with a substantial accuracy. Due to the presence of collinearity/multi-collinearity, it becomes difficult to isolate the individual effects of explanatory variables on the response variable. Multi-collinearity results in the following: Uncertainty in coefficient estimates or unstable variance: Small changes (adding/removing rows/columns) in the data results in change of coefficients.Increased standard error: Reduces the accuracy of the estimates and increases the chances of detection.Decreased statistical significance: Due to increased standard error, t-statistic declines which negatively impacts the capability of detecting statistical significance in coefficient leading to type-II error.Reducing coefficient & p-value: The importance of the correlated explanatory variable is masked due to collinearity.Overfitting: Leads to overfitting as is indicated by the high variance problem. Uncertainty in coefficient estimates or unstable variance: Small changes (adding/removing rows/columns) in the data results in change of coefficients. Increased standard error: Reduces the accuracy of the estimates and increases the chances of detection. Decreased statistical significance: Due to increased standard error, t-statistic declines which negatively impacts the capability of detecting statistical significance in coefficient leading to type-II error. Reducing coefficient & p-value: The importance of the correlated explanatory variable is masked due to collinearity. Overfitting: Leads to overfitting as is indicated by the high variance problem. In addition to observing the model’s behavior for the above stated effects, mutli-collinearity is quantitatively captured in correlation values too. Thus, the following can be used: Correlation matrix: Pearson’s correlation between two variables in the data varies between -1 to 1. The two variables data type should be numeric for calculation of pearson’s correlation value. Here, the correlation matrix for the Auto MPG dataset using R. The column name contains string and hence is eliminated. The response variable is mpg which represents fuel consumption efficiency. #data = Auto#generate correlation matrix in Rcorrelation_matrix <- cor(Auto[, -which(names(Auto) == "name")]) The high correlation between cylinder and displacement, horsepower and weight can be observed. Additionally, there are several pairs of explanatory variables with high positive/negative correlation. Thus, there is multi-collinearity. However, as one would notice, going through the table and identifying these variables is tiresome for 8 variables and it will only get worse as the number of variables increase. Thus, a heatmap of correlation is a more intuitive representation of correlation. Heatmap of correlations: Heatmap of correlations helps visualize the data better by adjusting the color for positive and negative correlation and size for magnitude. In R, corrplot package can be used to create a heatmap of correlations. library(corrplot)corrplot(correlation_matrix, type = "upper", order = "hclust", tl.col = "black", tl.srt = 45) The heatmaps are definitely more intuitive & visual. However, it helps identify correlation between 2 variables strictly and fails to identify collinearity which exists between 3 or more variables, for which Variance Inflation Factor can be used. Variance Inflation Factor (VIF): VIF is the ratio of variance of coefficient estimate when fitting the full model divided by the variance of coefficient estimate if fit on its own. The minimum possible value is 1 which indicates no collinearity. If value exceeds 5, then collinearity should be addressed. library(rms)multiple.lm <- lm(mpg ~ . -name, data = Auto)summary(multiple.lm)vif(multiple.lm) The VIF value for cylinders, displacement, horsepower, and weight are way higher than 5 and hence should be handled as the collinearity is high in the data. Multi-collinearity can be handled with the following two methods. Note that this correlation between independent variable leads to data redundancy, eliminating which can help get rid of multi-collinearity. Introduce penalization or remove highly correlated variables: Use lasso and ridge regression to eliminate variables which provide information which is redundant. This can also be achieved by observing the VIF.Combine highly correlated variables: Since the collinear variables contain redundant information, combining them into a single variable using methods such as PCA to generate independent variables. Introduce penalization or remove highly correlated variables: Use lasso and ridge regression to eliminate variables which provide information which is redundant. This can also be achieved by observing the VIF. Combine highly correlated variables: Since the collinear variables contain redundant information, combining them into a single variable using methods such as PCA to generate independent variables. For Autompg linear regression model implemented in R, check out this Github repository. This repository explores multicollinearity along with interaction terms and non-linear transformations for linear regression models. Introduction to Statistical Learning in R by Gareth James, Daniela Witten, Trevor Hastie, Robert Tibshirani.
[ { "code": null, "e": 556, "s": 171, "text": "Multiple linear regression models are used to model relationship between response/dependent variables and explanatory/independent variables. However, several problems such as multi-collinearity, correlation of variance of error terms, non-linearity impact the model’s interpretability. In this article, multi-collinearity, its effects and techniques to deal with it will be discussed." }, { "code": null, "e": 841, "s": 556, "text": "When the explanatory variables which are assumed to be independent of each other are revealed to be closely related to each other, this correlation is referred to as collinearity. When this correlation is observed for two or more explanatory variables, it is known multi-collinearity." }, { "code": null, "e": 1188, "s": 841, "text": "Multi-collinearity is particularly undesirable because it impacts the interpretability of linear regression models. Linear regression model not only help establish the presence/absence of a relationship between the response and explanatory variables, it helps identify the individual effect of each explanatory variables on the response variable." }, { "code": null, "e": 1540, "s": 1188, "text": "Hence, due to the presence of multi-collinearity, it is difficult to isolate these individual effects. In other words, multi-collinearity can be viewed as a phenomenon where two or more explanatory variables are highly linearly related to each other to the extent that an explanatory variable can be predicted from another with a substantial accuracy." }, { "code": null, "e": 1702, "s": 1540, "text": "Due to the presence of collinearity/multi-collinearity, it becomes difficult to isolate the individual effects of explanatory variables on the response variable." }, { "code": null, "e": 1747, "s": 1702, "text": "Multi-collinearity results in the following:" }, { "code": null, "e": 2404, "s": 1747, "text": "Uncertainty in coefficient estimates or unstable variance: Small changes (adding/removing rows/columns) in the data results in change of coefficients.Increased standard error: Reduces the accuracy of the estimates and increases the chances of detection.Decreased statistical significance: Due to increased standard error, t-statistic declines which negatively impacts the capability of detecting statistical significance in coefficient leading to type-II error.Reducing coefficient & p-value: The importance of the correlated explanatory variable is masked due to collinearity.Overfitting: Leads to overfitting as is indicated by the high variance problem." }, { "code": null, "e": 2555, "s": 2404, "text": "Uncertainty in coefficient estimates or unstable variance: Small changes (adding/removing rows/columns) in the data results in change of coefficients." }, { "code": null, "e": 2659, "s": 2555, "text": "Increased standard error: Reduces the accuracy of the estimates and increases the chances of detection." }, { "code": null, "e": 2868, "s": 2659, "text": "Decreased statistical significance: Due to increased standard error, t-statistic declines which negatively impacts the capability of detecting statistical significance in coefficient leading to type-II error." }, { "code": null, "e": 2985, "s": 2868, "text": "Reducing coefficient & p-value: The importance of the correlated explanatory variable is masked due to collinearity." }, { "code": null, "e": 3065, "s": 2985, "text": "Overfitting: Leads to overfitting as is indicated by the high variance problem." }, { "code": null, "e": 3247, "s": 3065, "text": "In addition to observing the model’s behavior for the above stated effects, mutli-collinearity is quantitatively captured in correlation values too. Thus, the following can be used:" }, { "code": null, "e": 3267, "s": 3247, "text": "Correlation matrix:" }, { "code": null, "e": 3441, "s": 3267, "text": "Pearson’s correlation between two variables in the data varies between -1 to 1. The two variables data type should be numeric for calculation of pearson’s correlation value." }, { "code": null, "e": 3636, "s": 3441, "text": "Here, the correlation matrix for the Auto MPG dataset using R. The column name contains string and hence is eliminated. The response variable is mpg which represents fuel consumption efficiency." }, { "code": null, "e": 3746, "s": 3636, "text": "#data = Auto#generate correlation matrix in Rcorrelation_matrix <- cor(Auto[, -which(names(Auto) == \"name\")])" }, { "code": null, "e": 3980, "s": 3746, "text": "The high correlation between cylinder and displacement, horsepower and weight can be observed. Additionally, there are several pairs of explanatory variables with high positive/negative correlation. Thus, there is multi-collinearity." }, { "code": null, "e": 4240, "s": 3980, "text": "However, as one would notice, going through the table and identifying these variables is tiresome for 8 variables and it will only get worse as the number of variables increase. Thus, a heatmap of correlation is a more intuitive representation of correlation." }, { "code": null, "e": 4265, "s": 4240, "text": "Heatmap of correlations:" }, { "code": null, "e": 4406, "s": 4265, "text": "Heatmap of correlations helps visualize the data better by adjusting the color for positive and negative correlation and size for magnitude." }, { "code": null, "e": 4478, "s": 4406, "text": "In R, corrplot package can be used to create a heatmap of correlations." }, { "code": null, "e": 4589, "s": 4478, "text": "library(corrplot)corrplot(correlation_matrix, type = \"upper\", order = \"hclust\", tl.col = \"black\", tl.srt = 45)" }, { "code": null, "e": 4836, "s": 4589, "text": "The heatmaps are definitely more intuitive & visual. However, it helps identify correlation between 2 variables strictly and fails to identify collinearity which exists between 3 or more variables, for which Variance Inflation Factor can be used." }, { "code": null, "e": 5141, "s": 4836, "text": "Variance Inflation Factor (VIF): VIF is the ratio of variance of coefficient estimate when fitting the full model divided by the variance of coefficient estimate if fit on its own. The minimum possible value is 1 which indicates no collinearity. If value exceeds 5, then collinearity should be addressed." }, { "code": null, "e": 5235, "s": 5141, "text": "library(rms)multiple.lm <- lm(mpg ~ . -name, data = Auto)summary(multiple.lm)vif(multiple.lm)" }, { "code": null, "e": 5392, "s": 5235, "text": "The VIF value for cylinders, displacement, horsepower, and weight are way higher than 5 and hence should be handled as the collinearity is high in the data." }, { "code": null, "e": 5598, "s": 5392, "text": "Multi-collinearity can be handled with the following two methods. Note that this correlation between independent variable leads to data redundancy, eliminating which can help get rid of multi-collinearity." }, { "code": null, "e": 6004, "s": 5598, "text": "Introduce penalization or remove highly correlated variables: Use lasso and ridge regression to eliminate variables which provide information which is redundant. This can also be achieved by observing the VIF.Combine highly correlated variables: Since the collinear variables contain redundant information, combining them into a single variable using methods such as PCA to generate independent variables." }, { "code": null, "e": 6214, "s": 6004, "text": "Introduce penalization or remove highly correlated variables: Use lasso and ridge regression to eliminate variables which provide information which is redundant. This can also be achieved by observing the VIF." }, { "code": null, "e": 6411, "s": 6214, "text": "Combine highly correlated variables: Since the collinear variables contain redundant information, combining them into a single variable using methods such as PCA to generate independent variables." }, { "code": null, "e": 6632, "s": 6411, "text": "For Autompg linear regression model implemented in R, check out this Github repository. This repository explores multicollinearity along with interaction terms and non-linear transformations for linear regression models." } ]
Build a Simple Neural Network using Numpy | by Ramesh Paudel, Ph.D. | Towards Data Science
In this article, we will discuss how to make a simple neural network using NumPy. Import Libraries Import Libraries First, we will import all the packages that we will need. We will need numpy, h5py (for loading dataset stored in H5 file), and matplotlib (for plotting). import numpy as npimport matplotlib.pyplot as pltimport h5py 2. Data Preparation The data is available in (“.h5”) format and contain training and test set of images labeled as cat or non-cat. The dataset is available in github repo for download. Load the dataset using the following function: def load_dataset(): train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r") train_x = np.array(train_dataset["train_set_x"][:]) train_y = np.array(train_dataset["train_set_y"][:])test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r") test_x = np.array(test_dataset["test_set_x"][:]) test_y = np.array(test_dataset["test_set_y"][:])classes = np.array(test_dataset["list_classes"][:]) train_y = train_y.reshape((1, train_y.shape[0])) test_y = test_y.reshape((1, test_y.shape[0])) return train_x, train_y, test_x, test_y, classes We can analyze the data by looking at their shape. train_x, train_y, test_x, test_y, classes = load_dataset()print ("Train X shape: " + str(train_x.shape))print ("Train Y shape: " + str(train_y.shape))print ("Test X shape: " + str(test_x.shape))print ("Test Y shape: " + str(test_y.shape)) We have 209 train image where each image is square (height = 64px) and (width = 64px) and have 3 channels (RGB). Similarly, we have 50 test images of the same dimension. Let us visualize the image. You can change the index to see different images. # change index for another imageindex = 2plt.imshow(train_x[index]) Data Preprocessing: The common data preprocessing for image data involves: Figure out the dimensions and shapes of the data (m_train, m_test, num_px, ...)Reshape the datasets such that each example is now a vector of size (height * width * channel, 1)“Standardize” the data Figure out the dimensions and shapes of the data (m_train, m_test, num_px, ...) Reshape the datasets such that each example is now a vector of size (height * width * channel, 1) “Standardize” the data First, we need to flatten the image. This can be done by reshaping the images of shape (height, width, channel) in a numpy-array of shape (height ∗ width ∗channel, 1). train_x = train_x.reshape(train_x.shape[0], -1).Ttest_x = test_x.reshape(test_x.shape[0], -1).Tprint ("Train X shape: " + str(train_x.shape))print ("Train Y shape: " + str(train_y.shape))print ("Test X shape: " + str(test_x.shape))print ("Test Y shape: " + str(test_y.shape)) Standardize the data: The common preprocessing step in machine learning is to center and standardize the dataset. For the given picture datasets, it can be done by dividing every row of the dataset by 255 (the maximum value of a pixel channel). train_x = train_x/255.test_x = test_x/255. Now we will build a simple neural network model that can correctly classify pictures as cat or non-cat. We will build a Neural Network as shown in the following figure. Key steps: The main steps for building a Neural Network are: Define the model structure (like number of input features, number of ouput, etc.)Initialize the model’s parameters (weight and bias)Loop: Define the model structure (like number of input features, number of ouput, etc.) Initialize the model’s parameters (weight and bias) Loop: Calculate current loss (forward propagation) Calculate current gradient (backward propagation) Update parameters (gradient descent) 3.1 Activation Function The sigmoid activation function is given by The sigmoid activation function can be calculated using np.exp(). def sigmoid(z): return 1/(1+np.exp(-z)) 3.2 Initializing Parameters We need to initialize the parameter w (weight) and b (bias). In the following example, w is initialized as a vector of random numbers using np.random.randn() while b is initialize zero. def initialize_parameters(dim): w = np.random.randn(dim, 1)*0.01 b = 0 return w, b 3.3 Forward and Back Propagation Once the parameters are initialized, we can do the “forward” and “backward” propagation steps for learning the parameters. Set of input features (X) are given. We will calculate the activation function as given below. We will compute the cost as given below. Finally, we will calculate the gradients as follows (back propagation). def propagate(w, b, X, Y): m = X.shape[1] #calculate activation function A = sigmoid(np.dot(w.T, X)+b) #find the cost cost = (-1/m) * np.sum(Y * np.log(A) + (1 - Y) * (np.log(1 - A))) #find gradient (back propagation) dw = (1/m) * np.dot(X, (A-Y).T) db = (1/m) * np.sum(A-Y) cost = np.squeeze(cost) grads = {"dw": dw, "db": db} return grads, cost 3.4 Optimization After initializing the parameters, computing the cost function, and calculating gradients, we can now update the parameters using gradient descent. def gradient_descent(w, b, X, Y, iterations, learning_rate): costs = [] for i in range(iterations): grads, cost = propagate(w, b, X, Y) #update parameters w = w - learning_rate * grads["dw"] b = b - learning_rate * grads["db"] costs.append(cost) if i % 500 == 0: print ("Cost after iteration %i: %f" %(i, cost)) params = {"w": w, "b": b} return params, costs 3.5 Prediction Using the learned parameter w and b, we can predict the labels for a train or test examples. For prediction we first need to calculate the activation function given as follows. Then convert the output (prediction) into 0 (if A <= 0.5) or 1 (if A > 0.5) and store in y_pred. def predict(w, b, X): # number of example m = X.shape[1] y_pred = np.zeros((1,m)) w = w.reshape(X.shape[0], 1) A = sigmoid(np.dot(w.T, X)+b) for i in range(A.shape[1]): y_pred[0,i] = 1 if A[0,i] >0.5 else 0 pass return y_pred 3.6 Final Model We can put together all the building block in the right order to make a neural network model. def model(train_x, train_y, test_x, test_y, iterations, learning_rate): w, b = initialize_parameters(train_x.shape[0]) parameters, costs = gradient_descent(w, b, train_x, train_y, iterations, learning_rate) w = parameters["w"] b = parameters["b"] # predict train_pred_y = predict(w, b, train_x) test_pred_y = predict(w, b, test_x) print("Train Acc: {} %".format(100 - np.mean(np.abs(train_pred_y - train_y)) * 100)) print("Test Acc: {} %".format(100 - np.mean(np.abs(test_pred_y - test_y)) * 100)) return costs We can use the following code to train and predict on the image dataset using the model built above. We will use the learning_rate of 0.005 and train the model for 2000 iterations. costs = model(train_x, train_y, test_x, test_y, iterations = 2000, learning_rate = 0.005) Training accuracy is around 99% which means that our model is working and fit the training data with high probability. Test accuracy is around 70%. Given the simple model and the small dataset, we can consider it as a good model. Finally, we can plot the cost and see how the model was learning parameters. plt.plot(costs)plt.ylabel('cost')plt.xlabel('iterations')plt.title("Learning rate =" + str(d["learning_rate"]))plt.show() We can see the cost decreasing in each iteration which shows that the parameters are being learned. In the next article, we will discuss how to make a neural with a hidden layer. Be a Medium member here and support independent writing for $5/month and get full access to every story on Medium.
[ { "code": null, "e": 254, "s": 172, "text": "In this article, we will discuss how to make a simple neural network using NumPy." }, { "code": null, "e": 271, "s": 254, "text": "Import Libraries" }, { "code": null, "e": 288, "s": 271, "text": "Import Libraries" }, { "code": null, "e": 443, "s": 288, "text": "First, we will import all the packages that we will need. We will need numpy, h5py (for loading dataset stored in H5 file), and matplotlib (for plotting)." }, { "code": null, "e": 504, "s": 443, "text": "import numpy as npimport matplotlib.pyplot as pltimport h5py" }, { "code": null, "e": 524, "s": 504, "text": "2. Data Preparation" }, { "code": null, "e": 736, "s": 524, "text": "The data is available in (“.h5”) format and contain training and test set of images labeled as cat or non-cat. The dataset is available in github repo for download. Load the dataset using the following function:" }, { "code": null, "e": 1311, "s": 736, "text": "def load_dataset(): train_dataset = h5py.File('datasets/train_catvnoncat.h5', \"r\") train_x = np.array(train_dataset[\"train_set_x\"][:]) train_y = np.array(train_dataset[\"train_set_y\"][:])test_dataset = h5py.File('datasets/test_catvnoncat.h5', \"r\") test_x = np.array(test_dataset[\"test_set_x\"][:]) test_y = np.array(test_dataset[\"test_set_y\"][:])classes = np.array(test_dataset[\"list_classes\"][:]) train_y = train_y.reshape((1, train_y.shape[0])) test_y = test_y.reshape((1, test_y.shape[0])) return train_x, train_y, test_x, test_y, classes" }, { "code": null, "e": 1362, "s": 1311, "text": "We can analyze the data by looking at their shape." }, { "code": null, "e": 1601, "s": 1362, "text": "train_x, train_y, test_x, test_y, classes = load_dataset()print (\"Train X shape: \" + str(train_x.shape))print (\"Train Y shape: \" + str(train_y.shape))print (\"Test X shape: \" + str(test_x.shape))print (\"Test Y shape: \" + str(test_y.shape))" }, { "code": null, "e": 1771, "s": 1601, "text": "We have 209 train image where each image is square (height = 64px) and (width = 64px) and have 3 channels (RGB). Similarly, we have 50 test images of the same dimension." }, { "code": null, "e": 1849, "s": 1771, "text": "Let us visualize the image. You can change the index to see different images." }, { "code": null, "e": 1917, "s": 1849, "text": "# change index for another imageindex = 2plt.imshow(train_x[index])" }, { "code": null, "e": 1992, "s": 1917, "text": "Data Preprocessing: The common data preprocessing for image data involves:" }, { "code": null, "e": 2191, "s": 1992, "text": "Figure out the dimensions and shapes of the data (m_train, m_test, num_px, ...)Reshape the datasets such that each example is now a vector of size (height * width * channel, 1)“Standardize” the data" }, { "code": null, "e": 2271, "s": 2191, "text": "Figure out the dimensions and shapes of the data (m_train, m_test, num_px, ...)" }, { "code": null, "e": 2369, "s": 2271, "text": "Reshape the datasets such that each example is now a vector of size (height * width * channel, 1)" }, { "code": null, "e": 2392, "s": 2369, "text": "“Standardize” the data" }, { "code": null, "e": 2560, "s": 2392, "text": "First, we need to flatten the image. This can be done by reshaping the images of shape (height, width, channel) in a numpy-array of shape (height ∗ width ∗channel, 1)." }, { "code": null, "e": 2836, "s": 2560, "text": "train_x = train_x.reshape(train_x.shape[0], -1).Ttest_x = test_x.reshape(test_x.shape[0], -1).Tprint (\"Train X shape: \" + str(train_x.shape))print (\"Train Y shape: \" + str(train_y.shape))print (\"Test X shape: \" + str(test_x.shape))print (\"Test Y shape: \" + str(test_y.shape))" }, { "code": null, "e": 3081, "s": 2836, "text": "Standardize the data: The common preprocessing step in machine learning is to center and standardize the dataset. For the given picture datasets, it can be done by dividing every row of the dataset by 255 (the maximum value of a pixel channel)." }, { "code": null, "e": 3124, "s": 3081, "text": "train_x = train_x/255.test_x = test_x/255." }, { "code": null, "e": 3228, "s": 3124, "text": "Now we will build a simple neural network model that can correctly classify pictures as cat or non-cat." }, { "code": null, "e": 3293, "s": 3228, "text": "We will build a Neural Network as shown in the following figure." }, { "code": null, "e": 3354, "s": 3293, "text": "Key steps: The main steps for building a Neural Network are:" }, { "code": null, "e": 3492, "s": 3354, "text": "Define the model structure (like number of input features, number of ouput, etc.)Initialize the model’s parameters (weight and bias)Loop:" }, { "code": null, "e": 3574, "s": 3492, "text": "Define the model structure (like number of input features, number of ouput, etc.)" }, { "code": null, "e": 3626, "s": 3574, "text": "Initialize the model’s parameters (weight and bias)" }, { "code": null, "e": 3632, "s": 3626, "text": "Loop:" }, { "code": null, "e": 3677, "s": 3632, "text": "Calculate current loss (forward propagation)" }, { "code": null, "e": 3727, "s": 3677, "text": "Calculate current gradient (backward propagation)" }, { "code": null, "e": 3764, "s": 3727, "text": "Update parameters (gradient descent)" }, { "code": null, "e": 3788, "s": 3764, "text": "3.1 Activation Function" }, { "code": null, "e": 3832, "s": 3788, "text": "The sigmoid activation function is given by" }, { "code": null, "e": 3898, "s": 3832, "text": "The sigmoid activation function can be calculated using np.exp()." }, { "code": null, "e": 3941, "s": 3898, "text": "def sigmoid(z): return 1/(1+np.exp(-z))" }, { "code": null, "e": 3969, "s": 3941, "text": "3.2 Initializing Parameters" }, { "code": null, "e": 4155, "s": 3969, "text": "We need to initialize the parameter w (weight) and b (bias). In the following example, w is initialized as a vector of random numbers using np.random.randn() while b is initialize zero." }, { "code": null, "e": 4247, "s": 4155, "text": "def initialize_parameters(dim): w = np.random.randn(dim, 1)*0.01 b = 0 return w, b" }, { "code": null, "e": 4280, "s": 4247, "text": "3.3 Forward and Back Propagation" }, { "code": null, "e": 4403, "s": 4280, "text": "Once the parameters are initialized, we can do the “forward” and “backward” propagation steps for learning the parameters." }, { "code": null, "e": 4440, "s": 4403, "text": "Set of input features (X) are given." }, { "code": null, "e": 4498, "s": 4440, "text": "We will calculate the activation function as given below." }, { "code": null, "e": 4539, "s": 4498, "text": "We will compute the cost as given below." }, { "code": null, "e": 4611, "s": 4539, "text": "Finally, we will calculate the gradients as follows (back propagation)." }, { "code": null, "e": 5010, "s": 4611, "text": "def propagate(w, b, X, Y): m = X.shape[1] #calculate activation function A = sigmoid(np.dot(w.T, X)+b) #find the cost cost = (-1/m) * np.sum(Y * np.log(A) + (1 - Y) * (np.log(1 - A))) #find gradient (back propagation) dw = (1/m) * np.dot(X, (A-Y).T) db = (1/m) * np.sum(A-Y) cost = np.squeeze(cost) grads = {\"dw\": dw, \"db\": db} return grads, cost" }, { "code": null, "e": 5027, "s": 5010, "text": "3.4 Optimization" }, { "code": null, "e": 5175, "s": 5027, "text": "After initializing the parameters, computing the cost function, and calculating gradients, we can now update the parameters using gradient descent." }, { "code": null, "e": 5628, "s": 5175, "text": "def gradient_descent(w, b, X, Y, iterations, learning_rate): costs = [] for i in range(iterations): grads, cost = propagate(w, b, X, Y) #update parameters w = w - learning_rate * grads[\"dw\"] b = b - learning_rate * grads[\"db\"] costs.append(cost) if i % 500 == 0: print (\"Cost after iteration %i: %f\" %(i, cost)) params = {\"w\": w, \"b\": b} return params, costs" }, { "code": null, "e": 5643, "s": 5628, "text": "3.5 Prediction" }, { "code": null, "e": 5820, "s": 5643, "text": "Using the learned parameter w and b, we can predict the labels for a train or test examples. For prediction we first need to calculate the activation function given as follows." }, { "code": null, "e": 5917, "s": 5820, "text": "Then convert the output (prediction) into 0 (if A <= 0.5) or 1 (if A > 0.5) and store in y_pred." }, { "code": null, "e": 6191, "s": 5917, "text": "def predict(w, b, X): # number of example m = X.shape[1] y_pred = np.zeros((1,m)) w = w.reshape(X.shape[0], 1) A = sigmoid(np.dot(w.T, X)+b) for i in range(A.shape[1]): y_pred[0,i] = 1 if A[0,i] >0.5 else 0 pass return y_pred" }, { "code": null, "e": 6207, "s": 6191, "text": "3.6 Final Model" }, { "code": null, "e": 6301, "s": 6207, "text": "We can put together all the building block in the right order to make a neural network model." }, { "code": null, "e": 6855, "s": 6301, "text": "def model(train_x, train_y, test_x, test_y, iterations, learning_rate): w, b = initialize_parameters(train_x.shape[0]) parameters, costs = gradient_descent(w, b, train_x, train_y, iterations, learning_rate) w = parameters[\"w\"] b = parameters[\"b\"] # predict train_pred_y = predict(w, b, train_x) test_pred_y = predict(w, b, test_x) print(\"Train Acc: {} %\".format(100 - np.mean(np.abs(train_pred_y - train_y)) * 100)) print(\"Test Acc: {} %\".format(100 - np.mean(np.abs(test_pred_y - test_y)) * 100)) return costs" }, { "code": null, "e": 7036, "s": 6855, "text": "We can use the following code to train and predict on the image dataset using the model built above. We will use the learning_rate of 0.005 and train the model for 2000 iterations." }, { "code": null, "e": 7126, "s": 7036, "text": "costs = model(train_x, train_y, test_x, test_y, iterations = 2000, learning_rate = 0.005)" }, { "code": null, "e": 7356, "s": 7126, "text": "Training accuracy is around 99% which means that our model is working and fit the training data with high probability. Test accuracy is around 70%. Given the simple model and the small dataset, we can consider it as a good model." }, { "code": null, "e": 7433, "s": 7356, "text": "Finally, we can plot the cost and see how the model was learning parameters." }, { "code": null, "e": 7555, "s": 7433, "text": "plt.plot(costs)plt.ylabel('cost')plt.xlabel('iterations')plt.title(\"Learning rate =\" + str(d[\"learning_rate\"]))plt.show()" }, { "code": null, "e": 7655, "s": 7555, "text": "We can see the cost decreasing in each iteration which shows that the parameters are being learned." }, { "code": null, "e": 7734, "s": 7655, "text": "In the next article, we will discuss how to make a neural with a hidden layer." } ]
Convert HTML table to array in JavaScript?
Get data from tag using find() and store that data into array using push(). Let’s say the following is our table − <table id="details"> <thead> <tr> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr><td>John</td><td>23</td> <tr><td>David</td><td>26</td> </tbody> </table> Let’s fetch the data from <td> and store in an array. Following is the complete code − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <style> .notShown { display: none; } </style> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <table id="details"> <thead> <tr> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr><td>John</td><td>23</td> <tr><td>David</td><td>26</td> </tbody> </table> <script> var convertedIntoArray = []; $("table#details tr").each(function() { var rowDataArray = []; var actualData = $(this).find('td'); if (actualData.length > 0) { actualData.each(function() { rowDataArray.push($(this).text()); }); convertedIntoArray.push(rowDataArray); } }); console.log(convertedIntoArray); </script> </body> </html> To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor. This will produce the following output −
[ { "code": null, "e": 1177, "s": 1062, "text": "Get data from tag using find() and store that data into array using push(). Let’s say the following is our table −" }, { "code": null, "e": 1338, "s": 1177, "text": "<table id=\"details\">\n<thead>\n<tr>\n<th>Name</th>\n<th>Age</th>\n</tr>\n</thead>\n<tbody>\n<tr><td>John</td><td>23</td>\n<tr><td>David</td><td>26</td>\n</tbody>\n</table>" }, { "code": null, "e": 1425, "s": 1338, "text": "Let’s fetch the data from <td> and store in an array. Following is the complete code −" }, { "code": null, "e": 1436, "s": 1425, "text": " Live Demo" }, { "code": null, "e": 2462, "s": 1436, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\"\nhref=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<style>\n .notShown {\n display: none;\n }\n</style>\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<table id=\"details\">\n<thead>\n<tr>\n<th>Name</th>\n<th>Age</th>\n</tr>\n</thead>\n<tbody>\n<tr><td>John</td><td>23</td>\n<tr><td>David</td><td>26</td>\n</tbody>\n</table>\n<script>\n var convertedIntoArray = [];\n $(\"table#details tr\").each(function() {\n var rowDataArray = [];\n var actualData = $(this).find('td');\n if (actualData.length > 0) {\n actualData.each(function() {\n rowDataArray.push($(this).text());\n });\n convertedIntoArray.push(rowDataArray);\n }\n });\n console.log(convertedIntoArray);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2624, "s": 2462, "text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor." }, { "code": null, "e": 2665, "s": 2624, "text": "This will produce the following output −" } ]
Python read values from dict - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws The values() method returns a new view of the dictionary values as a list referred to as “dict_values”. Since this is a view of the dictionary, all the updates made to the dictionary are also visible. The signature for the values() method is as shown below. Here, d refers to the dictionary, and v is a view over the dictionary. v=d.values() The values() method takes no parameters. However, it returns a view object that displays values as a list. Example 1: In this case, let us take a dictionary with numbers assigned to colour names. Here, we will extract all the values as a list. Moreover, we can see list is named as dict_values. #Initializing color={1:"Red",2:"Blue",3:"Green"} # Using values method v1=color.values() #Printing print("View has ",v1) Output View has dict_values(["Red","Blue","Green"]) Example 2: Let us take a dictionary with numbers assigned to a list containing names in this example. Firstly, let us add the new key-value pair to the dictionary. As we can see, it automatically updates the view. #Initializing n={1:["Jim","Kim"],2:["John","Tom"],3:["Riya","Siya"]} v1=n.values() #Printing print("Before update view has ",v1) #Adding new key value pair n.update({4:["X","Y"]}) #Printing print("After update view has ",v1) Output Before update view has dict_values([['Jim', 'Kim'], ['John', 'Tom'], ['Riya', 'Siya']]) After update view has dict_values([['Jim', 'Kim'], ['John', 'Tom'], ['Riya', 'Siya'], ['X', 'Y']]) Example 3: We will take a dictionary with the department name and student name in this case. Here, we will delete the key “Comp”. As a result, changes are reflected in the view also. #Initializing n={"Comp":"Jim","IT":"Tom","EXTC":"Siya"} # Using values method v1=n.values() #Printing print("Before Delete view has ",v1) del(n["Comp"]) #Printing print("After Delete view has ",v1) Output Before Delete view has dict_values(['Jim', 'Tom', 'Siya']) After Delete view has dict_values(['Tom', 'Siya']) The values() method extracts values from the dictionary as a list. Just because this is a view over the dictionary, all the updates made to the dictionary are also reflected in the view. Python Dictionary Python Dict in depth Happy Learning 🙂 How to read all items from Dictionary in Python Python Dictionary Methods and Usages How to get elements from Dict in Python How to use fromkeys for a Dictionary in Python How to copy a Dictionary in Python How to find Symmetric Difference of two Sets in Python How to Iterate Python Dictionary ? Python – How to remove key from dictionary ? How to sort python dictionary by key ? How to use difference_update for a Set in Python How to use update method in a Set in Python How to read JSON file in Python ? How to perform Union operation on a Set in Python Python How to read input from keyboard Python – How to read environment variables ? How to read all items from Dictionary in Python Python Dictionary Methods and Usages How to get elements from Dict in Python How to use fromkeys for a Dictionary in Python How to copy a Dictionary in Python How to find Symmetric Difference of two Sets in Python How to Iterate Python Dictionary ? Python – How to remove key from dictionary ? How to sort python dictionary by key ? How to use difference_update for a Set in Python How to use update method in a Set in Python How to read JSON file in Python ? How to perform Union operation on a Set in Python Python How to read input from keyboard Python – How to read environment variables ? Δ Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 599, "s": 398, "text": "The values() method returns a new view of the dictionary values as a list referred to as “dict_values”. Since this is a view of the dictionary, all the updates made to the dictionary are also visible." }, { "code": null, "e": 727, "s": 599, "text": "The signature for the values() method is as shown below. Here, d refers to the dictionary, and v is a view over the dictionary." }, { "code": null, "e": 740, "s": 727, "text": "v=d.values()" }, { "code": null, "e": 781, "s": 740, "text": "The values() method takes no parameters." }, { "code": null, "e": 847, "s": 781, "text": "However, it returns a view object that displays values as a list." }, { "code": null, "e": 858, "s": 847, "text": "Example 1:" }, { "code": null, "e": 1035, "s": 858, "text": "In this case, let us take a dictionary with numbers assigned to colour names. Here, we will extract all the values as a list. Moreover, we can see list is named as dict_values." }, { "code": null, "e": 1159, "s": 1035, "text": "#Initializing \ncolor={1:\"Red\",2:\"Blue\",3:\"Green\"}\n# Using values method\nv1=color.values()\n#Printing \nprint(\"View has \",v1)\n" }, { "code": null, "e": 1166, "s": 1159, "text": "Output" }, { "code": null, "e": 1212, "s": 1166, "text": "View has dict_values([\"Red\",\"Blue\",\"Green\"])\n" }, { "code": null, "e": 1223, "s": 1212, "text": "Example 2:" }, { "code": null, "e": 1426, "s": 1223, "text": "Let us take a dictionary with numbers assigned to a list containing names in this example. Firstly, let us add the new key-value pair to the dictionary. As we can see, it automatically updates the view." }, { "code": null, "e": 1655, "s": 1426, "text": "#Initializing \nn={1:[\"Jim\",\"Kim\"],2:[\"John\",\"Tom\"],3:[\"Riya\",\"Siya\"]}\nv1=n.values()\n#Printing \nprint(\"Before update view has \",v1)\n#Adding new key value pair\nn.update({4:[\"X\",\"Y\"]})\n#Printing \nprint(\"After update view has \",v1)\n" }, { "code": null, "e": 1662, "s": 1655, "text": "Output" }, { "code": null, "e": 1852, "s": 1662, "text": "Before update view has dict_values([['Jim', 'Kim'], ['John', 'Tom'], ['Riya', 'Siya']])\nAfter update view has dict_values([['Jim', 'Kim'], ['John', 'Tom'], ['Riya', 'Siya'], ['X', 'Y']])\n" }, { "code": null, "e": 1863, "s": 1852, "text": "Example 3:" }, { "code": null, "e": 2035, "s": 1863, "text": "We will take a dictionary with the department name and student name in this case. Here, we will delete the key “Comp”. As a result, changes are reflected in the view also." }, { "code": null, "e": 2237, "s": 2035, "text": "#Initializing \nn={\"Comp\":\"Jim\",\"IT\":\"Tom\",\"EXTC\":\"Siya\"}\n# Using values method\nv1=n.values()\n#Printing \nprint(\"Before Delete view has \",v1)\ndel(n[\"Comp\"])\n#Printing \nprint(\"After Delete view has \",v1)\n" }, { "code": null, "e": 2244, "s": 2237, "text": "Output" }, { "code": null, "e": 2357, "s": 2244, "text": "Before Delete view has dict_values(['Jim', 'Tom', 'Siya'])\nAfter Delete view has dict_values(['Tom', 'Siya'])\n" }, { "code": null, "e": 2544, "s": 2357, "text": "The values() method extracts values from the dictionary as a list. Just because this is a view over the dictionary, all the updates made to the dictionary are also reflected in the view." }, { "code": null, "e": 2562, "s": 2544, "text": "Python Dictionary" }, { "code": null, "e": 2583, "s": 2562, "text": "Python Dict in depth" }, { "code": null, "e": 2600, "s": 2583, "text": "Happy Learning 🙂" }, { "code": null, "e": 3244, "s": 2600, "text": "\nHow to read all items from Dictionary in Python\nPython Dictionary Methods and Usages\nHow to get elements from Dict in Python\nHow to use fromkeys for a Dictionary in Python\nHow to copy a Dictionary in Python\nHow to find Symmetric Difference of two Sets in Python\nHow to Iterate Python Dictionary ?\nPython – How to remove key from dictionary ?\nHow to sort python dictionary by key ?\nHow to use difference_update for a Set in Python\nHow to use update method in a Set in Python\nHow to read JSON file in Python ?\nHow to perform Union operation on a Set in Python\nPython How to read input from keyboard\nPython – How to read environment variables ?\n" }, { "code": null, "e": 3292, "s": 3244, "text": "How to read all items from Dictionary in Python" }, { "code": null, "e": 3329, "s": 3292, "text": "Python Dictionary Methods and Usages" }, { "code": null, "e": 3369, "s": 3329, "text": "How to get elements from Dict in Python" }, { "code": null, "e": 3416, "s": 3369, "text": "How to use fromkeys for a Dictionary in Python" }, { "code": null, "e": 3451, "s": 3416, "text": "How to copy a Dictionary in Python" }, { "code": null, "e": 3506, "s": 3451, "text": "How to find Symmetric Difference of two Sets in Python" }, { "code": null, "e": 3541, "s": 3506, "text": "How to Iterate Python Dictionary ?" }, { "code": null, "e": 3586, "s": 3541, "text": "Python – How to remove key from dictionary ?" }, { "code": null, "e": 3625, "s": 3586, "text": "How to sort python dictionary by key ?" }, { "code": null, "e": 3674, "s": 3625, "text": "How to use difference_update for a Set in Python" }, { "code": null, "e": 3718, "s": 3674, "text": "How to use update method in a Set in Python" }, { "code": null, "e": 3752, "s": 3718, "text": "How to read JSON file in Python ?" }, { "code": null, "e": 3802, "s": 3752, "text": "How to perform Union operation on a Set in Python" }, { "code": null, "e": 3841, "s": 3802, "text": "Python How to read input from keyboard" }, { "code": null, "e": 3886, "s": 3841, "text": "Python – How to read environment variables ?" }, { "code": null, "e": 3892, "s": 3890, "text": "Δ" }, { "code": null, "e": 3915, "s": 3892, "text": " Python – Introduction" }, { "code": null, "e": 3934, "s": 3915, "text": " Python – Features" }, { "code": null, "e": 3963, "s": 3934, "text": " Python – Install on Windows" }, { "code": null, "e": 3990, "s": 3963, "text": " Python – Modes of Program" }, { "code": null, "e": 4014, "s": 3990, "text": " Python – Number System" }, { "code": null, "e": 4036, "s": 4014, "text": " Python – Identifiers" }, { "code": null, "e": 4056, "s": 4036, "text": " Python – Operators" }, { "code": null, "e": 4083, "s": 4056, "text": " Python – Ternary Operator" }, { "code": null, "e": 4116, "s": 4083, "text": " Python – Command Line Arguments" }, { "code": null, "e": 4135, "s": 4116, "text": " Python – Keywords" }, { "code": null, "e": 4156, "s": 4135, "text": " Python – Data Types" }, { "code": null, "e": 4185, "s": 4156, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 4215, "s": 4185, "text": " Python – Virtual Environment" }, { "code": null, "e": 4238, "s": 4215, "text": " Pyhton – Type Casting" }, { "code": null, "e": 4262, "s": 4238, "text": " Python – String to Int" }, { "code": null, "e": 4295, "s": 4262, "text": " Python – Conditional Statements" }, { "code": null, "e": 4318, "s": 4295, "text": " Python – if statement" }, { "code": null, "e": 4347, "s": 4318, "text": " Python – *args and **kwargs" }, { "code": null, "e": 4373, "s": 4347, "text": " Python – Date Formatting" }, { "code": null, "e": 4408, "s": 4373, "text": " Python – Read input from keyboard" }, { "code": null, "e": 4428, "s": 4408, "text": " Python – raw_input" }, { "code": null, "e": 4452, "s": 4428, "text": " Python – List In Depth" }, { "code": null, "e": 4481, "s": 4452, "text": " Python – List Comprehension" }, { "code": null, "e": 4504, "s": 4481, "text": " Python – Set in Depth" }, { "code": null, "e": 4534, "s": 4504, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 4559, "s": 4534, "text": " Python – Tuple in Depth" }, { "code": null, "e": 4589, "s": 4559, "text": " Python – Stack Datastructure" }, { "code": null, "e": 4619, "s": 4589, "text": " Python – Classes and Objects" }, { "code": null, "e": 4642, "s": 4619, "text": " Python – Constructors" }, { "code": null, "e": 4673, "s": 4642, "text": " Python – Object Introspection" }, { "code": null, "e": 4695, "s": 4673, "text": " Python – Inheritance" }, { "code": null, "e": 4716, "s": 4695, "text": " Python – Decorators" }, { "code": null, "e": 4752, "s": 4716, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 4782, "s": 4752, "text": " Python – Exceptions Handling" }, { "code": null, "e": 4816, "s": 4782, "text": " Python – User defined Exceptions" }, { "code": null, "e": 4842, "s": 4816, "text": " Python – Multiprocessing" }, { "code": null, "e": 4880, "s": 4842, "text": " Python – Default function parameters" }, { "code": null, "e": 4908, "s": 4880, "text": " Python – Lambdas Functions" }, { "code": null, "e": 4932, "s": 4908, "text": " Python – NumPy Library" }, { "code": null, "e": 4958, "s": 4932, "text": " Python – MySQL Connector" }, { "code": null, "e": 4990, "s": 4958, "text": " Python – MySQL Create Database" }, { "code": null, "e": 5016, "s": 4990, "text": " Python – MySQL Read Data" }, { "code": null, "e": 5044, "s": 5016, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 5075, "s": 5044, "text": " Python – MySQL Update Records" }, { "code": null, "e": 5106, "s": 5075, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 5139, "s": 5106, "text": " Python – String Case Conversion" }, { "code": null, "e": 5174, "s": 5139, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 5211, "s": 5174, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 5249, "s": 5211, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 5275, "s": 5249, "text": " Howto – Merge two Lists" }, { "code": null, "e": 5300, "s": 5275, "text": " Howto – Merge two dicts" }, { "code": null, "e": 5340, "s": 5300, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 5375, "s": 5340, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 5410, "s": 5375, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 5439, "s": 5410, "text": " Howto – Read Env variables" }, { "code": null, "e": 5465, "s": 5439, "text": " Howto – Read a text File" }, { "code": null, "e": 5491, "s": 5465, "text": " Howto – Read a JSON File" }, { "code": null, "e": 5523, "s": 5491, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 5551, "s": 5523, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 5591, "s": 5551, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 5625, "s": 5591, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 5650, "s": 5625, "text": " Howto – create Zip File" }, { "code": null, "e": 5671, "s": 5650, "text": " Howto – Get OS info" }, { "code": null, "e": 5702, "s": 5671, "text": " Howto – Get size of Directory" }, { "code": null, "e": 5739, "s": 5702, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 5776, "s": 5739, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 5798, "s": 5776, "text": " Howto – Sort Objects" }, { "code": null, "e": 5836, "s": 5798, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 5859, "s": 5836, "text": " Howto – Read CSV File" }, { "code": null, "e": 5897, "s": 5859, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 5928, "s": 5897, "text": " Howto – Access for loop index" }, { "code": null, "e": 5966, "s": 5928, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 6006, "s": 5966, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 6053, "s": 6006, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 6085, "s": 6053, "text": " Howto – Sort dictionary by key" } ]
Files Class writeString() Method in Java with Examples - GeeksforGeeks
05 Feb, 2021 The writeString() method of File Class in Java is used to write contents to the specified file. Syntax: Files.writeString(path, string, options) Parameters: path – File path with data type as Path string – a specified string which will enter in the file with return type String. options – Different options to enter the string in the file. Like append the string to the file, overwrite everything in the file with the current string, etc Return Value: This method does not return any value. Below are two overloaded forms of the writeString() method. public static Path writeString​(Path path, CharSequence csq, OpenOption... options) throws IOException public static Path writeString​(Path path, CharSequence csq, Charset cs, OpenOption... options) throws IOException UTF-8 charset is used to write the content to file in the first method. The second method does the same using the specified charset. How the file is opened is specified in Options. Below is the implementation of the problem statement: Java // Implementation of writeString() method in Javaimport java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.StandardOpenOption; public class GFG { public static void main(String[] args) { // Initializing file Path with some conditions Path filePath = Paths.get("/home/mayur/", "temp", "gfg.txt"); try { // Write content to file Files.writeString(filePath, "Hello from GFG !!", StandardOpenOption.APPEND); // Verify file content String content = Files.readString(filePath); System.out.println(content); } catch (IOException e) { e.printStackTrace(); } }} Output: Hello from GFG ! ! output File Java-File Class Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Generics in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23948, "s": 23920, "text": "\n05 Feb, 2021" }, { "code": null, "e": 24044, "s": 23948, "text": "The writeString() method of File Class in Java is used to write contents to the specified file." }, { "code": null, "e": 24052, "s": 24044, "text": "Syntax:" }, { "code": null, "e": 24093, "s": 24052, "text": "Files.writeString(path, string, options)" }, { "code": null, "e": 24106, "s": 24093, "text": "Parameters: " }, { "code": null, "e": 24146, "s": 24106, "text": "path – File path with data type as Path" }, { "code": null, "e": 24228, "s": 24146, "text": "string – a specified string which will enter in the file with return type String." }, { "code": null, "e": 24387, "s": 24228, "text": "options – Different options to enter the string in the file. Like append the string to the file, overwrite everything in the file with the current string, etc" }, { "code": null, "e": 24440, "s": 24387, "text": "Return Value: This method does not return any value." }, { "code": null, "e": 24500, "s": 24440, "text": "Below are two overloaded forms of the writeString() method." }, { "code": null, "e": 24603, "s": 24500, "text": "public static Path writeString​(Path path, CharSequence csq, OpenOption... options) throws IOException" }, { "code": null, "e": 24718, "s": 24603, "text": "public static Path writeString​(Path path, CharSequence csq, Charset cs, OpenOption... options) throws IOException" }, { "code": null, "e": 24790, "s": 24718, "text": "UTF-8 charset is used to write the content to file in the first method." }, { "code": null, "e": 24851, "s": 24790, "text": "The second method does the same using the specified charset." }, { "code": null, "e": 24899, "s": 24851, "text": "How the file is opened is specified in Options." }, { "code": null, "e": 24953, "s": 24899, "text": "Below is the implementation of the problem statement:" }, { "code": null, "e": 24958, "s": 24953, "text": "Java" }, { "code": "// Implementation of writeString() method in Javaimport java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.StandardOpenOption; public class GFG { public static void main(String[] args) { // Initializing file Path with some conditions Path filePath = Paths.get(\"/home/mayur/\", \"temp\", \"gfg.txt\"); try { // Write content to file Files.writeString(filePath, \"Hello from GFG !!\", StandardOpenOption.APPEND); // Verify file content String content = Files.readString(filePath); System.out.println(content); } catch (IOException e) { e.printStackTrace(); } }}", "e": 25745, "s": 24958, "text": null }, { "code": null, "e": 25753, "s": 25745, "text": "Output:" }, { "code": null, "e": 25772, "s": 25753, "text": "Hello from GFG ! !" }, { "code": null, "e": 25784, "s": 25772, "text": "output File" }, { "code": null, "e": 25800, "s": 25784, "text": "Java-File Class" }, { "code": null, "e": 25807, "s": 25800, "text": "Picked" }, { "code": null, "e": 25812, "s": 25807, "text": "Java" }, { "code": null, "e": 25826, "s": 25812, "text": "Java Programs" }, { "code": null, "e": 25831, "s": 25826, "text": "Java" }, { "code": null, "e": 25929, "s": 25831, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25938, "s": 25929, "text": "Comments" }, { "code": null, "e": 25951, "s": 25938, "text": "Old Comments" }, { "code": null, "e": 25997, "s": 25951, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26018, "s": 25997, "text": "Constructors in Java" }, { "code": null, "e": 26033, "s": 26018, "text": "Stream In Java" }, { "code": null, "e": 26050, "s": 26033, "text": "Generics in Java" }, { "code": null, "e": 26069, "s": 26050, "text": "Exceptions in Java" }, { "code": null, "e": 26113, "s": 26069, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 26139, "s": 26113, "text": "Java Programming Examples" }, { "code": null, "e": 26173, "s": 26139, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 26220, "s": 26173, "text": "Implementing a Linked List in Java using Class" } ]
Evaluating linear relationships. How to use scatterplots, correlation... | by Emily A. Halford | Towards Data Science
One of the most common analyses conducted by data scientists is the evaluation of linear relationships between numeric variables. These relationships can be visualized using scatterplots, and this step should be taken regardless of any further analyses that are conducted. Regression analyses and correlation coefficients are both commonly used to statistically assess linear relationships, and these analytic techniques are closely related both conceptually and mathematically. This article will describe scatterplots, correlation coefficients, and linear regression, as well as the relationships between all three statistical tools. Scatterplots are used to visually assess the relationship between two numeric variables. Typically, the explanatory variable is placed on the X axis and the dependent variable is placed on the Y axis. The creation of a scatterplot is an essential first step before a correlation or regression analysis is conducted. Correlation coefficients and linear regression only work well to describe relationships that are fairly linear, and the scatterplot makes it easy to see what kind of relationships may be present in your data. Additionally, the scatterplot provides insight into the strength and direction of any possible relationship, which can later be confirmed via statistical analyses. Let’s look at examples of determining relationship direction, strength, and linearity using scatterplots. Both relationships pictured below are negative and fairly linear. We know this because as X increases, Y decreases at a relatively constant interval. The scatterplot on the right, however, represents a much stronger negative relationship than the relationship on the left. We can determine this because there is far less spread between the data points. If you picture an imaginary best-fit line slicing through these data, the points in the scatterplot on the right would all fall quite close to that line. Since the linear relationship is strong, knowing an X value tells us more about the possible value of Y in the righthand plot than it does in the lefthand plot. Now, both linear relationships pictured below are positive. As X increases, Y also increases. Yet again, the relationship represented in the scatterplot on the right is far stronger than that in the scatterplot on the left. Often, the relationship between two continuous variables isn’t linear at all. One such non-linear relationship is pictured below — as X increases, Y follows a parabolic shape. There appears to be a strong and important relationship between these variables, but it would not be captured by techniques designed to assess linear relationships (e.g., correlation and regression). The possibility of a relationship such as that pictured below underscores the importance of producing a scatterplot before running analyses, as this meaningful relationship could be completely missed in an analysis that skips data visualization. Once you’ve seen a somewhat linear relationship on your scatterplot, you can calculate a correlation coefficient to get a number representing the strength of the association. Correlation coefficients can be either negative or positive (which indicates a negative or positive relationship, respectively) and range from -1 to 1, with the ends of this spectrum representing strong relationships and 0 indicating that there is no linear relationship between the variables. There are two kinds of correlation coefficients that differ slightly from each other. Pearson’s correlation assumes both normality and linearity in the relationship between X and Y. Spearman’s correlation has less stringent assumptions, assuming only that the relationship is monotonic. This means that the relationship has to be consistently increasing or decreasing, but that it does not have to do so in a linear manner (see left). Spearman’s correlation also performs better than Pearson’s correlation in instances where there are outliers or very few data points. Assuming that both samples (X and Y) are normally distributed, a t-test can be used to assess the statistical significance of either kind of correlation coefficient. There are a few important limitations of correlation coefficients that should be noted. First, the correlation coefficient only measures the strength of the relationship, not its magnitude (how much does Y increase or decrease with increasing values of X?). Additionally, relationships between more than 2 variables simply can’t be assessed using a basic correlation coefficient. A single number can only provide so much information, and this value can be misleading without an associated scatterplot. With a large enough n, almost any relationship will be statistically significant in the t-test associated with a correlation coefficient. However, this doesn’t mean that the relationship that you’re seeing is truly meaningful. Usually, linear relationships don’t become visually apparent in a scatterplot unless the correlation coefficient is as high as about |0.7|. Depending on the sample size, however, values much lower than that often reach statistical significance. Given that correlation coefficients have such a tendency to overstate the meaningfulness of a relationship, this value is often squared to produce an R2 value. The smaller squared value tends to be more intuitive, and comes with a convenient interpretation: the R2 value tells you the percentage of variation in Y that is explained by variation in X. As useful as R2 is, this value still does not provide information about the magnitude of a relationship and cannot describe the relationships between multiple variables. Let’s assess the correlation coefficients of the positive relationships pictured above. Here are those scatterplots again: One line of R code is all it takes to produce both the Pearson correlation coefficient and the associated t-test output for the “weak” positive correlation pictured on the left: cor.test(data$x_pos_weak, data$y_pos_weak, method = "pearson") As can be seen in the output below, the Pearson correlation coefficient (0.78) is very large even in this “weak” relationship. The p-value associated with the t-test statistic is well below 0.05, indicating a significant relationship: We can now use this correlation coefficient to calculate an R2 value, which in this case would be 0.77983282 = 0.61. This lower value seems to better represent our somewhat scattered data, and we can now say that 61% of variation in Y is explained by variation in X. Now, let’s run this analysis for the “strong” positive relationship pictured above in the right panel: cor.test(data$x_pos_strong, data$y_pos_strong, method = "pearson") Now the relationship is almost equivalent to 1, which confirms the very strong relationship that we could observe in the scatterplot above. Yet again, the relationship is statistically significant: In this case, our R2 value (0.97359732) remains quite close to the Pearson correlation coefficient at 0.95. In other words, 95% of variation in Y is explained by variation in X. Given how strong the relationship appeared to be on the scatterplot, this value still seems to fit the data well. *Note: There are many kinds of regression analyses, and lots of complexity that one can dive into in learning about regression. For the purposes of this article, I am keeping it simple and am focused entirely on linear regression and its relationship with scatterplots and correlation coefficients. Regression takes correlation a bit further by producing a line which best fits your data. A simple linear regression analysis still provides us with the R2 value, but also provides a value representing the magnitude (slope) of the relationship between X and Y. This information enhances our understanding of the underlying relationship, and can be used to predict Y values given a certain value of X. T-tests are still used, but now they test the null hypothesis that the slope of the line representing the relationship between X and Y is zero (magnitude!). It is also possible to assess relationships involving multiple explanatory variables using linear regression. The magnitude of these relationships can be assessed using the separate slopes that represent the relationship between each included variable and the outcome variable in that model. Additionally, the R2 value produced using multiple regression (many X variables) represents the percentage of change in Y that can be explained by all of those variables combined. This additional analytic capability and output allows us to get an even better understanding of the associations present in our data and to represent more complex relationships. In order to use linear regression appropriately, the following assumptions must be met: Independence: All observations are independent of each other, residuals are uncorrelatedLinearity: The relationship between X and Y is linearHomoscedasticity: Constant variance of residuals at different values of XNormality: Data should be normally distributed around the regression line Independence: All observations are independent of each other, residuals are uncorrelated Linearity: The relationship between X and Y is linear Homoscedasticity: Constant variance of residuals at different values of X Normality: Data should be normally distributed around the regression line Let’s assume that these criteria are met in our sample data and run regression analyses to test those positive associations visualized earlier. Just a couple of lines of code produce the linear model for our “weak” association: weak = lm(y_pos_weak ~ x_pos_weak, data = data)summary(weak) We can gather a few important things from the output shown below. First, the Multiple R-squared value is exactly equal to that produced by squaring the correlation coefficient. Second, we see that our data can best be described by the following line: Y = 1.8960 + 3.2711(X) We now know that on average, for every one-unit increase in X, there is a 3.2711-unit increase in Y. We can also plug X values into this equation to make predictions of Y. Let’s run the model now for our “strong” relationship: strong = lm(y_pos_strong ~ x_pos_strong, data = data)summary(strong) Again, the R2 value is consistent with what we calculated before. These data can best be described by the following line: Y = 0.8041 + 5.4092(X) Now, Y is expected to increase by 5.4092 units for every 1-unit increase in X. Not only is this relationship stronger, as can be seen by the higher R2 value, but its magnitude is also greater as is indicated by this greater slope. While it is tempting to quickly throw data into a regression model to assess linear relationships, it is important to understand what the resulting output means and to visualize the data in a scatterplot before drawing any conclusions. A GitHub repo containing all relevant code and sample data can be found here.
[ { "code": null, "e": 651, "s": 172, "text": "One of the most common analyses conducted by data scientists is the evaluation of linear relationships between numeric variables. These relationships can be visualized using scatterplots, and this step should be taken regardless of any further analyses that are conducted. Regression analyses and correlation coefficients are both commonly used to statistically assess linear relationships, and these analytic techniques are closely related both conceptually and mathematically." }, { "code": null, "e": 807, "s": 651, "text": "This article will describe scatterplots, correlation coefficients, and linear regression, as well as the relationships between all three statistical tools." }, { "code": null, "e": 1008, "s": 807, "text": "Scatterplots are used to visually assess the relationship between two numeric variables. Typically, the explanatory variable is placed on the X axis and the dependent variable is placed on the Y axis." }, { "code": null, "e": 1496, "s": 1008, "text": "The creation of a scatterplot is an essential first step before a correlation or regression analysis is conducted. Correlation coefficients and linear regression only work well to describe relationships that are fairly linear, and the scatterplot makes it easy to see what kind of relationships may be present in your data. Additionally, the scatterplot provides insight into the strength and direction of any possible relationship, which can later be confirmed via statistical analyses." }, { "code": null, "e": 1602, "s": 1496, "text": "Let’s look at examples of determining relationship direction, strength, and linearity using scatterplots." }, { "code": null, "e": 2270, "s": 1602, "text": "Both relationships pictured below are negative and fairly linear. We know this because as X increases, Y decreases at a relatively constant interval. The scatterplot on the right, however, represents a much stronger negative relationship than the relationship on the left. We can determine this because there is far less spread between the data points. If you picture an imaginary best-fit line slicing through these data, the points in the scatterplot on the right would all fall quite close to that line. Since the linear relationship is strong, knowing an X value tells us more about the possible value of Y in the righthand plot than it does in the lefthand plot." }, { "code": null, "e": 2494, "s": 2270, "text": "Now, both linear relationships pictured below are positive. As X increases, Y also increases. Yet again, the relationship represented in the scatterplot on the right is far stronger than that in the scatterplot on the left." }, { "code": null, "e": 3116, "s": 2494, "text": "Often, the relationship between two continuous variables isn’t linear at all. One such non-linear relationship is pictured below — as X increases, Y follows a parabolic shape. There appears to be a strong and important relationship between these variables, but it would not be captured by techniques designed to assess linear relationships (e.g., correlation and regression). The possibility of a relationship such as that pictured below underscores the importance of producing a scatterplot before running analyses, as this meaningful relationship could be completely missed in an analysis that skips data visualization." }, { "code": null, "e": 3585, "s": 3116, "text": "Once you’ve seen a somewhat linear relationship on your scatterplot, you can calculate a correlation coefficient to get a number representing the strength of the association. Correlation coefficients can be either negative or positive (which indicates a negative or positive relationship, respectively) and range from -1 to 1, with the ends of this spectrum representing strong relationships and 0 indicating that there is no linear relationship between the variables." }, { "code": null, "e": 4154, "s": 3585, "text": "There are two kinds of correlation coefficients that differ slightly from each other. Pearson’s correlation assumes both normality and linearity in the relationship between X and Y. Spearman’s correlation has less stringent assumptions, assuming only that the relationship is monotonic. This means that the relationship has to be consistently increasing or decreasing, but that it does not have to do so in a linear manner (see left). Spearman’s correlation also performs better than Pearson’s correlation in instances where there are outliers or very few data points." }, { "code": null, "e": 4320, "s": 4154, "text": "Assuming that both samples (X and Y) are normally distributed, a t-test can be used to assess the statistical significance of either kind of correlation coefficient." }, { "code": null, "e": 4700, "s": 4320, "text": "There are a few important limitations of correlation coefficients that should be noted. First, the correlation coefficient only measures the strength of the relationship, not its magnitude (how much does Y increase or decrease with increasing values of X?). Additionally, relationships between more than 2 variables simply can’t be assessed using a basic correlation coefficient." }, { "code": null, "e": 5294, "s": 4700, "text": "A single number can only provide so much information, and this value can be misleading without an associated scatterplot. With a large enough n, almost any relationship will be statistically significant in the t-test associated with a correlation coefficient. However, this doesn’t mean that the relationship that you’re seeing is truly meaningful. Usually, linear relationships don’t become visually apparent in a scatterplot unless the correlation coefficient is as high as about |0.7|. Depending on the sample size, however, values much lower than that often reach statistical significance." }, { "code": null, "e": 5815, "s": 5294, "text": "Given that correlation coefficients have such a tendency to overstate the meaningfulness of a relationship, this value is often squared to produce an R2 value. The smaller squared value tends to be more intuitive, and comes with a convenient interpretation: the R2 value tells you the percentage of variation in Y that is explained by variation in X. As useful as R2 is, this value still does not provide information about the magnitude of a relationship and cannot describe the relationships between multiple variables." }, { "code": null, "e": 5938, "s": 5815, "text": "Let’s assess the correlation coefficients of the positive relationships pictured above. Here are those scatterplots again:" }, { "code": null, "e": 6116, "s": 5938, "text": "One line of R code is all it takes to produce both the Pearson correlation coefficient and the associated t-test output for the “weak” positive correlation pictured on the left:" }, { "code": null, "e": 6179, "s": 6116, "text": "cor.test(data$x_pos_weak, data$y_pos_weak, method = \"pearson\")" }, { "code": null, "e": 6414, "s": 6179, "text": "As can be seen in the output below, the Pearson correlation coefficient (0.78) is very large even in this “weak” relationship. The p-value associated with the t-test statistic is well below 0.05, indicating a significant relationship:" }, { "code": null, "e": 6681, "s": 6414, "text": "We can now use this correlation coefficient to calculate an R2 value, which in this case would be 0.77983282 = 0.61. This lower value seems to better represent our somewhat scattered data, and we can now say that 61% of variation in Y is explained by variation in X." }, { "code": null, "e": 6784, "s": 6681, "text": "Now, let’s run this analysis for the “strong” positive relationship pictured above in the right panel:" }, { "code": null, "e": 6851, "s": 6784, "text": "cor.test(data$x_pos_strong, data$y_pos_strong, method = \"pearson\")" }, { "code": null, "e": 7049, "s": 6851, "text": "Now the relationship is almost equivalent to 1, which confirms the very strong relationship that we could observe in the scatterplot above. Yet again, the relationship is statistically significant:" }, { "code": null, "e": 7341, "s": 7049, "text": "In this case, our R2 value (0.97359732) remains quite close to the Pearson correlation coefficient at 0.95. In other words, 95% of variation in Y is explained by variation in X. Given how strong the relationship appeared to be on the scatterplot, this value still seems to fit the data well." }, { "code": null, "e": 7640, "s": 7341, "text": "*Note: There are many kinds of regression analyses, and lots of complexity that one can dive into in learning about regression. For the purposes of this article, I am keeping it simple and am focused entirely on linear regression and its relationship with scatterplots and correlation coefficients." }, { "code": null, "e": 8198, "s": 7640, "text": "Regression takes correlation a bit further by producing a line which best fits your data. A simple linear regression analysis still provides us with the R2 value, but also provides a value representing the magnitude (slope) of the relationship between X and Y. This information enhances our understanding of the underlying relationship, and can be used to predict Y values given a certain value of X. T-tests are still used, but now they test the null hypothesis that the slope of the line representing the relationship between X and Y is zero (magnitude!)." }, { "code": null, "e": 8848, "s": 8198, "text": "It is also possible to assess relationships involving multiple explanatory variables using linear regression. The magnitude of these relationships can be assessed using the separate slopes that represent the relationship between each included variable and the outcome variable in that model. Additionally, the R2 value produced using multiple regression (many X variables) represents the percentage of change in Y that can be explained by all of those variables combined. This additional analytic capability and output allows us to get an even better understanding of the associations present in our data and to represent more complex relationships." }, { "code": null, "e": 8936, "s": 8848, "text": "In order to use linear regression appropriately, the following assumptions must be met:" }, { "code": null, "e": 9224, "s": 8936, "text": "Independence: All observations are independent of each other, residuals are uncorrelatedLinearity: The relationship between X and Y is linearHomoscedasticity: Constant variance of residuals at different values of XNormality: Data should be normally distributed around the regression line" }, { "code": null, "e": 9313, "s": 9224, "text": "Independence: All observations are independent of each other, residuals are uncorrelated" }, { "code": null, "e": 9367, "s": 9313, "text": "Linearity: The relationship between X and Y is linear" }, { "code": null, "e": 9441, "s": 9367, "text": "Homoscedasticity: Constant variance of residuals at different values of X" }, { "code": null, "e": 9515, "s": 9441, "text": "Normality: Data should be normally distributed around the regression line" }, { "code": null, "e": 9659, "s": 9515, "text": "Let’s assume that these criteria are met in our sample data and run regression analyses to test those positive associations visualized earlier." }, { "code": null, "e": 9743, "s": 9659, "text": "Just a couple of lines of code produce the linear model for our “weak” association:" }, { "code": null, "e": 9804, "s": 9743, "text": "weak = lm(y_pos_weak ~ x_pos_weak, data = data)summary(weak)" }, { "code": null, "e": 10055, "s": 9804, "text": "We can gather a few important things from the output shown below. First, the Multiple R-squared value is exactly equal to that produced by squaring the correlation coefficient. Second, we see that our data can best be described by the following line:" }, { "code": null, "e": 10078, "s": 10055, "text": "Y = 1.8960 + 3.2711(X)" }, { "code": null, "e": 10250, "s": 10078, "text": "We now know that on average, for every one-unit increase in X, there is a 3.2711-unit increase in Y. We can also plug X values into this equation to make predictions of Y." }, { "code": null, "e": 10305, "s": 10250, "text": "Let’s run the model now for our “strong” relationship:" }, { "code": null, "e": 10374, "s": 10305, "text": "strong = lm(y_pos_strong ~ x_pos_strong, data = data)summary(strong)" }, { "code": null, "e": 10496, "s": 10374, "text": "Again, the R2 value is consistent with what we calculated before. These data can best be described by the following line:" }, { "code": null, "e": 10519, "s": 10496, "text": "Y = 0.8041 + 5.4092(X)" }, { "code": null, "e": 10750, "s": 10519, "text": "Now, Y is expected to increase by 5.4092 units for every 1-unit increase in X. Not only is this relationship stronger, as can be seen by the higher R2 value, but its magnitude is also greater as is indicated by this greater slope." }, { "code": null, "e": 10986, "s": 10750, "text": "While it is tempting to quickly throw data into a regression model to assess linear relationships, it is important to understand what the resulting output means and to visualize the data in a scatterplot before drawing any conclusions." } ]
JQuery | Get the text of a span element - GeeksforGeeks
03 Aug, 2021 Given an HTML document and the task is to get the text of a <span> tag using JQuery. Method 1: Using jQuery text() Method: This method is used to set or return the text content of specified elements. If this method is used to return content, it returns the text content of all matched elements (HTML tags will be removed). If this method is used to set content, it overwrites the content of all matched elements. Syntax: Return text content:$(selector).text() $(selector).text() Set text content:$(selector).text(content) $(selector).text(content) Set text content using a function:$(selector).text(function(index, curContent)) $(selector).text(function(index, curContent)) Parameters: content: It is required parameter. It specifies the new text content for the selected elements. function(index, curContent): It is optional parameter. It specifies the function that returns the new text content for the selected elements.index: It returns the index position of element in the set.curContent: It returns current content of selected elements. index: It returns the index position of element in the set. curContent: It returns current content of selected elements. Example: This example gets the content by using JQuery’s text() method . <!DOCTYPE HTML> <html> <head> <title> JQuery | Get the text of a span element </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <span id="GFG_Span" style = "font-size: 15px; font-weight: bold;"> This is text of Span element. </span> <br><br> <button> Click Here </button> <p id="GFG_DOWN" style="color:green;font-size:20px;font-weight:bold;"> </p> <script> $('button').on('click', function() { var $val = $('#GFG_Span').text(); $('#GFG_DOWN').text($val); }); </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Method 2: Using jQuery html() Method: This method set or return the content (HTML) of the specified elements. If this method is used to return content, it returns the content of first matched element. If this method is used to set content, it overwrites the content of all matched elements. Syntax: Return content:$(selector).html() $(selector).html() Set content:$(selector).html(content) $(selector).html(content) Set content using a function:$(selector).html(function(index, curContent)) $(selector).html(function(index, curContent)) Parameters: content: This parameter is required. It specifies the new text content for the selected elements containing the HTML tags. function(index, curContent): This parameter is optional. It specifies a function that returns the new content for the selected elements.index: It returns the index position of element in the set.curContent: It returns current HTML content of selected elements. index: It returns the index position of element in the set. curContent: It returns current HTML content of selected elements. Example: This example gets the content by using JQuery’s html() method . <!DOCTYPE HTML> <html> <head> <title> JQuery | Get the text of a span element. </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <span id="GFG_Span" style="font-size:15px; font-weight:bold;"> This is text of Span element. </span> <br><br> <button> Click Here </button> <p id="GFG_DOWN" style="color:green; font-size:20px; font-weight:bold;"> </p> <script> $('button').on('click', function() { var $val = $('#GFG_Span').html(); $('#GFG_DOWN').text($val); }); </script> </body> </html> Output: Before clicking on the button: After clicking on the button: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-Misc JavaScript JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? JQuery | Set the value of an input text field How to change selected value of a drop-down list using jQuery? Form validation using jQuery How to change the background color after clicking the button in JavaScript ? How to Dynamically Add/Remove Table Rows using jQuery ?
[ { "code": null, "e": 24435, "s": 24407, "text": "\n03 Aug, 2021" }, { "code": null, "e": 24520, "s": 24435, "text": "Given an HTML document and the task is to get the text of a <span> tag using JQuery." }, { "code": null, "e": 24848, "s": 24520, "text": "Method 1: Using jQuery text() Method: This method is used to set or return the text content of specified elements. If this method is used to return content, it returns the text content of all matched elements (HTML tags will be removed). If this method is used to set content, it overwrites the content of all matched elements." }, { "code": null, "e": 24856, "s": 24848, "text": "Syntax:" }, { "code": null, "e": 24896, "s": 24856, "text": "Return text content:$(selector).text()\n" }, { "code": null, "e": 24916, "s": 24896, "text": "$(selector).text()\n" }, { "code": null, "e": 24960, "s": 24916, "text": "Set text content:$(selector).text(content)\n" }, { "code": null, "e": 24987, "s": 24960, "text": "$(selector).text(content)\n" }, { "code": null, "e": 25068, "s": 24987, "text": "Set text content using a function:$(selector).text(function(index, curContent))\n" }, { "code": null, "e": 25115, "s": 25068, "text": "$(selector).text(function(index, curContent))\n" }, { "code": null, "e": 25127, "s": 25115, "text": "Parameters:" }, { "code": null, "e": 25223, "s": 25127, "text": "content: It is required parameter. It specifies the new text content for the selected elements." }, { "code": null, "e": 25484, "s": 25223, "text": "function(index, curContent): It is optional parameter. It specifies the function that returns the new text content for the selected elements.index: It returns the index position of element in the set.curContent: It returns current content of selected elements." }, { "code": null, "e": 25544, "s": 25484, "text": "index: It returns the index position of element in the set." }, { "code": null, "e": 25605, "s": 25544, "text": "curContent: It returns current content of selected elements." }, { "code": null, "e": 25678, "s": 25605, "text": "Example: This example gets the content by using JQuery’s text() method ." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | Get the text of a span element </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <span id=\"GFG_Span\" style = \"font-size: 15px; font-weight: bold;\"> This is text of Span element. </span> <br><br> <button> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;font-size:20px;font-weight:bold;\"> </p> <script> $('button').on('click', function() { var $val = $('#GFG_Span').text(); $('#GFG_DOWN').text($val); }); </script> </body> </html> ", "e": 26644, "s": 25678, "text": null }, { "code": null, "e": 26652, "s": 26644, "text": "Output:" }, { "code": null, "e": 26683, "s": 26652, "text": "Before clicking on the button:" }, { "code": null, "e": 26713, "s": 26683, "text": "After clicking on the button:" }, { "code": null, "e": 27004, "s": 26713, "text": "Method 2: Using jQuery html() Method: This method set or return the content (HTML) of the specified elements. If this method is used to return content, it returns the content of first matched element. If this method is used to set content, it overwrites the content of all matched elements." }, { "code": null, "e": 27012, "s": 27004, "text": "Syntax:" }, { "code": null, "e": 27047, "s": 27012, "text": "Return content:$(selector).html()\n" }, { "code": null, "e": 27067, "s": 27047, "text": "$(selector).html()\n" }, { "code": null, "e": 27106, "s": 27067, "text": "Set content:$(selector).html(content)\n" }, { "code": null, "e": 27133, "s": 27106, "text": "$(selector).html(content)\n" }, { "code": null, "e": 27209, "s": 27133, "text": "Set content using a function:$(selector).html(function(index, curContent))\n" }, { "code": null, "e": 27256, "s": 27209, "text": "$(selector).html(function(index, curContent))\n" }, { "code": null, "e": 27268, "s": 27256, "text": "Parameters:" }, { "code": null, "e": 27391, "s": 27268, "text": "content: This parameter is required. It specifies the new text content for the selected elements containing the HTML tags." }, { "code": null, "e": 27652, "s": 27391, "text": "function(index, curContent): This parameter is optional. It specifies a function that returns the new content for the selected elements.index: It returns the index position of element in the set.curContent: It returns current HTML content of selected elements." }, { "code": null, "e": 27712, "s": 27652, "text": "index: It returns the index position of element in the set." }, { "code": null, "e": 27778, "s": 27712, "text": "curContent: It returns current HTML content of selected elements." }, { "code": null, "e": 27851, "s": 27778, "text": "Example: This example gets the content by using JQuery’s html() method ." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | Get the text of a span element. </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <span id=\"GFG_Span\" style=\"font-size:15px; font-weight:bold;\"> This is text of Span element. </span> <br><br> <button> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size:20px; font-weight:bold;\"> </p> <script> $('button').on('click', function() { var $val = $('#GFG_Span').html(); $('#GFG_DOWN').text($val); }); </script> </body> </html> ", "e": 28778, "s": 27851, "text": null }, { "code": null, "e": 28786, "s": 28778, "text": "Output:" }, { "code": null, "e": 28817, "s": 28786, "text": "Before clicking on the button:" }, { "code": null, "e": 28847, "s": 28817, "text": "After clicking on the button:" }, { "code": null, "e": 29115, "s": 28847, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 29127, "s": 29115, "text": "jQuery-Misc" }, { "code": null, "e": 29138, "s": 29127, "text": "JavaScript" }, { "code": null, "e": 29145, "s": 29138, "text": "JQuery" }, { "code": null, "e": 29162, "s": 29145, "text": "Web Technologies" }, { "code": null, "e": 29189, "s": 29162, "text": "Web technologies Questions" }, { "code": null, "e": 29287, "s": 29189, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29332, "s": 29287, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29393, "s": 29332, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29465, "s": 29393, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29517, "s": 29465, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 29563, "s": 29517, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29609, "s": 29563, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 29672, "s": 29609, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 29701, "s": 29672, "text": "Form validation using jQuery" }, { "code": null, "e": 29778, "s": 29701, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
Using SAP ABAP, how can I read content of CSV files in a directory to an internal table?
There are many functions that can be used to read csv however many are broken and read part of content. You need to go through each file and then process the file content. I would prefer to perform this manually. You can use the READ DATASET to read data from a file on the application server. Below is the syntax: READ DATASET <dsn> INTO <f> [LENGTH <len>]. Below is SAP documentation link that you can use to know more about reading data from files: SAP Documentation Incase you are using binary mode, you can use LENGTH to find the length of data transferred to <f>. The value of variable length is set by system in <len> as below: DATA FNAME(60) VALUE 'file'. DATA: TEXT1(10) VALUE 'helloworld', TEXT3(5), LENG TYPE I. OPEN DATASET FNAME FOR OUTPUT IN BINARY MODE. TRANSFER TEXT1 TO FNAME. CLOSE DATASET FNAME. OPEN DATASET FNAME FOR INPUT IN BINARY MODE. DO. READ DATASET FNAME INTO TEXT2 LENGTH LENG. WRITE: / SY-SUBRC, TEXT2, LENG. IF SY-SUBRC <> 0. EXIT. ENDIF. ENDDO. CLOSE DATASET FNAME.
[ { "code": null, "e": 1275, "s": 1062, "text": "There are many functions that can be used to read csv however many are broken and read part of content. You need to go through each file and then process the file content. I would prefer to perform this manually." }, { "code": null, "e": 1377, "s": 1275, "text": "You can use the READ DATASET to read data from a file on the application server. Below is the syntax:" }, { "code": null, "e": 1421, "s": 1377, "text": "READ DATASET <dsn> INTO <f> [LENGTH <len>]." }, { "code": null, "e": 1514, "s": 1421, "text": "Below is SAP documentation link that you can use to know more about reading data from files:" }, { "code": null, "e": 1532, "s": 1514, "text": "SAP Documentation" }, { "code": null, "e": 1697, "s": 1532, "text": "Incase you are using binary mode, you can use LENGTH to find the length of data transferred to <f>. The value of variable length is set by system in <len> as below:" }, { "code": null, "e": 2084, "s": 1697, "text": "DATA FNAME(60) VALUE 'file'.\nDATA: TEXT1(10) VALUE 'helloworld',\n TEXT3(5),\n LENG TYPE I.\nOPEN DATASET FNAME FOR OUTPUT IN BINARY MODE.\nTRANSFER TEXT1 TO FNAME.\nCLOSE DATASET FNAME.\nOPEN DATASET FNAME FOR INPUT IN BINARY MODE.\nDO.\n READ DATASET FNAME INTO TEXT2 LENGTH LENG.\n WRITE: / SY-SUBRC, TEXT2, LENG.\n IF SY-SUBRC <> 0.\n EXIT.\n ENDIF.\nENDDO.\nCLOSE DATASET FNAME." } ]
Fade in tab with Bootstrap
Use the .in class in Bootstrap to fade in the tab. You can try to run the following code to fade in tab − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <h2>Tutorials Website</h2> <p>The following is our learning content:</p> <ul class = "nav nav-tabs"> <li class="active"><a data-toggle = "tab" href = "#home">Home</a></li> <li><a data-toggle = "tab" href = "#two">About</a></li> <li><a data-toggle = "tab" href = "#three">Product</a></li> </ul> <div class = "tab-content"> <div id = "home" class="tab-pane in active"> <h2>Home</h2> <p>This is demo text!</p> </div> <div id = "two" class="tab-pane fade"> <h2>About</h2> <p>This is demo text!</p> </div> <div id = "three" class="tab-pane fade"> <h2>Product</h2> <p>This is demo text!</p> </div> </div> </div> </body> </html>
[ { "code": null, "e": 1113, "s": 1062, "text": "Use the .in class in Bootstrap to fade in the tab." }, { "code": null, "e": 1168, "s": 1113, "text": "You can try to run the following code to fade in tab −" }, { "code": null, "e": 1178, "s": 1168, "text": "Live Demo" }, { "code": null, "e": 2378, "s": 1178, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>Tutorials Website</h2>\n <p>The following is our learning content:</p>\n <ul class = \"nav nav-tabs\">\n <li class=\"active\"><a data-toggle = \"tab\" href = \"#home\">Home</a></li>\n <li><a data-toggle = \"tab\" href = \"#two\">About</a></li>\n <li><a data-toggle = \"tab\" href = \"#three\">Product</a></li>\n </ul>\n <div class = \"tab-content\">\n <div id = \"home\" class=\"tab-pane in active\">\n <h2>Home</h2>\n <p>This is demo text!</p>\n </div>\n <div id = \"two\" class=\"tab-pane fade\">\n <h2>About</h2>\n <p>This is demo text!</p>\n </div>\n <div id = \"three\" class=\"tab-pane fade\">\n <h2>Product</h2>\n <p>This is demo text!</p>\n </div>\n </div>\n </div>\n </body>\n</html>" } ]
Firebase (sign in with Google) Authentication in Node.js using Firebase UI and Cookie Sessions - GeeksforGeeks
26 Aug, 2020 Firebase Authentication provides the backend services that are easy-to-use SDKs and ready-made UI libraries to authenticate users to your app. Prerequisites: Basic knowledge of node, JavaScript and firebase. Setup: First we need to create a Firebase Project, head over to firebase Console and create a new project. I am going to name it SignInWithGoogle Click on the web to create a web app. Go to Firebase Settings>Service Account >Generate a new Key. This Key should be remain private, It is advised to keep this in environment variables. Now go to Authentication tab and turn on Sign in with Google. Now Create a new project having success.html (with a simple anchor tag, directing to “/ ” root ) and login.html [leave a blank division with id “firebaseui-auth-container”, the place where Firebase UI will be Initialized] Change console directory to root of your project type by using the following commands in the console $npm init $npm install express firebase-admin cookie-parser https fs Note: The last two packages are only needed if you wanna save cookies in local-host, however, if you will be running a backend on https then there is no need. const express = require("express");const admin = require("firebase-admin");const cookieParser = require("cookie-parser");const https = require('https');const fs = require('fs'); const app = express();app.use(cookieParser()); var key="--BEGIN PRIVATE KEY--\nMIIEvgIBADANBgk" + "qhkiG9w0BAQE--your key here--+1d4\n--END" + " PRIVATE KEY-\n"; admin.initializeApp({ credential: admin.credential.cert({ "private_key": key.replace(/\\n/g, '\n'), "client_email": "YOUR CLIENT EMAIL HERE", "project_id": "YOUR PROJECT ID " })}); app.get('/', (req, res) => { res.sendFile(__dirname +'/login.html'); }); app.get('/logout', (req, res) => { res.clearCookie('__session'); res.redirect('/');}); app.get('/success', checkCookie, (req, res) => { res.sendFile(__dirname + '/success.html'); console.log("UID of Signed in User is" + req.decodedClaims.uid); // You will reach here only if session // is working Fine}); app.get('savecookie', (req, res) => { const Idtoken=req.query.token; setCookie(Idtoken, res);}); // Saving cookies and verify cookies// Reference : //https://firebase.google.com/docs/auth/admin/manage-cookies function savecookie(idtoken, res) { const expiresIn = 60 * 60 * 24 * 5 * 1000; admin.auth().createSessionCookie(idtoken, {expiresIn}) .then((sessionCookie) => { const options = {maxAge: expiresIn, httpOnly: true, secure: true}; admin.auth().verifyIdToken(idtoken) .then(function(decodedClaims) { res.redirect('/success'); }); }, error => { res.status(401).send("UnAuthorised Request"); });} function checkCookie(req, res, next) { const sessionCookie = req.cookies.__session || ''; admin.auth().verifySessionCookie( sessionCookie, true).then((decodedClaims) => { req.decodedClaims = decodedClaims; next(); }) .catch(error => { // Session cookie is unavailable or invalid. // Force user to login. res.redirect('/'); });} Here is app.js file, If you look it closely, you will find that there is no port listening to our request. This is where we need those two node modules. Most browsers does’t allow you to save cookies in local host, that’s why we will setup HTTPS connection for our localhost. Make sure you are in root directory of project. Open bash and type $openssl req -nodes -new -x509 -keyout server.key -out server.cert Two files (server.key and server.cert) will be generated. Add the following code to app.js file- https.createServer({ key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.cert') }, app) .listen(3000, function () { console.log('listening on port 3000!' + ' Go to https://localhost:3000/') }); Load this script before body tag in login page <!-- Firebase Package--><script src="https://www.gstatic.com/firebasejs/5.8.5/firebase.js"></script> <!-- Loads the login UI elements--><script src="https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.js"></script><link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.css" /> Load this script in login page after body tag (fill the config data that you got from firebase console). var config = { apiKey: "YOUR_KEY", authDomain: "YOUR_DOMAIN", databaseURL: "YOURURL", projectId: "--", storageBucket: "", messagingSenderId: "", appId: ""}; firebase.initializeApp(config);firebase.auth().setPersistence( firebase.auth.Auth.Persistence.NONE); // FirebaseUI config.var uiConfig = { signInOptions: [ // Google sign in option firebase.auth.GoogleAuthProvider.PROVIDER_ID, ], // Terms of service url/callback. tosUrl: '<your-tos-url>', // Privacy policy url/callback. privacyPolicyUrl: function () { window.location.assign( '<your-privacy-policy-url>'); }, callbacks: { signInSuccess: function (user, credential, redirectUrl) { // User successfully signed in. user.getIdToken().then(function (idToken) { window.location.href = '/savecookie?idToken=' + idToken; }).catch(error => { console.log(error); }); } }}; // Initialize the FirebaseUI Widget using Firebase.var ui = new firebaseui.auth.AuthUI(firebase.auth()); // The start method will wait until the DOM is loaded.ui.start('#firebaseui-auth-container', uiConfig); Now hit save and run the command $node app.js Now go to https://localhost:3000/ and sign in, then close the tab or browser and type https://localhost:3000/success, you will see that you are not redirected to the sign-in page again, instead, you are taken to the success page. Note: Here it didn’t ask me to select which account to login with the app because I was signed in with only one account, in-case you have signed in with multiple accounts, it will ask you to choose an account to proceed with. Download My Completed project in case of any error you face or write in the comment Reference: https://firebase.google.com/docs/auth/admin/manage-cookies nidhi_biet Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method Difference between promise and async await in Node.js Express.js res.render() Function How to use an ES6 import in Node.js? How to read and write Excel file in Node.js ? Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24928, "s": 24900, "text": "\n26 Aug, 2020" }, { "code": null, "e": 25071, "s": 24928, "text": "Firebase Authentication provides the backend services that are easy-to-use SDKs and ready-made UI libraries to authenticate users to your app." }, { "code": null, "e": 25136, "s": 25071, "text": "Prerequisites: Basic knowledge of node, JavaScript and firebase." }, { "code": null, "e": 25244, "s": 25136, "text": "Setup: First we need to create a Firebase Project, head over to firebase Console and create a new project. " }, { "code": null, "e": 25283, "s": 25244, "text": "I am going to name it SignInWithGoogle" }, { "code": null, "e": 25321, "s": 25283, "text": "Click on the web to create a web app." }, { "code": null, "e": 25470, "s": 25321, "text": "Go to Firebase Settings>Service Account >Generate a new Key. This Key should be remain private, It is advised to keep this in environment variables." }, { "code": null, "e": 25532, "s": 25470, "text": "Now go to Authentication tab and turn on Sign in with Google." }, { "code": null, "e": 25754, "s": 25532, "text": "Now Create a new project having success.html (with a simple anchor tag, directing to “/ ” root ) and login.html [leave a blank division with id “firebaseui-auth-container”, the place where Firebase UI will be Initialized]" }, { "code": null, "e": 25855, "s": 25754, "text": "Change console directory to root of your project type by using the following commands in the console" }, { "code": null, "e": 25925, "s": 25855, "text": "$npm init\n$npm install express firebase-admin cookie-parser https fs\n" }, { "code": null, "e": 26084, "s": 25925, "text": "Note: The last two packages are only needed if you wanna save cookies in local-host, however, if you will be running a backend on https then there is no need." }, { "code": "const express = require(\"express\");const admin = require(\"firebase-admin\");const cookieParser = require(\"cookie-parser\");const https = require('https');const fs = require('fs'); const app = express();app.use(cookieParser()); var key=\"--BEGIN PRIVATE KEY--\\nMIIEvgIBADANBgk\" + \"qhkiG9w0BAQE--your key here--+1d4\\n--END\" + \" PRIVATE KEY-\\n\"; admin.initializeApp({ credential: admin.credential.cert({ \"private_key\": key.replace(/\\\\n/g, '\\n'), \"client_email\": \"YOUR CLIENT EMAIL HERE\", \"project_id\": \"YOUR PROJECT ID \" })}); app.get('/', (req, res) => { res.sendFile(__dirname +'/login.html'); }); app.get('/logout', (req, res) => { res.clearCookie('__session'); res.redirect('/');}); app.get('/success', checkCookie, (req, res) => { res.sendFile(__dirname + '/success.html'); console.log(\"UID of Signed in User is\" + req.decodedClaims.uid); // You will reach here only if session // is working Fine}); app.get('savecookie', (req, res) => { const Idtoken=req.query.token; setCookie(Idtoken, res);}); // Saving cookies and verify cookies// Reference : //https://firebase.google.com/docs/auth/admin/manage-cookies function savecookie(idtoken, res) { const expiresIn = 60 * 60 * 24 * 5 * 1000; admin.auth().createSessionCookie(idtoken, {expiresIn}) .then((sessionCookie) => { const options = {maxAge: expiresIn, httpOnly: true, secure: true}; admin.auth().verifyIdToken(idtoken) .then(function(decodedClaims) { res.redirect('/success'); }); }, error => { res.status(401).send(\"UnAuthorised Request\"); });} function checkCookie(req, res, next) { const sessionCookie = req.cookies.__session || ''; admin.auth().verifySessionCookie( sessionCookie, true).then((decodedClaims) => { req.decodedClaims = decodedClaims; next(); }) .catch(error => { // Session cookie is unavailable or invalid. // Force user to login. res.redirect('/'); });}", "e": 28174, "s": 26084, "text": null }, { "code": null, "e": 28327, "s": 28174, "text": "Here is app.js file, If you look it closely, you will find that there is no port listening to our request. This is where we need those two node modules." }, { "code": null, "e": 28450, "s": 28327, "text": "Most browsers does’t allow you to save cookies in local host, that’s why we will setup HTTPS connection for our localhost." }, { "code": null, "e": 28498, "s": 28450, "text": "Make sure you are in root directory of project." }, { "code": null, "e": 28517, "s": 28498, "text": "Open bash and type" }, { "code": null, "e": 28584, "s": 28517, "text": "$openssl req -nodes -new -x509 -keyout server.key -out server.cert" }, { "code": null, "e": 28642, "s": 28584, "text": "Two files (server.key and server.cert) will be generated." }, { "code": null, "e": 28681, "s": 28642, "text": "Add the following code to app.js file-" }, { "code": "https.createServer({ key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.cert') }, app) .listen(3000, function () { console.log('listening on port 3000!' + ' Go to https://localhost:3000/') });", "e": 28906, "s": 28681, "text": null }, { "code": null, "e": 28953, "s": 28906, "text": "Load this script before body tag in login page" }, { "code": " <!-- Firebase Package--><script src=\"https://www.gstatic.com/firebasejs/5.8.5/firebase.js\"></script> <!-- Loads the login UI elements--><script src=\"https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.js\"></script><link type=\"text/css\" rel=\"stylesheet\" href=\"https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.css\" />", "e": 29290, "s": 28953, "text": null }, { "code": null, "e": 29395, "s": 29290, "text": "Load this script in login page after body tag (fill the config data that you got from firebase console)." }, { "code": "var config = { apiKey: \"YOUR_KEY\", authDomain: \"YOUR_DOMAIN\", databaseURL: \"YOURURL\", projectId: \"--\", storageBucket: \"\", messagingSenderId: \"\", appId: \"\"}; firebase.initializeApp(config);firebase.auth().setPersistence( firebase.auth.Auth.Persistence.NONE); // FirebaseUI config.var uiConfig = { signInOptions: [ // Google sign in option firebase.auth.GoogleAuthProvider.PROVIDER_ID, ], // Terms of service url/callback. tosUrl: '<your-tos-url>', // Privacy policy url/callback. privacyPolicyUrl: function () { window.location.assign( '<your-privacy-policy-url>'); }, callbacks: { signInSuccess: function (user, credential, redirectUrl) { // User successfully signed in. user.getIdToken().then(function (idToken) { window.location.href = '/savecookie?idToken=' + idToken; }).catch(error => { console.log(error); }); } }}; // Initialize the FirebaseUI Widget using Firebase.var ui = new firebaseui.auth.AuthUI(firebase.auth()); // The start method will wait until the DOM is loaded.ui.start('#firebaseui-auth-container', uiConfig);", "e": 30689, "s": 29395, "text": null }, { "code": null, "e": 30737, "s": 30689, "text": "Now hit save and run the command $node app.js" }, { "code": null, "e": 30967, "s": 30737, "text": "Now go to https://localhost:3000/ and sign in, then close the tab or browser and type https://localhost:3000/success, you will see that you are not redirected to the sign-in page again, instead, you are taken to the success page." }, { "code": null, "e": 31193, "s": 30967, "text": "Note: Here it didn’t ask me to select which account to login with the app because I was signed in with only one account, in-case you have signed in with multiple accounts, it will ask you to choose an account to proceed with." }, { "code": null, "e": 31277, "s": 31193, "text": "Download My Completed project in case of any error you face or write in the comment" }, { "code": null, "e": 31347, "s": 31277, "text": "Reference: https://firebase.google.com/docs/auth/admin/manage-cookies" }, { "code": null, "e": 31358, "s": 31347, "text": "nidhi_biet" }, { "code": null, "e": 31371, "s": 31358, "text": "Node.js-Misc" }, { "code": null, "e": 31379, "s": 31371, "text": "Node.js" }, { "code": null, "e": 31396, "s": 31379, "text": "Web Technologies" }, { "code": null, "e": 31494, "s": 31396, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31524, "s": 31494, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 31578, "s": 31524, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 31611, "s": 31578, "text": "Express.js res.render() Function" }, { "code": null, "e": 31648, "s": 31611, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 31694, "s": 31648, "text": "How to read and write Excel file in Node.js ?" }, { "code": null, "e": 31736, "s": 31694, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 31779, "s": 31736, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31841, "s": 31779, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31886, "s": 31841, "text": "Convert a string to an integer in JavaScript" } ]
DateTime.AddMonths() Method in C# - GeeksforGeeks
18 Jan, 2019 This method is used to return a new DateTime that adds the specified number of months to the value of this instance. Syntax: public DateTime AddMonths (int months); Here, months is the number of months. The months parameter can be negative or positive. Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and months. Exception: This method will throw ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue or months is less than -120, 000 or greater than 120, 000. Below programs illustrate the use of the above-discussed method: Example 1: // C# program to demonstrate the// DateTime.AddMonths(Int32) Methodusing System; class GFG { // Main Methodpublic static void Main(){ // Creating a DateTime object DateTime d1 = new DateTime(2018, 4, 17); for (int i = 0; i <= 10; i++) { // using the method Console.WriteLine(d1.AddMonths(i).ToString("d")); } Console.WriteLine("In Leap Years:"); // Creating a DateTime object // by taking a leap year // It is 31st March 2016 DateTime d2 = new DateTime(2016, 03, 31); // taking a month value int m = 1; // using the method // Result will be 30 April 2016 Console.WriteLine(d2.AddMonths(m).ToString("d")); }} Output: 04/17/2018 05/17/2018 06/17/2018 07/17/2018 08/17/2018 09/17/2018 10/17/2018 11/17/2018 12/17/2018 01/17/2019 02/17/2019 In Leap Years: 04/30/2016 Example 2: // C# program to demonstrate the// DateTime.AddMonths(Int32) Methodusing System; class GFG { // Main Methodpublic static void Main(){ // Creating a DateTime object // taking MaxValue DateTime d1 = DateTime.MaxValue; // taking a month MaxValue int m = 12005; // using the method will // give an runtime error // as months parameter is // greater than 12000 Console.WriteLine(d1.AddMonths(m).ToString("d"));}} Runtime Error: Unhandled Exception:System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime.Parameter name: months Note: This method does not change the value of this DateTime object. Instead, it returns a new DateTime object whose value is the result of this operation. This calculates the resulting month and year, taking into account leap years and the number of days in a month, then adjusts the day part of the resulting DateTime object. The time-of-day part of the resulting DateTime object remains the same as this instance. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addmonths?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. Comments Old Comments C# Dictionary with examples C# | Method Overriding C# | Class and Object Difference between Ref and Out keywords in C# C# | Constructors Introduction to .NET Framework Extension Method in C# C# | Abstract Classes C# | Delegates C# | Data Types
[ { "code": null, "e": 24504, "s": 24476, "text": "\n18 Jan, 2019" }, { "code": null, "e": 24621, "s": 24504, "text": "This method is used to return a new DateTime that adds the specified number of months to the value of this instance." }, { "code": null, "e": 24629, "s": 24621, "text": "Syntax:" }, { "code": null, "e": 24669, "s": 24629, "text": "public DateTime AddMonths (int months);" }, { "code": null, "e": 24757, "s": 24669, "text": "Here, months is the number of months. The months parameter can be negative or positive." }, { "code": null, "e": 24886, "s": 24757, "text": "Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and months." }, { "code": null, "e": 25080, "s": 24886, "text": "Exception: This method will throw ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue or months is less than -120, 000 or greater than 120, 000." }, { "code": null, "e": 25145, "s": 25080, "text": "Below programs illustrate the use of the above-discussed method:" }, { "code": null, "e": 25156, "s": 25145, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// DateTime.AddMonths(Int32) Methodusing System; class GFG { // Main Methodpublic static void Main(){ // Creating a DateTime object DateTime d1 = new DateTime(2018, 4, 17); for (int i = 0; i <= 10; i++) { // using the method Console.WriteLine(d1.AddMonths(i).ToString(\"d\")); } Console.WriteLine(\"In Leap Years:\"); // Creating a DateTime object // by taking a leap year // It is 31st March 2016 DateTime d2 = new DateTime(2016, 03, 31); // taking a month value int m = 1; // using the method // Result will be 30 April 2016 Console.WriteLine(d2.AddMonths(m).ToString(\"d\")); }}", "e": 25876, "s": 25156, "text": null }, { "code": null, "e": 25884, "s": 25876, "text": "Output:" }, { "code": null, "e": 26032, "s": 25884, "text": "04/17/2018\n05/17/2018\n06/17/2018\n07/17/2018\n08/17/2018\n09/17/2018\n10/17/2018\n11/17/2018\n12/17/2018\n01/17/2019\n02/17/2019\nIn Leap Years:\n04/30/2016\n" }, { "code": null, "e": 26043, "s": 26032, "text": "Example 2:" }, { "code": "// C# program to demonstrate the// DateTime.AddMonths(Int32) Methodusing System; class GFG { // Main Methodpublic static void Main(){ // Creating a DateTime object // taking MaxValue DateTime d1 = DateTime.MaxValue; // taking a month MaxValue int m = 12005; // using the method will // give an runtime error // as months parameter is // greater than 12000 Console.WriteLine(d1.AddMonths(m).ToString(\"d\"));}}", "e": 26490, "s": 26043, "text": null }, { "code": null, "e": 26505, "s": 26490, "text": "Runtime Error:" }, { "code": null, "e": 26654, "s": 26505, "text": "Unhandled Exception:System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime.Parameter name: months" }, { "code": null, "e": 26660, "s": 26654, "text": "Note:" }, { "code": null, "e": 26810, "s": 26660, "text": "This method does not change the value of this DateTime object. Instead, it returns a new DateTime object whose value is the result of this operation." }, { "code": null, "e": 26982, "s": 26810, "text": "This calculates the resulting month and year, taking into account leap years and the number of days in a month, then adjusts the day part of the resulting DateTime object." }, { "code": null, "e": 27071, "s": 26982, "text": "The time-of-day part of the resulting DateTime object remains the same as this instance." }, { "code": null, "e": 27082, "s": 27071, "text": "Reference:" }, { "code": null, "e": 27176, "s": 27082, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addmonths?view=netframework-4.7.2" }, { "code": null, "e": 27199, "s": 27176, "text": "CSharp DateTime Struct" }, { "code": null, "e": 27213, "s": 27199, "text": "CSharp-method" }, { "code": null, "e": 27216, "s": 27213, "text": "C#" }, { "code": null, "e": 27314, "s": 27216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27323, "s": 27314, "text": "Comments" }, { "code": null, "e": 27336, "s": 27323, "text": "Old Comments" }, { "code": null, "e": 27364, "s": 27336, "text": "C# Dictionary with examples" }, { "code": null, "e": 27387, "s": 27364, "text": "C# | Method Overriding" }, { "code": null, "e": 27409, "s": 27387, "text": "C# | Class and Object" }, { "code": null, "e": 27455, "s": 27409, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27473, "s": 27455, "text": "C# | Constructors" }, { "code": null, "e": 27504, "s": 27473, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27527, "s": 27504, "text": "Extension Method in C#" }, { "code": null, "e": 27549, "s": 27527, "text": "C# | Abstract Classes" }, { "code": null, "e": 27564, "s": 27549, "text": "C# | Delegates" } ]
Scrapy - Extracting Items
For extracting data from web pages, Scrapy uses a technique called selectors based on XPath and CSS expressions. Following are some examples of XPath expressions − /html/head/title − This will select the <title> element, inside the <head> element of an HTML document. /html/head/title − This will select the <title> element, inside the <head> element of an HTML document. /html/head/title/text() − This will select the text within the same <title> element. /html/head/title/text() − This will select the text within the same <title> element. //td − This will select all the elements from <td>. //td − This will select all the elements from <td>. //div[@class = "slice"] − This will select all elements from div which contain an attribute class = "slice" //div[@class = "slice"] − This will select all elements from div which contain an attribute class = "slice" Selectors have four basic methods as shown in the following table − extract() It returns a unicode string along with the selected data. re() It returns a list of unicode strings, extracted when the regular expression was given as argument. xpath() It returns a list of selectors, which represents the nodes selected by the xpath expression given as an argument. css() It returns a list of selectors, which represents the nodes selected by the CSS expression given as an argument. To demonstrate the selectors with the built-in Scrapy shell, you need to have IPython installed in your system. The important thing here is, the URLs should be included within the quotes while running Scrapy; otherwise the URLs with '&' characters won't work. You can start a shell by using the following command in the project's top level directory − scrapy shell "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/" A shell will look like the following − [ ... Scrapy log here ... ] 2014-01-23 17:11:42-0400 [scrapy] DEBUG: Crawled (200) <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Books/>(referer: None) [s] Available Scrapy objects: [s] crawler <scrapy.crawler.Crawler object at 0x3636b50> [s] item {} [s] request <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Books/> [s] response <200 http://www.dmoz.org/Computers/Programming/Languages/Python/Books/> [s] settings <scrapy.settings.Settings object at 0x3fadc50> [s] spider <Spider 'default' at 0x3cebf50> [s] Useful shortcuts: [s] shelp() Shell help (print this help) [s] fetch(req_or_url) Fetch request (or URL) and update local objects [s] view(response) View response in a browser In [1]: When shell loads, you can access the body or header by using response.body and response.header respectively. Similarly, you can run queries on the response using response.selector.xpath() or response.selector.css(). For instance − In [1]: response.xpath('//title') Out[1]: [<Selector xpath = '//title' data = u'<title>My Book - Scrapy'>] In [2]: response.xpath('//title').extract() Out[2]: [u'<title>My Book - Scrapy: Index: Chapters</title>'] In [3]: response.xpath('//title/text()') Out[3]: [<Selector xpath = '//title/text()' data = u'My Book - Scrapy: Index:'>] In [4]: response.xpath('//title/text()').extract() Out[4]: [u'My Book - Scrapy: Index: Chapters'] In [5]: response.xpath('//title/text()').re('(\w+):') Out[5]: [u'Scrapy', u'Index', u'Chapters'] To extract data from a normal HTML site, we have to inspect the source code of the site to get XPaths. After inspecting, you can see that the data will be in the ul tag. Select the elements within li tag. The following lines of code shows extraction of different types of data − For selecting data within li tag − response.xpath('//ul/li') For selecting descriptions − response.xpath('//ul/li/text()').extract() For selecting site titles − response.xpath('//ul/li/a/text()').extract() For selecting site links − response.xpath('//ul/li/a/@href').extract() The following code demonstrates the use of above extractors − import scrapy class MyprojectSpider(scrapy.Spider): name = "project" allowed_domains = ["dmoz.org"] start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" ] def parse(self, response): for sel in response.xpath('//ul/li'): title = sel.xpath('a/text()').extract() link = sel.xpath('a/@href').extract() desc = sel.xpath('text()').extract() print title, link, desc 27 Lectures 3.5 hours Attreya Bhatt Print Add Notes Bookmark this page
[ { "code": null, "e": 2401, "s": 2237, "text": "For extracting data from web pages, Scrapy uses a technique called selectors based on XPath and CSS expressions. Following are some examples of XPath expressions −" }, { "code": null, "e": 2505, "s": 2401, "text": "/html/head/title − This will select the <title> element, inside the <head> element of an HTML document." }, { "code": null, "e": 2609, "s": 2505, "text": "/html/head/title − This will select the <title> element, inside the <head> element of an HTML document." }, { "code": null, "e": 2694, "s": 2609, "text": "/html/head/title/text() − This will select the text within the same <title> element." }, { "code": null, "e": 2779, "s": 2694, "text": "/html/head/title/text() − This will select the text within the same <title> element." }, { "code": null, "e": 2831, "s": 2779, "text": "//td − This will select all the elements from <td>." }, { "code": null, "e": 2883, "s": 2831, "text": "//td − This will select all the elements from <td>." }, { "code": null, "e": 2991, "s": 2883, "text": "//div[@class = \"slice\"] − This will select all elements from div which contain an attribute class = \"slice\"" }, { "code": null, "e": 3099, "s": 2991, "text": "//div[@class = \"slice\"] − This will select all elements from div which contain an attribute class = \"slice\"" }, { "code": null, "e": 3167, "s": 3099, "text": "Selectors have four basic methods as shown in the following table −" }, { "code": null, "e": 3177, "s": 3167, "text": "extract()" }, { "code": null, "e": 3235, "s": 3177, "text": "It returns a unicode string along with the selected data." }, { "code": null, "e": 3240, "s": 3235, "text": "re()" }, { "code": null, "e": 3339, "s": 3240, "text": "It returns a list of unicode strings, extracted when the regular expression was given as argument." }, { "code": null, "e": 3347, "s": 3339, "text": "xpath()" }, { "code": null, "e": 3461, "s": 3347, "text": "It returns a list of selectors, which represents the nodes selected by the xpath expression given as an argument." }, { "code": null, "e": 3467, "s": 3461, "text": "css()" }, { "code": null, "e": 3579, "s": 3467, "text": "It returns a list of selectors, which represents the nodes selected by the CSS expression given as an argument." }, { "code": null, "e": 3931, "s": 3579, "text": "To demonstrate the selectors with the built-in Scrapy shell, you need to have IPython installed in your system. The important thing here is, the URLs should be included within the quotes while running Scrapy; otherwise the URLs with '&' characters won't work. You can start a shell by using the following command in the project's top level directory −" }, { "code": null, "e": 4013, "s": 3931, "text": "scrapy shell \"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/\"\n" }, { "code": null, "e": 4052, "s": 4013, "text": "A shell will look like the following −" }, { "code": null, "e": 4835, "s": 4052, "text": "[ ... Scrapy log here ... ]\n\n2014-01-23 17:11:42-0400 [scrapy] DEBUG: Crawled (200) \n<GET http://www.dmoz.org/Computers/Programming/Languages/Python/Books/>(referer: None)\n[s] Available Scrapy objects:\n[s] crawler <scrapy.crawler.Crawler object at 0x3636b50>\n[s] item {}\n[s] request <GET http://www.dmoz.org/Computers/Programming/Languages/Python/Books/>\n[s] response <200 http://www.dmoz.org/Computers/Programming/Languages/Python/Books/>\n[s] settings <scrapy.settings.Settings object at 0x3fadc50>\n[s] spider <Spider 'default' at 0x3cebf50>\n[s] Useful shortcuts:\n[s] shelp() Shell help (print this help)\n[s] fetch(req_or_url) Fetch request (or URL) and update local objects\n[s] view(response) View response in a browser\n\nIn [1]:\n" }, { "code": null, "e": 5051, "s": 4835, "text": "When shell loads, you can access the body or header by using response.body and response.header respectively. Similarly, you can run queries on the response using response.selector.xpath() or response.selector.css()." }, { "code": null, "e": 5066, "s": 5051, "text": "For instance −" }, { "code": null, "e": 5600, "s": 5066, "text": "In [1]: response.xpath('//title')\nOut[1]: [<Selector xpath = '//title' data = u'<title>My Book - Scrapy'>]\n\nIn [2]: response.xpath('//title').extract()\nOut[2]: [u'<title>My Book - Scrapy: Index: Chapters</title>']\n\nIn [3]: response.xpath('//title/text()')\nOut[3]: [<Selector xpath = '//title/text()' data = u'My Book - Scrapy: Index:'>]\n\nIn [4]: response.xpath('//title/text()').extract()\nOut[4]: [u'My Book - Scrapy: Index: Chapters']\n\nIn [5]: response.xpath('//title/text()').re('(\\w+):')\nOut[5]: [u'Scrapy', u'Index', u'Chapters']" }, { "code": null, "e": 5805, "s": 5600, "text": "To extract data from a normal HTML site, we have to inspect the source code of the site to get XPaths. After inspecting, you can see that the data will be in the ul tag. Select the elements within li tag." }, { "code": null, "e": 5879, "s": 5805, "text": "The following lines of code shows extraction of different types of data −" }, { "code": null, "e": 5914, "s": 5879, "text": "For selecting data within li tag −" }, { "code": null, "e": 5940, "s": 5914, "text": "response.xpath('//ul/li')" }, { "code": null, "e": 5969, "s": 5940, "text": "For selecting descriptions −" }, { "code": null, "e": 6012, "s": 5969, "text": "response.xpath('//ul/li/text()').extract()" }, { "code": null, "e": 6040, "s": 6012, "text": "For selecting site titles −" }, { "code": null, "e": 6085, "s": 6040, "text": "response.xpath('//ul/li/a/text()').extract()" }, { "code": null, "e": 6112, "s": 6085, "text": "For selecting site links −" }, { "code": null, "e": 6156, "s": 6112, "text": "response.xpath('//ul/li/a/@href').extract()" }, { "code": null, "e": 6218, "s": 6156, "text": "The following code demonstrates the use of above extractors −" }, { "code": null, "e": 6754, "s": 6218, "text": "import scrapy\n\nclass MyprojectSpider(scrapy.Spider):\n name = \"project\"\n allowed_domains = [\"dmoz.org\"]\n \n start_urls = [\n \"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/\",\n \"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/\"\n ]\n def parse(self, response):\n for sel in response.xpath('//ul/li'):\n title = sel.xpath('a/text()').extract()\n link = sel.xpath('a/@href').extract()\n desc = sel.xpath('text()').extract()\n print title, link, desc" }, { "code": null, "e": 6789, "s": 6754, "text": "\n 27 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6804, "s": 6789, "text": " Attreya Bhatt" }, { "code": null, "e": 6811, "s": 6804, "text": " Print" }, { "code": null, "e": 6822, "s": 6811, "text": " Add Notes" } ]
How to implement an instance method of an arbitrary object using method reference in Java?
A method reference is a new feature in Java 8, which is related to Lambda Expression. It can allow us to reference constructors or methods without executing them. The method references and lambda expressions are similar in that they both require a target type that consists of a compatible functional interface. Class :: instanceMethodName import java.util.*; import java.util.function.*; public class ArbitraryObjectMethodRefTest { public static void main(String[] args) { List<Person> persons = new ArrayList<Person>(); persons.add(new Person("Raja", 30)); persons.add(new Person("Jai", 25)); persons.add(new Person("Adithya", 20)); persons.add(new Person("Surya", 35)); persons.add(new Person("Ravi", 32)); List ages = ArbitraryObjectMethodRefTest.listAllAges(persons, Person :: getAge); System.out.println("Printing out all ages: \n" + ages); } private static List listAllAges(List person, Function<Person, Integer> f) { List result = new ArrayList(); person.forEach(x -> result.add(f.apply((Person)x))); return result; } private static class Person { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } } Printing out all ages: [30, 25, 20, 35, 32]
[ { "code": null, "e": 1374, "s": 1062, "text": "A method reference is a new feature in Java 8, which is related to Lambda Expression. It can allow us to reference constructors or methods without executing them. The method references and lambda expressions are similar in that they both require a target type that consists of a compatible functional interface." }, { "code": null, "e": 1402, "s": 1374, "text": "Class :: instanceMethodName" }, { "code": null, "e": 2492, "s": 1402, "text": "import java.util.*;\nimport java.util.function.*;\n\npublic class ArbitraryObjectMethodRefTest {\n public static void main(String[] args) {\n List<Person> persons = new ArrayList<Person>();\n persons.add(new Person(\"Raja\", 30));\n persons.add(new Person(\"Jai\", 25));\n persons.add(new Person(\"Adithya\", 20));\n persons.add(new Person(\"Surya\", 35));\n persons.add(new Person(\"Ravi\", 32));\n List ages = ArbitraryObjectMethodRefTest.listAllAges(persons, Person :: getAge);\n System.out.println(\"Printing out all ages: \\n\" + ages);\n }\n private static List listAllAges(List person, Function<Person, Integer> f) {\n List result = new ArrayList();\n person.forEach(x -> result.add(f.apply((Person)x)));\n return result;\n }\n private static class Person {\n private final String name;\n private final int age;\n public Person(String name, int age) {\n this.name = name;\n this.age = age;\n }\n public String getName() {\n return name;\n }\n public int getAge() {\n return age;\n }\n }\n}" }, { "code": null, "e": 2536, "s": 2492, "text": "Printing out all ages:\n[30, 25, 20, 35, 32]" } ]
Composite Design Pattern in C++
Composite pattern is used where we need to treat a group of objects in similar way as a single object. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy. This type of design pattern comes under structural pattern as this pattern creates a tree structure of group of objects. This pattern creates a class that contains group of its own objects. This class provides ways to modify its group of same objects. We are demonstrating use of composite pattern via following example in which we will show employees hierarchy of an organization. Here we can see the composite and leaf both classes are implementing the component. The important part is the composite class, this is also containing the component objects shown by the composition relationship. #include <iostream> #include <vector> using namespace std; class PageObject { public: virtual void addItem(PageObject a) { } virtual void removeItem() { } virtual void deleteItem(PageObject a) { } }; class Page : public PageObject { public: void addItem(PageObject a) { cout << "Item added into the page" << endl; } void removeItem() { cout << "Item Removed from page" << endl; } void deleteItem(PageObject a) { cout << "Item Deleted from Page" << endl; } }; class Copy : public PageObject { vector<PageObject> copyPages; public: void AddElement(PageObject a) { copyPages.push_back(a); } void addItem(PageObject a) { cout << "Item added to the copy" << endl; } void removeItem() { cout << "Item removed from the copy" << endl; } void deleteItem(PageObject a) { cout << "Item deleted from the copy"; } }; int main() { Page p1; Page p2; Copy myCopy; myCopy.AddElement(p1); myCopy.AddElement(p2); myCopy.addItem(p1); p1.addItem(p2); myCopy.removeItem(); p2.removeItem(); } Item added to the copy Item added into the page Item removed from the copy Item Removed from page
[ { "code": null, "e": 1395, "s": 1062, "text": "Composite pattern is used where we need to treat a group of objects in similar way as a single object. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy. This type of design pattern comes under structural pattern as this pattern creates a tree structure of group of objects." }, { "code": null, "e": 1526, "s": 1395, "text": "This pattern creates a class that contains group of its own objects. This class provides ways to modify its group of same objects." }, { "code": null, "e": 1656, "s": 1526, "text": "We are demonstrating use of composite pattern via following example in which we will show employees hierarchy of an organization." }, { "code": null, "e": 1868, "s": 1656, "text": "Here we can see the composite and leaf both classes are implementing the component. The important part is the composite class, this is also containing the component objects shown by the composition relationship." }, { "code": null, "e": 3018, "s": 1868, "text": "#include <iostream>\n#include <vector>\nusing namespace std;\nclass PageObject {\n public:\n virtual void addItem(PageObject a) { }\n virtual void removeItem() { }\n virtual void deleteItem(PageObject a) { }\n};\nclass Page : public PageObject {\n public:\n void addItem(PageObject a) {\n cout << \"Item added into the page\" << endl;\n }\n void removeItem() {\n cout << \"Item Removed from page\" << endl;\n }\n void deleteItem(PageObject a) {\n cout << \"Item Deleted from Page\" << endl;\n }\n};\nclass Copy : public PageObject {\n vector<PageObject> copyPages;\n public:\n void AddElement(PageObject a) {\n copyPages.push_back(a);\n }\n void addItem(PageObject a) {\n cout << \"Item added to the copy\" << endl;\n }\n void removeItem() {\n cout << \"Item removed from the copy\" << endl;\n }\n void deleteItem(PageObject a) {\n cout << \"Item deleted from the copy\";\n }\n};\nint main() {\n Page p1;\n Page p2;\n Copy myCopy;\n myCopy.AddElement(p1);\n myCopy.AddElement(p2);\n myCopy.addItem(p1);\n p1.addItem(p2);\n myCopy.removeItem();\n p2.removeItem();\n}" }, { "code": null, "e": 3116, "s": 3018, "text": "Item added to the copy\nItem added into the page\nItem removed from the copy\nItem Removed from page" } ]
Selenium Webdriver - Identify Multiple Elements
In this chapter, we will learn how to identify multiple elements by various options. Let us begin by understanding identifying multiple elements by Id. It is not recommended to identify multiple elements by the locator id, since the value of an id attribute is unique to an element and is applicable to a single element on the page. Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the elements. We can use the class attribute for elements for their identification and utilise the method find_elements_by_class_name. With this, all the elements with the matching value of the attribute class are returned in the form of list. In case there are no elements with the matching value of the class attribute, an empty list shall be returned. The syntax for identifying multiple elements by Classname is as follows − driver.find_elements_by_class_name("value of class attribute") Let us see the html code of webelements having class attribute as given below − The value of the class attribute highlighted in the above image is toc chapters. Let us try to count the number of such webelements. The code implementation for identifying multiple elements by Classname is as follows − from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #implicit wait time driver.implicitly_wait(5) #url launch driver.get("https://www.tutorialspoint.com/about/about_careers.htm") #identify elements with class attribute l = driver.find_elements_by_class_name("chapters") #count elements s = len(l) print('Count is:') print(s) #driver quit driver.quit() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the total count of webelements having the class attributes value chapters (obtained from the len method) - 2 gets printed in the console. Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the elements. We can use the tagname for elements for their identification and utilise the method find_elements_by_tag_name. With this, all the elements with the matching value of the tagname are returned in the form of list. In case there are no elements with the matching value of the tagname, an empty list shall be returned. The syntax for identifying multiple elements by Tagname is as follows − driver.find_elements_by_tag_name("value of tagname") Let us see the html code of a webelement, which is as follows − The value of the tagname highlighted in the above image is h4. Let us try to count the number of webelements having tagname as h4. The code implementation for identifying multiple elements by Tagname is as follows − from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #implicit wait time driver.implicitly_wait(5) #url launch driver.get("https://www.tutorialspoint.com/index.htm") #identify elements with tagname l = driver.find_elements_by_tag_name("h4") #count elements s = len(l) print('Count is:') print(s) #driver quit driver.quit() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the total count of webelement having the tagname as h4 (obtained from the len method) - 1 gets printed in the console. Once we navigate to a webpage, we may have to interact with the webelements by clicking a link to complete our automation test case. The partial link text is used for elements having the anchor tag. For this, our first job is to identify the elements. We can use the partial link text attribute for elements for their identification and utlize the method find_elements_by_partial_link_text. With this, all the elements with the matching value of the given partial link text are returned in the form of a list. In case there are no elements with the matching value of the partial link text, an empty list shall be returned. The syntax for identifying multiple elements by Partial Link Text is as follows − driver.find_elements_by_partial_link_text("value of partial link text") Let us see the html code of link, which is as follows − The link highlighted - Terms of Use in the above image has a tagname - a and the partial link text - Terms. Let us try to identify the text after identifying it. The code implementation for identifying multiple elements by Partial Link Text is as follows − from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #implicit wait time driver.implicitly_wait(5) #url launch driver.get("https://www.tutorialspoint.com/about/about_careers.htm") #identify elements with partial link text l = driver.find_elements_by_partial_link_text('Terms') #count elements s = len(l) #iterate through list for i in l: #obtain text t = i.text print('Text is: ' + t) #driver quit driver.quit() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the text of the link identified with the partial link text locator (obtained from the text method) - Terms of use gets printed in the console. Once we navigate to a webpage, we may have to interact with the webelements by clicking a link to complete our automation test case. The link text is used for elements having the anchor tag. For this, our first job is to identify the elements. We can use the link text attribute for elements for their identification and utilize the method find_elements_by_link_text. With this, all the elements with the matching value of the given link text are returned in the form of a list. In case there are no elements with the matching value of the link text, an empty list shall be returned. The syntax for identifying multiple elements by Link Text is as follows − driver.find_elements_by_link_text("value of link text") Let us see the html code of link, which is as follows − The link highlighted - Cookies Policy in the above image has a tagname - a and the link text - Cookies Policy. Let us try to identify the text after identifying it. The code implementation for identifying multiple elements by Link Text is as follows − from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #implicit wait time driver.implicitly_wait(5) #url launch driver.get("https://www.tutorialspoint.com/about/about_careers.htm") #identify elements with link text l = driver.find_elements_by_link_text('Cookies Policy') #count elements s = len(l) #iterate through list for i in l: #obtain text t = i.text print('Text is: ' + t) #driver quit driver.quit() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the text of the link identified with the link text locator (obtained from the text method) - Cookies Policy gets printed in the console. Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the elements. We can use the name attribute of elements for their identification and utilize the method find_elements_by_name. With this, the elements with the matching value of the attribute name are returned in the form of a list. In case there is no element with the matching value of the name attribute, an empty list shall be returned. The syntax for identifying multiple elements by Name is as follows − driver.find_elements_by_name("value of name attribute") Let us see the html code of an webelement, which is as follows − The edit box highlighted in the above image has a name attribute with value search. Let us try to input some text into this edit box after identifying it. The code implementation for identifying multiple elements by Name is as follows − from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #implicit wait time driver.implicitly_wait(5) #url launch driver.get("https://www.tutorialspoint.com/index.htm") #identify elements with name attribute l = driver.find_elements_by_name('search') #count elements s = len(l) #iterate through list for i in l: #obtain text t = i.send_keys('Selenium Python') v = i.get_attribute('value') print('Value entered is: ' + v) #driver quit driver.quit() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium Python gets printed in the console. Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the elements. We can create a css selector for their identification and utilize the method find_elements_by_css_selector. With this, the elements with the matching value of the given css are returned in the form of list. In case there is no element with the matching value of the css, an empty list shall be returned. The syntax for identifying multiple elements by CSS Selector is as follows − driver.find_elements_by_css_selector("value of css") The rules to create a css expression are discussed below − To identify the element with css, the expression should be tagname[attribute='value']. We can also specifically use the id attribute to create a css expression. To identify the element with css, the expression should be tagname[attribute='value']. We can also specifically use the id attribute to create a css expression. With id, the format of a css expression should be tagname#id. For example, input#txt [here input is the tagname and the txt is the value of the id attribute]. With id, the format of a css expression should be tagname#id. For example, input#txt [here input is the tagname and the txt is the value of the id attribute]. With class, the format of css expression should be tagname.class . For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute]. With class, the format of css expression should be tagname.class . For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute]. If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n). If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n). In the above code, if we want to identify the fourth li child of ul[Questions and Answers], the css expression should be ul.reading li:nth-of-type(4). Similarly, to identify the last child, the css expression should be ul.reading li:last-child. For attributes whose values are dynamically changing, we can use ^= to locate an element whose attribute value starts with a particular text. For example, input[name^='qa'] [here input is the tagname and the value of the name attribute starts with qa]. For attributes whose values are dynamically changing, we can use $= to locate an element whose attribute value ends with a particular text. For example, input[class$='txt'] Here, input is the tagname and the value of the class attribute ends with txt. For attributes whose values are dynamically changing, we can use *= to locate an element whose attribute value contains a specific sub-text. For example, input[name*='nam'] Here, input is the tagname and the value of the name attribute contains the sub-text nam. Let us see the html code of a webelement − The edit box highlighted in the above image has a name attribute with value search, the css expression should be input[name='search']. Let us try to input some text into this edit box after identifying it. The code implementation for identifying multiple elements by CSS Selector is as follows − from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #implicit wait time driver.implicitly_wait(5) #url launch driver.get("https://www.tutorialspoint.com/index.htm") #identify elements with css l = driver.find_elements_by_css_selector("input[name='search']") #count elements s = len(l) #iterate through list for i in l: #obtain text t = i.send_keys('Tutorialspoint') v = i.get_attribute('value') print('Value entered is: ' + v) #driver quit driver.quit() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Tutorialspoint gets printed in the console. Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the elements. We can create an xpath for their identification and utilize the method find_elements_by_xpath. With this, the elements with the matching value of the given xpath are returned in the form of a list. In case there is no element with the matching value of the xpath, an empty list shall be returned. The syntax for identifying multiple elements by Xpath is as follows: driver.find_elements_by_xpath("value of xpath") The rules to create a xpath expression are discussed below − To identify the element with xpath, the expression should be //tagname[@attribute='value']. There can be two types of xpath – relative and absolute. The absolute xpath begins with / symbol and starts from the root node upto the element that we want to identify. To identify the element with xpath, the expression should be //tagname[@attribute='value']. There can be two types of xpath – relative and absolute. The absolute xpath begins with / symbol and starts from the root node upto the element that we want to identify. For example, /html/body/div[1]/div/div[1]/a The relative xpath begins with // symbol and does not start from the root node. The relative xpath begins with // symbol and does not start from the root node. For example, //img[@alt='tutorialspoint'] Let us see the html code of the highlighted link - Home starting from the root. The absolute xpath for the element Home can be as follows − /html/body/div[1]/div/div[1]/a. The relative xpath for element Home can be as follows − //a[@title='TutorialsPoint - Home']. There are also functions available which help to frame relative xpath expressions − text() It is used to identify an element with the help of the visible text on the page. The xpath expression is as follows − //*[text()='Home']. starts-with It is used to identify an element whose attribute value begins with a specific text. This function is normally used for attributes whose value changes on each page load. Let us see the html of the element Q/A − The xpath expression should be as follows − //a[starts-with(@title, 'Questions &')]. contains() It identifies an element whose attribute value contains a sub-text. This function is normally used for attributes whose value changes on each page load. The xpath expression is as follows − //a[contains(@title, 'Questions & Answers')]. Let us see the html code of a webelement − The edit box highlighted in the above image has a name attribute with value search, the xpath expression should be //input[@name='search']. Let us try to input some text into this edit box after identifying it. The code implementation for identifying multiple elements by Xpath is as follows − from selenium import webdriver driver = webdriver.Chrome(executable_path='../drivers/chromedriver') #implicit wait time driver.implicitly_wait(5) #url launch driver.get("https://www.tutorialspoint.com/index.htm") #identify elements with xpath l = driver.find_elements_by_xpath("//input[@name='search']") #count elements s = len(l) #iterate through list for i in l: #obtain text t = i.send_keys('Tutorialspoint - Selenium') v = i.get_attribute('value') print('Value entered is: ' + v) #driver quit driver.quit() The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Tutorialspoint - Selenium gets printed in the console. 46 Lectures 5.5 hours Aditya Dua 296 Lectures 146 hours Arun Motoori 411 Lectures 38.5 hours In28Minutes Official 22 Lectures 7 hours Arun Motoori 118 Lectures 17 hours Arun Motoori 278 Lectures 38.5 hours Lets Kode It Print Add Notes Bookmark this page
[ { "code": null, "e": 2355, "s": 2203, "text": "In this chapter, we will learn how to identify multiple elements by various options. Let us begin by understanding identifying multiple elements by Id." }, { "code": null, "e": 2536, "s": 2355, "text": "It is not recommended to identify multiple elements by the locator id, since the value of an id attribute is unique to an element and is applicable to a single element on the page." }, { "code": null, "e": 2741, "s": 2536, "text": "Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case." }, { "code": null, "e": 3024, "s": 2741, "text": "For this, our first job is to identify the elements. We can use the class attribute for elements for their identification and utilise the method find_elements_by_class_name. With this, all the elements with the matching value of the attribute class are returned in the form of list." }, { "code": null, "e": 3135, "s": 3024, "text": "In case there are no elements with the matching value of the class attribute, an empty list shall be returned." }, { "code": null, "e": 3209, "s": 3135, "text": "The syntax for identifying multiple elements by Classname is as follows −" }, { "code": null, "e": 3273, "s": 3209, "text": "driver.find_elements_by_class_name(\"value of class attribute\")\n" }, { "code": null, "e": 3353, "s": 3273, "text": "Let us see the html code of webelements having class attribute as given below −" }, { "code": null, "e": 3486, "s": 3353, "text": "The value of the class attribute highlighted in the above image is toc chapters. Let us try to count the number of such webelements." }, { "code": null, "e": 3573, "s": 3486, "text": "The code implementation for identifying multiple elements by Classname is as follows −" }, { "code": null, "e": 3973, "s": 3573, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify elements with class attribute\nl = driver.find_elements_by_class_name(\"chapters\")\n#count elements\ns = len(l)\nprint('Count is:')\nprint(s)\n#driver quit\ndriver.quit()" }, { "code": null, "e": 4231, "s": 3973, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the total count of webelements having the class attributes value chapters (obtained from the len method) - 2 gets printed in the console." }, { "code": null, "e": 4436, "s": 4231, "text": "Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case." }, { "code": null, "e": 4701, "s": 4436, "text": "For this, our first job is to identify the elements. We can use the tagname for elements for their identification and utilise the method find_elements_by_tag_name. With this, all the elements with the matching value of the tagname are returned in the form of list." }, { "code": null, "e": 4804, "s": 4701, "text": "In case there are no elements with the matching value of the tagname, an empty list shall be returned." }, { "code": null, "e": 4876, "s": 4804, "text": "The syntax for identifying multiple elements by Tagname is as follows −" }, { "code": null, "e": 4930, "s": 4876, "text": "driver.find_elements_by_tag_name(\"value of tagname\")\n" }, { "code": null, "e": 4994, "s": 4930, "text": "Let us see the html code of a webelement, which is as follows −" }, { "code": null, "e": 5125, "s": 4994, "text": "The value of the tagname highlighted in the above image is h4. Let us try to count the number of webelements having tagname as h4." }, { "code": null, "e": 5210, "s": 5125, "text": "The code implementation for identifying multiple elements by Tagname is as follows −" }, { "code": null, "e": 5580, "s": 5210, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify elements with tagname\nl = driver.find_elements_by_tag_name(\"h4\")\n#count elements\ns = len(l)\nprint('Count is:')\nprint(s)\n#driver quit\ndriver.quit()" }, { "code": null, "e": 5819, "s": 5580, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the total count of webelement having the tagname as h4 (obtained from the len method) - 1 gets printed in the console." }, { "code": null, "e": 6018, "s": 5819, "text": "Once we navigate to a webpage, we may have to interact with the webelements by clicking a link to complete our automation test case. The partial link text is used for elements having the anchor tag." }, { "code": null, "e": 6329, "s": 6018, "text": "For this, our first job is to identify the elements. We can use the partial link text attribute for elements for their identification and utlize the method find_elements_by_partial_link_text. With this, all the elements with the matching value of the given partial link text are returned in the form of a list." }, { "code": null, "e": 6442, "s": 6329, "text": "In case there are no elements with the matching value of the partial link text, an empty list shall be returned." }, { "code": null, "e": 6524, "s": 6442, "text": "The syntax for identifying multiple elements by Partial Link Text is as follows −" }, { "code": null, "e": 6597, "s": 6524, "text": "driver.find_elements_by_partial_link_text(\"value of partial link text\")\n" }, { "code": null, "e": 6653, "s": 6597, "text": "Let us see the html code of link, which is as follows −" }, { "code": null, "e": 6815, "s": 6653, "text": "The link highlighted - Terms of Use in the above image has a tagname - a and the partial link text - Terms. Let us try to identify the text after identifying it." }, { "code": null, "e": 6910, "s": 6815, "text": "The code implementation for identifying multiple elements by Partial Link Text is as follows −" }, { "code": null, "e": 7372, "s": 6910, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify elements with partial link text\nl = driver.find_elements_by_partial_link_text('Terms')\n#count elements\ns = len(l)\n#iterate through list\nfor i in l:\n#obtain text\n t = i.text\nprint('Text is: ' + t)\n#driver quit\ndriver.quit()" }, { "code": null, "e": 7635, "s": 7372, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the text of the link identified with the partial link text locator (obtained from the text method) - Terms of use gets printed in the console." }, { "code": null, "e": 7826, "s": 7635, "text": "Once we navigate to a webpage, we may have to interact with the webelements by clicking a link to complete our automation test case. The link text is used for elements having the anchor tag." }, { "code": null, "e": 8114, "s": 7826, "text": "For this, our first job is to identify the elements. We can use the link text attribute for elements for their identification and utilize the method find_elements_by_link_text. With this, all the elements with the matching value of the given link text are returned in the form of a list." }, { "code": null, "e": 8219, "s": 8114, "text": "In case there are no elements with the matching value of the link text, an empty list shall be returned." }, { "code": null, "e": 8293, "s": 8219, "text": "The syntax for identifying multiple elements by Link Text is as follows −" }, { "code": null, "e": 8350, "s": 8293, "text": "driver.find_elements_by_link_text(\"value of link text\")\n" }, { "code": null, "e": 8406, "s": 8350, "text": "Let us see the html code of link, which is as follows −" }, { "code": null, "e": 8571, "s": 8406, "text": "The link highlighted - Cookies Policy in the above image has a tagname - a and the link text - Cookies Policy. Let us try to identify the text after identifying it." }, { "code": null, "e": 8658, "s": 8571, "text": "The code implementation for identifying multiple elements by Link Text is as follows −" }, { "code": null, "e": 9113, "s": 8658, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify elements with link text\nl = driver.find_elements_by_link_text('Cookies Policy')\n#count elements\ns = len(l)\n#iterate through list\nfor i in l:\n#obtain text\n t = i.text\nprint('Text is: ' + t)\n#driver quit\ndriver.quit()" }, { "code": null, "e": 9370, "s": 9113, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the text of the link identified with the link text locator (obtained from the text method) - Cookies Policy gets printed in the console." }, { "code": null, "e": 9575, "s": 9370, "text": "Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case." }, { "code": null, "e": 9847, "s": 9575, "text": "For this, our first job is to identify the elements. We can use the name attribute of elements for their identification and utilize the method find_elements_by_name. With this, the elements with the matching value of the attribute name are returned in the form of a list." }, { "code": null, "e": 9955, "s": 9847, "text": "In case there is no element with the matching value of the name attribute, an empty list shall be returned." }, { "code": null, "e": 10024, "s": 9955, "text": "The syntax for identifying multiple elements by Name is as follows −" }, { "code": null, "e": 10081, "s": 10024, "text": "driver.find_elements_by_name(\"value of name attribute\")\n" }, { "code": null, "e": 10146, "s": 10081, "text": "Let us see the html code of an webelement, which is as follows −" }, { "code": null, "e": 10301, "s": 10146, "text": "The edit box highlighted in the above image has a name attribute with value search. Let us try to input some text into this edit box after identifying it." }, { "code": null, "e": 10383, "s": 10301, "text": "The code implementation for identifying multiple elements by Name is as follows −" }, { "code": null, "e": 10881, "s": 10383, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify elements with name attribute\nl = driver.find_elements_by_name('search')\n#count elements\ns = len(l)\n#iterate through list\nfor i in l:\n#obtain text\n t = i.send_keys('Selenium Python')\n v = i.get_attribute('value')\nprint('Value entered is: ' + v)\n#driver quit\ndriver.quit()" }, { "code": null, "e": 11127, "s": 10881, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium Python gets printed in the console." }, { "code": null, "e": 11332, "s": 11127, "text": "Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case." }, { "code": null, "e": 11592, "s": 11332, "text": "For this, our first job is to identify the elements. We can create a css selector for their identification and utilize the method find_elements_by_css_selector. With this, the elements with the matching value of the given css are returned in the form of list." }, { "code": null, "e": 11689, "s": 11592, "text": "In case there is no element with the matching value of the css, an empty list shall be returned." }, { "code": null, "e": 11766, "s": 11689, "text": "The syntax for identifying multiple elements by CSS Selector is as follows −" }, { "code": null, "e": 11820, "s": 11766, "text": "driver.find_elements_by_css_selector(\"value of css\")\n" }, { "code": null, "e": 11879, "s": 11820, "text": "The rules to create a css expression are discussed below −" }, { "code": null, "e": 12040, "s": 11879, "text": "To identify the element with css, the expression should be tagname[attribute='value']. We can also specifically use the id attribute to create a css expression." }, { "code": null, "e": 12201, "s": 12040, "text": "To identify the element with css, the expression should be tagname[attribute='value']. We can also specifically use the id attribute to create a css expression." }, { "code": null, "e": 12360, "s": 12201, "text": "With id, the format of a css expression should be tagname#id. For example, input#txt [here input is the tagname and the txt is the value of the id attribute]." }, { "code": null, "e": 12519, "s": 12360, "text": "With id, the format of a css expression should be tagname#id. For example, input#txt [here input is the tagname and the txt is the value of the id attribute]." }, { "code": null, "e": 12694, "s": 12519, "text": "With class, the format of css expression should be tagname.class . For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute]." }, { "code": null, "e": 12869, "s": 12694, "text": "With class, the format of css expression should be tagname.class . For example, input.cls-txt [here input is the tagname and the cls-txt is the value of the class attribute]." }, { "code": null, "e": 13001, "s": 12869, "text": "If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n)." }, { "code": null, "e": 13133, "s": 13001, "text": "If there are n children of a parent element, and we want to identify the nth child, the css expression should have nth-of –type(n)." }, { "code": null, "e": 13378, "s": 13133, "text": "In the above code, if we want to identify the fourth li child of ul[Questions and Answers], the css expression should be ul.reading li:nth-of-type(4). Similarly, to identify the last child, the css expression should be ul.reading li:last-child." }, { "code": null, "e": 13631, "s": 13378, "text": "For attributes whose values are dynamically changing, we can use ^= to locate an element whose attribute value starts with a particular text. For example, input[name^='qa'] [here input is the tagname and the value of the name attribute starts with qa]." }, { "code": null, "e": 13883, "s": 13631, "text": "For attributes whose values are dynamically changing, we can use $= to locate an element whose attribute value ends with a particular text. For example, input[class$='txt'] Here, input is the tagname and the value of the class attribute ends with txt." }, { "code": null, "e": 14146, "s": 13883, "text": "For attributes whose values are dynamically changing, we can use *= to locate an element whose attribute value contains a specific sub-text. For example, input[name*='nam'] Here, input is the tagname and the value of the name attribute contains the sub-text nam." }, { "code": null, "e": 14189, "s": 14146, "text": "Let us see the html code of a webelement −" }, { "code": null, "e": 14395, "s": 14189, "text": "The edit box highlighted in the above image has a name attribute with value search, the css expression should be input[name='search']. Let us try to input some text into this edit box after identifying it." }, { "code": null, "e": 14485, "s": 14395, "text": "The code implementation for identifying multiple elements by CSS Selector is as follows −" }, { "code": null, "e": 14993, "s": 14485, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify elements with css\nl = driver.find_elements_by_css_selector(\"input[name='search']\")\n#count elements\ns = len(l)\n#iterate through list\nfor i in l:\n#obtain text\n t = i.send_keys('Tutorialspoint')\n v = i.get_attribute('value')\nprint('Value entered is: ' + v)\n#driver quit\ndriver.quit()" }, { "code": null, "e": 15238, "s": 14993, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Tutorialspoint gets printed in the console." }, { "code": null, "e": 15443, "s": 15238, "text": "Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case." }, { "code": null, "e": 15694, "s": 15443, "text": "For this, our first job is to identify the elements. We can create an xpath for their identification and utilize the method find_elements_by_xpath. With this, the elements with the matching value of the given xpath are returned in the form of a list." }, { "code": null, "e": 15793, "s": 15694, "text": "In case there is no element with the matching value of the xpath, an empty list shall be returned." }, { "code": null, "e": 15862, "s": 15793, "text": "The syntax for identifying multiple elements by Xpath is as follows:" }, { "code": null, "e": 15911, "s": 15862, "text": "driver.find_elements_by_xpath(\"value of xpath\")\n" }, { "code": null, "e": 15972, "s": 15911, "text": "The rules to create a xpath expression are discussed below −" }, { "code": null, "e": 16234, "s": 15972, "text": "To identify the element with xpath, the expression should be //tagname[@attribute='value']. There can be two types of xpath – relative and absolute. The absolute xpath begins with / symbol and starts from the root node upto the element that we want to identify." }, { "code": null, "e": 16496, "s": 16234, "text": "To identify the element with xpath, the expression should be //tagname[@attribute='value']. There can be two types of xpath – relative and absolute. The absolute xpath begins with / symbol and starts from the root node upto the element that we want to identify." }, { "code": null, "e": 16509, "s": 16496, "text": "For example," }, { "code": null, "e": 16541, "s": 16509, "text": "/html/body/div[1]/div/div[1]/a\n" }, { "code": null, "e": 16621, "s": 16541, "text": "The relative xpath begins with // symbol and does not start from the root node." }, { "code": null, "e": 16701, "s": 16621, "text": "The relative xpath begins with // symbol and does not start from the root node." }, { "code": null, "e": 16714, "s": 16701, "text": "For example," }, { "code": null, "e": 16744, "s": 16714, "text": "//img[@alt='tutorialspoint']\n" }, { "code": null, "e": 16824, "s": 16744, "text": "Let us see the html code of the highlighted link - Home starting from the root." }, { "code": null, "e": 16884, "s": 16824, "text": "The absolute xpath for the element Home can be as follows −" }, { "code": null, "e": 16917, "s": 16884, "text": "/html/body/div[1]/div/div[1]/a.\n" }, { "code": null, "e": 16973, "s": 16917, "text": "The relative xpath for element Home can be as follows −" }, { "code": null, "e": 17011, "s": 16973, "text": "//a[@title='TutorialsPoint - Home'].\n" }, { "code": null, "e": 17095, "s": 17011, "text": "There are also functions available which help to frame relative xpath expressions −" }, { "code": null, "e": 17102, "s": 17095, "text": "text()" }, { "code": null, "e": 17220, "s": 17102, "text": "It is used to identify an element with the help of the visible text on the page. The xpath expression is as follows −" }, { "code": null, "e": 17241, "s": 17220, "text": "//*[text()='Home'].\n" }, { "code": null, "e": 17253, "s": 17241, "text": "starts-with" }, { "code": null, "e": 17423, "s": 17253, "text": "It is used to identify an element whose attribute value begins with a specific text. This function is normally used for attributes whose value changes on each page load." }, { "code": null, "e": 17464, "s": 17423, "text": "Let us see the html of the element Q/A −" }, { "code": null, "e": 17508, "s": 17464, "text": "The xpath expression should be as follows −" }, { "code": null, "e": 17550, "s": 17508, "text": "//a[starts-with(@title, 'Questions &')].\n" }, { "code": null, "e": 17561, "s": 17550, "text": "contains()" }, { "code": null, "e": 17714, "s": 17561, "text": "It identifies an element whose attribute value contains a sub-text. This function is normally used for attributes whose value changes on each page load." }, { "code": null, "e": 17751, "s": 17714, "text": "The xpath expression is as follows −" }, { "code": null, "e": 17798, "s": 17751, "text": "//a[contains(@title, 'Questions & Answers')].\n" }, { "code": null, "e": 17841, "s": 17798, "text": "Let us see the html code of a webelement −" }, { "code": null, "e": 18052, "s": 17841, "text": "The edit box highlighted in the above image has a name attribute with value search, the xpath expression should be //input[@name='search']. Let us try to input some text into this edit box after identifying it." }, { "code": null, "e": 18135, "s": 18052, "text": "The code implementation for identifying multiple elements by Xpath is as follows −" }, { "code": null, "e": 18652, "s": 18135, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#identify elements with xpath\nl = driver.find_elements_by_xpath(\"//input[@name='search']\")\n#count elements\ns = len(l)\n#iterate through list\nfor i in l:\n#obtain text\n t = i.send_keys('Tutorialspoint - Selenium')\n v = i.get_attribute('value')\nprint('Value entered is: ' + v)\n#driver quit\ndriver.quit()" }, { "code": null, "e": 18908, "s": 18652, "text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Tutorialspoint - Selenium gets printed in the console." }, { "code": null, "e": 18943, "s": 18908, "text": "\n 46 Lectures \n 5.5 hours \n" }, { "code": null, "e": 18955, "s": 18943, "text": " Aditya Dua" }, { "code": null, "e": 18991, "s": 18955, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 19005, "s": 18991, "text": " Arun Motoori" }, { "code": null, "e": 19042, "s": 19005, "text": "\n 411 Lectures \n 38.5 hours \n" }, { "code": null, "e": 19064, "s": 19042, "text": " In28Minutes Official" }, { "code": null, "e": 19097, "s": 19064, "text": "\n 22 Lectures \n 7 hours \n" }, { "code": null, "e": 19111, "s": 19097, "text": " Arun Motoori" }, { "code": null, "e": 19146, "s": 19111, "text": "\n 118 Lectures \n 17 hours \n" }, { "code": null, "e": 19160, "s": 19146, "text": " Arun Motoori" }, { "code": null, "e": 19197, "s": 19160, "text": "\n 278 Lectures \n 38.5 hours \n" }, { "code": null, "e": 19211, "s": 19197, "text": " Lets Kode It" }, { "code": null, "e": 19218, "s": 19211, "text": " Print" }, { "code": null, "e": 19229, "s": 19218, "text": " Add Notes" } ]
The potato train — using Python with extremely large numbers and arbitrary precision for binomial probability | by Florin Andrei | Towards Data Science
Math is hard, let’s go shopping — for tutorials, that is. I definitely wish I had read this tutorial before trying some things in Python that involve extremely large numbers (binomial probability for large values of n) and my code started to crash. But wait, I hear you saying, Python can handle arbitrarily large numbers, limited only by the amount of RAM. Sure, as long as those are all integers. Now try to mix some float values in, for good measure, and things start crashing. Arbitrarily large numbers mixed with arbitrary precision floats are not fun in vanilla Python. Let’s try to gradually increase the demands on integer arithmetic in Python while calculating binomial distributions and see what happens. Welcome to... This is the Cold War era. There’s a very large industrial center, off in some faraway, frozen lands. Nothing grows there, so the workers are being sent food for sustenance. Once in a while, a train full of potatoes arrives at the station. Now, this is hard stuff — we’re talking blizzards and storms — so potatoes get damaged. It is a fact that, in every transport, 20% of potatoes arriving in the station are bad. Well, it’s your turn to make dinner, so grab a big, hefty bag and head off to the station. 20 potatoes will be enough for your team. But it’s lights out, pitch black, leadership has wisely allocated all energy to the factories in order to meet the quotas, so you pick potatoes at random, blindly. What are the odds that all potatoes you pick will be good? What are the odds that just 1 potato will be bad? Or 2 bad, or 3? Or all bad? (which would definitely ruin dinner) Or maybe the comrades said: “Look, we all know how it is, just try not to pick more than 4 bad potatoes this time around. Up to 4 bad out of 20 is fine. We’ll survive. Less is better. More is not good.” What are the odds that your team won’t have a sad dinner this time around? This is where you meet your arch-enemy: There’s a very large pile of objects that are either type A or type B. The fraction of type A objects in the pile is p, where 0 <= p <= 1; the rest are type B. Out of that pile, you pick n objects, with n much smaller than the size of the whole pile. What are the odds that, out of the n objects you’ve picked, exactly k will be type A? In other words, you pick n=20 potatoes, out of a train where p=0.2 of all potatoes (or 20%) are bad. What are the odds that k potatoes (k between 0 and 20) out of the ones you pick are bad? This is the formula for the odds: Many Stats 101 books will give you some sort of proof (see Credits at the end). I just cook potatoes, so let’s move on. But before we do, please notice the factorials in the formula. Factorials can grow very large very quickly. This will turn around and nicely bite us in the code later on. But not just yet. We’ll start slow, we’ll use small numbers at first. Trust me, I’m an engineer. Everything will be fine — for a while. Fire up your Jupyter notebook and tag along. Let’s import the good stuff: Implement the probability formula: And compute the probabilities for all k values: Let’s see the results: print(df) probability0 1.152922e-021 5.764608e-022 1.369094e-013 2.053641e-014 2.181994e-015 1.745595e-016 1.090997e-017 5.454985e-028 2.216088e-029 7.386959e-0310 2.031414e-0311 4.616849e-0412 8.656592e-0513 1.331783e-0514 1.664729e-0615 1.664729e-0716 1.300570e-0817 7.650410e-1018 3.187671e-1119 8.388608e-1320 1.048576e-14 The probability that all potatoes are good is about 1%. The probability that only 1 potato is bad is about 5%; that 2 potatoes are bad is 14%; for 3 bad potatoes it’s 21%, for 4 bad is 22%, and it’s downhill from there — 17%, 11%, etc. That all potatoes are bad is very unlikely — 1 case out of 100 billion billion. How about cumulative probabilities — that 4 or fewer potatoes are bad? It’s what the teammates asked. Let’s see: dfcs = df.cumsum()dfcs.rename(columns={'probability': 'cumulative probability'}, inplace=True)print(dfcs) cumulative probability0 0.0115291 0.0691752 0.2060853 0.4114494 0.6296485 0.8042086 0.9133077 0.9678578 0.9900189 0.99740510 0.99943711 0.99989812 0.99998513 0.99999814 1.00000015 1.00000016 1.00000017 1.00000018 1.00000019 1.00000020 1.000000 There’s a 63% chance that only 4 or fewer potatoes will be bad. That’s almost 2 out of 3 times that your teammates will find dinner at the very least acceptable. Hey, it could be worse. But seeing is believing, so let’s plot the probabilities for all k values. Code: df.plot(figsize=(16,9))dfcs.plot(figsize=(16,9)) And image results: But alas, that’s not where it ends. You cook so well, now they want you to make dinner for the whole Precision Tooling section of the factory. That’s a bunch of teams, and you figure you’ll need 200 potatoes for everyone. So seize the means of production, which in this case are a couple burlap sacks, find someone to help you, and head to the train station. That’s n=200, so probably about 40 bad potatoes or less would be acceptable to the comrades, assuming all teams are like yours. Let’s see what the odds are. Change the value for n in the code and re-run it. And this is where things, like so many potatoes in the train, go bad: ---------------------------------------------------------------------------OverflowError Traceback (most recent call last)<ipython-input-4-c84b1e23a65f> in <module> 7 # compute probabilities for all k 8 for k in tqdm(range(n + 1)):----> 9 df.loc[k] = bin_prob(n, p, k)<ipython-input-3-60f4e81371ca> in bin_prob(n, p, k) 1 def bin_prob(n, p, k):----> 2 arr = math.factorial(n) / math.factorial(k) / math.factorial(n - k) 3 bp = arr * (p ** k) * ((1 - p) ** (n - k)) 4 return bpOverflowError: integer division result too large for a float Ah, yes. We’re computing 200! in there, which has 375 digits (no joke). The / operator wants to handle things as float, and Python can’t do float in that range. But wait, the // operator also does division (floor division, close enough), and handles everything as the integer type. Python’s only limit for integers is the size of the RAM. Those two divisions always make integers anyway in that formula (think why), so it’s okay to use // instead. Let’s give it a try again at n=200: It works beautifully: The odds that 40 potatoes or less will be bad are about 54%. That’s pretty sketchy, but hey, you’re there to work, not to enjoy fancy food, so toughen up, comrade. Sometimes we fail. Sometimes we succeed. And sometimes, as they used to say in the Eastern Bloc, we succeed too well. Despite the rotten potatoes, your cooking is so excellent now you have to make dinner for the whole factory. That’s 2000 potatoes for a lot of hungry workers. Get your teammates, hop on the truck, drive to the train station. For the glory of the Motherland. What are the odds that 400 potatoes, or less, will be bad in the bounty you bring back from the train? Change the code so that n=2000 and run it again. The result is pretty sad: ---------------------------------------------------------------------------OverflowError Traceback (most recent call last)<ipython-input-5-d85e2d80093f> in <module> 7 # compute probabilities for all k 8 for k in tqdm(range(n + 1)):----> 9 df.loc[k] = bin_prob(n, p, k)<ipython-input-4-88c12493fe27> in bin_prob(n, p, k) 1 def bin_prob(n, p, k): 2 arr = math.factorial(n) // math.factorial(k) // math.factorial(n - k)----> 3 bp = arr * (p ** k) * ((1 - p) ** (n - k)) 4 return bpOverflowError: int too large to convert to float We’re trying to compute 2000! in there. That number has 5736 digits. There’s nothing you can do in plain Python to work around that. That integer is fine, but you have to make it play nice with float, and plain Python doesn’t do float in that range. Decimal to the rescue. It handles arbitrarily large numbers of any kind. By default, it works with a precision of 28 digits, but you can change it to whatever you want, and it does change dynamically in some cases. import decimalprint(decimal.getcontext())Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow]) It even has some math functions embedded, so int(decimal.Context().power(2, 3)) is 23 = 8. You may have to convert formats into Decimal while working with it, then back to regular float or int, but that’s a small price to pay for eliminating size limits. Just keep in mind it’s a little slower than regular math libraries, so break this glass only in case of emergency. Let’s fix our function: The reason why we wrap everything in Decimal() in there is that we’re dealing with float values; if those arguments were integer, ctx.power() would take them directly. At the end, before we return it we convert the Decimal format to float. And, wow, does it ever work: The probability that 400 potatoes, or less, will be bad is 51%. Maybe you won’t be cooking for the whole factory for too long. Decimal is awesome. I’ve cranked it up to n=20000. It took 10 minutes to complete, single-threaded, but it did the job. You may want to switch to multiprocessing at that point. If you want to see the Jupyter notebook with the whole code for this tutorial, here it is. Of course, you can always import scipy and do the same calculation using library functions... import scipy.stats as ssn, p, k = 2000, 0.2, 40ss.binom.cdf(k, n, p) ...and that will give you the same cumulative probability calculated the hard way above (use pmf() instead of cdf() if you want the plain probability, instead of cumulative). But that was not the point — the point was to show how Python can handle very large numbers outside of specialized libraries, and to explore a bit of statistics while we’re at it. The Basic Practice of Statistics, 8th edition, by Moore, Notz, and Fligner. Sources for images not made by me:
[ { "code": null, "e": 420, "s": 171, "text": "Math is hard, let’s go shopping — for tutorials, that is. I definitely wish I had read this tutorial before trying some things in Python that involve extremely large numbers (binomial probability for large values of n) and my code started to crash." }, { "code": null, "e": 747, "s": 420, "text": "But wait, I hear you saying, Python can handle arbitrarily large numbers, limited only by the amount of RAM. Sure, as long as those are all integers. Now try to mix some float values in, for good measure, and things start crashing. Arbitrarily large numbers mixed with arbitrary precision floats are not fun in vanilla Python." }, { "code": null, "e": 886, "s": 747, "text": "Let’s try to gradually increase the demands on integer arithmetic in Python while calculating binomial distributions and see what happens." }, { "code": null, "e": 900, "s": 886, "text": "Welcome to..." }, { "code": null, "e": 1139, "s": 900, "text": "This is the Cold War era. There’s a very large industrial center, off in some faraway, frozen lands. Nothing grows there, so the workers are being sent food for sustenance. Once in a while, a train full of potatoes arrives at the station." }, { "code": null, "e": 1315, "s": 1139, "text": "Now, this is hard stuff — we’re talking blizzards and storms — so potatoes get damaged. It is a fact that, in every transport, 20% of potatoes arriving in the station are bad." }, { "code": null, "e": 1612, "s": 1315, "text": "Well, it’s your turn to make dinner, so grab a big, hefty bag and head off to the station. 20 potatoes will be enough for your team. But it’s lights out, pitch black, leadership has wisely allocated all energy to the factories in order to meet the quotas, so you pick potatoes at random, blindly." }, { "code": null, "e": 1786, "s": 1612, "text": "What are the odds that all potatoes you pick will be good? What are the odds that just 1 potato will be bad? Or 2 bad, or 3? Or all bad? (which would definitely ruin dinner)" }, { "code": null, "e": 2064, "s": 1786, "text": "Or maybe the comrades said: “Look, we all know how it is, just try not to pick more than 4 bad potatoes this time around. Up to 4 bad out of 20 is fine. We’ll survive. Less is better. More is not good.” What are the odds that your team won’t have a sad dinner this time around?" }, { "code": null, "e": 2104, "s": 2064, "text": "This is where you meet your arch-enemy:" }, { "code": null, "e": 2441, "s": 2104, "text": "There’s a very large pile of objects that are either type A or type B. The fraction of type A objects in the pile is p, where 0 <= p <= 1; the rest are type B. Out of that pile, you pick n objects, with n much smaller than the size of the whole pile. What are the odds that, out of the n objects you’ve picked, exactly k will be type A?" }, { "code": null, "e": 2631, "s": 2441, "text": "In other words, you pick n=20 potatoes, out of a train where p=0.2 of all potatoes (or 20%) are bad. What are the odds that k potatoes (k between 0 and 20) out of the ones you pick are bad?" }, { "code": null, "e": 2665, "s": 2631, "text": "This is the formula for the odds:" }, { "code": null, "e": 2785, "s": 2665, "text": "Many Stats 101 books will give you some sort of proof (see Credits at the end). I just cook potatoes, so let’s move on." }, { "code": null, "e": 2956, "s": 2785, "text": "But before we do, please notice the factorials in the formula. Factorials can grow very large very quickly. This will turn around and nicely bite us in the code later on." }, { "code": null, "e": 3092, "s": 2956, "text": "But not just yet. We’ll start slow, we’ll use small numbers at first. Trust me, I’m an engineer. Everything will be fine — for a while." }, { "code": null, "e": 3166, "s": 3092, "text": "Fire up your Jupyter notebook and tag along. Let’s import the good stuff:" }, { "code": null, "e": 3201, "s": 3166, "text": "Implement the probability formula:" }, { "code": null, "e": 3249, "s": 3201, "text": "And compute the probabilities for all k values:" }, { "code": null, "e": 3272, "s": 3249, "text": "Let’s see the results:" }, { "code": null, "e": 3634, "s": 3272, "text": "print(df) probability0 1.152922e-021 5.764608e-022 1.369094e-013 2.053641e-014 2.181994e-015 1.745595e-016 1.090997e-017 5.454985e-028 2.216088e-029 7.386959e-0310 2.031414e-0311 4.616849e-0412 8.656592e-0513 1.331783e-0514 1.664729e-0615 1.664729e-0716 1.300570e-0817 7.650410e-1018 3.187671e-1119 8.388608e-1320 1.048576e-14" }, { "code": null, "e": 3950, "s": 3634, "text": "The probability that all potatoes are good is about 1%. The probability that only 1 potato is bad is about 5%; that 2 potatoes are bad is 14%; for 3 bad potatoes it’s 21%, for 4 bad is 22%, and it’s downhill from there — 17%, 11%, etc. That all potatoes are bad is very unlikely — 1 case out of 100 billion billion." }, { "code": null, "e": 4063, "s": 3950, "text": "How about cumulative probabilities — that 4 or fewer potatoes are bad? It’s what the teammates asked. Let’s see:" }, { "code": null, "e": 4741, "s": 4063, "text": "dfcs = df.cumsum()dfcs.rename(columns={'probability': 'cumulative probability'}, inplace=True)print(dfcs) cumulative probability0 0.0115291 0.0691752 0.2060853 0.4114494 0.6296485 0.8042086 0.9133077 0.9678578 0.9900189 0.99740510 0.99943711 0.99989812 0.99998513 0.99999814 1.00000015 1.00000016 1.00000017 1.00000018 1.00000019 1.00000020 1.000000" }, { "code": null, "e": 4927, "s": 4741, "text": "There’s a 63% chance that only 4 or fewer potatoes will be bad. That’s almost 2 out of 3 times that your teammates will find dinner at the very least acceptable. Hey, it could be worse." }, { "code": null, "e": 5008, "s": 4927, "text": "But seeing is believing, so let’s plot the probabilities for all k values. Code:" }, { "code": null, "e": 5057, "s": 5008, "text": "df.plot(figsize=(16,9))dfcs.plot(figsize=(16,9))" }, { "code": null, "e": 5076, "s": 5057, "text": "And image results:" }, { "code": null, "e": 5435, "s": 5076, "text": "But alas, that’s not where it ends. You cook so well, now they want you to make dinner for the whole Precision Tooling section of the factory. That’s a bunch of teams, and you figure you’ll need 200 potatoes for everyone. So seize the means of production, which in this case are a couple burlap sacks, find someone to help you, and head to the train station." }, { "code": null, "e": 5592, "s": 5435, "text": "That’s n=200, so probably about 40 bad potatoes or less would be acceptable to the comrades, assuming all teams are like yours. Let’s see what the odds are." }, { "code": null, "e": 5712, "s": 5592, "text": "Change the value for n in the code and re-run it. And this is where things, like so many potatoes in the train, go bad:" }, { "code": null, "e": 6318, "s": 5712, "text": "---------------------------------------------------------------------------OverflowError Traceback (most recent call last)<ipython-input-4-c84b1e23a65f> in <module> 7 # compute probabilities for all k 8 for k in tqdm(range(n + 1)):----> 9 df.loc[k] = bin_prob(n, p, k)<ipython-input-3-60f4e81371ca> in bin_prob(n, p, k) 1 def bin_prob(n, p, k):----> 2 arr = math.factorial(n) / math.factorial(k) / math.factorial(n - k) 3 bp = arr * (p ** k) * ((1 - p) ** (n - k)) 4 return bpOverflowError: integer division result too large for a float" }, { "code": null, "e": 6479, "s": 6318, "text": "Ah, yes. We’re computing 200! in there, which has 375 digits (no joke). The / operator wants to handle things as float, and Python can’t do float in that range." }, { "code": null, "e": 6802, "s": 6479, "text": "But wait, the // operator also does division (floor division, close enough), and handles everything as the integer type. Python’s only limit for integers is the size of the RAM. Those two divisions always make integers anyway in that formula (think why), so it’s okay to use // instead. Let’s give it a try again at n=200:" }, { "code": null, "e": 6824, "s": 6802, "text": "It works beautifully:" }, { "code": null, "e": 6988, "s": 6824, "text": "The odds that 40 potatoes or less will be bad are about 54%. That’s pretty sketchy, but hey, you’re there to work, not to enjoy fancy food, so toughen up, comrade." }, { "code": null, "e": 7106, "s": 6988, "text": "Sometimes we fail. Sometimes we succeed. And sometimes, as they used to say in the Eastern Bloc, we succeed too well." }, { "code": null, "e": 7364, "s": 7106, "text": "Despite the rotten potatoes, your cooking is so excellent now you have to make dinner for the whole factory. That’s 2000 potatoes for a lot of hungry workers. Get your teammates, hop on the truck, drive to the train station. For the glory of the Motherland." }, { "code": null, "e": 7542, "s": 7364, "text": "What are the odds that 400 potatoes, or less, will be bad in the bounty you bring back from the train? Change the code so that n=2000 and run it again. The result is pretty sad:" }, { "code": null, "e": 8138, "s": 7542, "text": "---------------------------------------------------------------------------OverflowError Traceback (most recent call last)<ipython-input-5-d85e2d80093f> in <module> 7 # compute probabilities for all k 8 for k in tqdm(range(n + 1)):----> 9 df.loc[k] = bin_prob(n, p, k)<ipython-input-4-88c12493fe27> in bin_prob(n, p, k) 1 def bin_prob(n, p, k): 2 arr = math.factorial(n) // math.factorial(k) // math.factorial(n - k)----> 3 bp = arr * (p ** k) * ((1 - p) ** (n - k)) 4 return bpOverflowError: int too large to convert to float" }, { "code": null, "e": 8388, "s": 8138, "text": "We’re trying to compute 2000! in there. That number has 5736 digits. There’s nothing you can do in plain Python to work around that. That integer is fine, but you have to make it play nice with float, and plain Python doesn’t do float in that range." }, { "code": null, "e": 8603, "s": 8388, "text": "Decimal to the rescue. It handles arbitrarily large numbers of any kind. By default, it works with a precision of 28 digits, but you can change it to whatever you want, and it does change dynamically in some cases." }, { "code": null, "e": 8846, "s": 8603, "text": "import decimalprint(decimal.getcontext())Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])" }, { "code": null, "e": 9216, "s": 8846, "text": "It even has some math functions embedded, so int(decimal.Context().power(2, 3)) is 23 = 8. You may have to convert formats into Decimal while working with it, then back to regular float or int, but that’s a small price to pay for eliminating size limits. Just keep in mind it’s a little slower than regular math libraries, so break this glass only in case of emergency." }, { "code": null, "e": 9240, "s": 9216, "text": "Let’s fix our function:" }, { "code": null, "e": 9480, "s": 9240, "text": "The reason why we wrap everything in Decimal() in there is that we’re dealing with float values; if those arguments were integer, ctx.power() would take them directly. At the end, before we return it we convert the Decimal format to float." }, { "code": null, "e": 9509, "s": 9480, "text": "And, wow, does it ever work:" }, { "code": null, "e": 9636, "s": 9509, "text": "The probability that 400 potatoes, or less, will be bad is 51%. Maybe you won’t be cooking for the whole factory for too long." }, { "code": null, "e": 9813, "s": 9636, "text": "Decimal is awesome. I’ve cranked it up to n=20000. It took 10 minutes to complete, single-threaded, but it did the job. You may want to switch to multiprocessing at that point." }, { "code": null, "e": 9904, "s": 9813, "text": "If you want to see the Jupyter notebook with the whole code for this tutorial, here it is." }, { "code": null, "e": 9998, "s": 9904, "text": "Of course, you can always import scipy and do the same calculation using library functions..." }, { "code": null, "e": 10067, "s": 9998, "text": "import scipy.stats as ssn, p, k = 2000, 0.2, 40ss.binom.cdf(k, n, p)" }, { "code": null, "e": 10242, "s": 10067, "text": "...and that will give you the same cumulative probability calculated the hard way above (use pmf() instead of cdf() if you want the plain probability, instead of cumulative)." }, { "code": null, "e": 10422, "s": 10242, "text": "But that was not the point — the point was to show how Python can handle very large numbers outside of specialized libraries, and to explore a bit of statistics while we’re at it." }, { "code": null, "e": 10498, "s": 10422, "text": "The Basic Practice of Statistics, 8th edition, by Moore, Notz, and Fligner." } ]
Find repeated character present first in a string - GeeksforGeeks
14 Feb, 2022 Given a string, find the repeated character present first in the string.(Not the first repeated character, found here.) Examples: Input : geeksforgeeks Output : g (mind that it will be g, not e.) Asked in: Goldman Sachs internship Simple Solution using O(N^2) complexity The solution is to loop through the string for each character and search for the same in the rest of the string. This would need two loops and thus not optimal. C++ C Java Python3 C# PHP Javascript // C++ program to find the first// character that is repeated#include <bits/stdc++.h>#include <string.h> using namespace std;int findRepeatFirstN2(char* s){ // this is O(N^2) method int p = -1, i, j; for (i = 0; i < strlen(s); i++) { for (j = i + 1; j < strlen(s); j++) { if (s[i] == s[j]) { p = i; break; } } if (p != -1) break; } return p;} // Driver codeint main(){ char str[] = "geeksforgeeks"; int pos = findRepeatFirstN2(str); if (pos == -1) cout << "Not found"; else cout << str[pos]; return 0;} // This code is contributed// by Akanksha Rai // C program to find the first character that// is repeated#include <stdio.h>#include <string.h> int findRepeatFirstN2(char* s){ // this is O(N^2) method int p = -1, i, j; for (i = 0; i < strlen(s); i++) { for (j = i + 1; j < strlen(s); j++) { if (s[i] == s[j]) { p = i; break; } } if (p != -1) break; } return p;} // Driver codeint main(){ char str[] = "geeksforgeeks"; int pos = findRepeatFirstN2(str); if (pos == -1) printf("Not found"); else printf("%c", str[pos]); return 0;} // Java program to find the first character// that is repeatedimport java.io.*;import java.util.*; class GFG { static int findRepeatFirstN2(String s) { // this is O(N^2) method int p = -1, i, j; for (i = 0; i < s.length(); i++) { for (j = i + 1; j < s.length(); j++) { if (s.charAt(i) == s.charAt(j)) { p = i; break; } } if (p != -1) break; } return p; } // Driver code static public void main (String[] args) { String str = "geeksforgeeks"; int pos = findRepeatFirstN2(str); if (pos == -1) System.out.println("Not found"); else System.out.println( str.charAt(pos)); }} // This code is contributed by anuj_67. # Python3 program to find the first# character that is repeated def findRepeatFirstN2(s): # this is O(N^2) method p = -1 for i in range(len(s)): for j in range (i + 1, len(s)): if (s[i] == s[j]): p = i break if (p != -1): break return p # Driver codeif __name__ == "__main__": str = "geeksforgeeks" pos = findRepeatFirstN2(str) if (pos == -1): print ("Not found") else: print (str[pos]) # This code is contributed# by ChitraNayal // C# program to find the first character// that is repeatedusing System; class GFG { static int findRepeatFirstN2(string s) { // this is O(N^2) method int p = -1, i, j; for (i = 0; i < s.Length; i++) { for (j = i + 1; j < s.Length; j++) { if (s[i] == s[j]) { p = i; break; } } if (p != -1) break; } return p; } // Driver code static public void Main () { string str = "geeksforgeeks"; int pos = findRepeatFirstN2(str); if (pos == -1) Console.WriteLine("Not found"); else Console.WriteLine( str[pos]); }} // This code is contributed by anuj_67. <?php// PHP program to find the first// character that is repeated function findRepeatFirstN2($s){ // this is O(N^2) method $p = -1; for ($i = 0; $i < strlen($s); $i++) { for ($j = ($i + 1); $j < strlen($s); $j++) { if ($s[$i] == $s[$j]) { $p = $i; break; } } if ($p != -1) break; } return $p;} // Driver code$str = "geeksforgeeks";$pos = findRepeatFirstN2($str); if ($pos == -1) echo ("Not found");else echo ($str[$pos]); // This code is contributed by jit_t?> <script> // Javascript program to find the first// character that is repeatedfunction findRepeatFirstN2(s){ // This is O(N^2) method let p = -1, i, j; for(i = 0; i < s.length; i++) { for(j = i + 1; j < s.length; j++) { if (s[i] == s[j]) { p = i; break; } } if (p != -1) break; } return p;} // Driver codelet str = "geeksforgeeks";let pos = findRepeatFirstN2(str); if (pos == -1) document.write("Not found");else document.write(str[pos]); // This code is contributed by suresh07 </script> g Optimization by counting occurrencesThis solution is optimized by using the following techniques: 1. We loop through the string and hash the characters using ASCII codes. Store 1 if found and store 2 if found again. Also, store the position of the letter first found in.2. We run a loop on the hash array and now we find the minimum position of any character repeated. This will have a runtime of O(N). C++ C Java Python3 C# Javascript // C++ program to find the first character that// is repeated#include<bits/stdc++.h> using namespace std;// 256 is taken just to ensure nothing is left,// actual max ASCII limit is 128#define MAX_CHAR 256 int findRepeatFirst(char* s){ // this is optimized method int p = -1, i, k; // initialized counts of occurrences of // elements as zero int hash[MAX_CHAR] = { 0 }; // initialized positions int pos[MAX_CHAR]; for (i = 0; i < strlen(s); i++) { k = (int)s[i]; if (hash[k] == 0) { hash[k]++; pos[k] = i; } else if (hash[k] == 1) hash[k]++; } for (i = 0; i < MAX_CHAR; i++) { if (hash[i] == 2) { if (p == -1) // base case p = pos[i]; else if (p > pos[i]) p = pos[i]; } } return p;} // Driver codeint main(){ char str[] = "geeksforgeeks"; int pos = findRepeatFirst(str); if (pos == -1) cout << "Not found"; else cout << str[pos]; return 0;} // This code is contributed// by Akanksha Rai // C program to find the first character that// is repeated#include <stdio.h>#include <string.h> // 256 is taken just to ensure nothing is left,// actual max ASCII limit is 128#define MAX_CHAR 256 int findRepeatFirst(char* s){ // this is optimized method int p = -1, i, k; // initialized counts of occurrences of // elements as zero int hash[MAX_CHAR] = { 0 }; // initialized positions int pos[MAX_CHAR]; for (i = 0; i < strlen(s); i++) { k = (int)s[i]; if (hash[k] == 0) { hash[k]++; pos[k] = i; } else if (hash[k] == 1) hash[k]++; } for (i = 0; i < MAX_CHAR; i++) { if (hash[i] == 2) { if (p == -1) // base case p = pos[i]; else if (p > pos[i]) p = pos[i]; } } return p;} // Driver codeint main(){ char str[] = "geeksforgeeks"; int pos = findRepeatFirst(str); if (pos == -1) printf("Not found"); else printf("%c", str[pos]); return 0;} // Java Program to find the first character // that is repeated import java.util.*;import java.lang.*; public class GFG{ public static int findRepeatFirst(String s) { // this is optimized method int p = -1, i, k; // initialized counts of occurrences of // elements as zero int MAX_CHAR = 256; int hash[] = new int[MAX_CHAR]; // initialized positions int pos[] = new int[MAX_CHAR]; for (i = 0; i < s.length(); i++) { k = (int)s.charAt(i); if (hash[k] == 0) { hash[k]++; pos[k] = i; } else if (hash[k] == 1) hash[k]++; } for (i = 0; i < MAX_CHAR; i++) { if (hash[i] == 2) { if (p == -1) // base case p = pos[i]; else if (p > pos[i]) p = pos[i]; } } return p; } // Driver code public static void main(String[] args) { String str = "geeksforgeeks"; int pos = findRepeatFirst(str); if (pos == -1) System.out.println("Not found"); else System.out.println(str.charAt(pos)); }} // Code Contributed by Mohit Gupta_OMG # Python 3 program to find the first# character that is repeated # 256 is taken just to ensure nothing# is left, actual max ASCII limit is 128 MAX_CHAR = 256 def findRepeatFirst(s): # this is optimized method p = -1 # initialized counts of occurrences # of elements as zero hash = [0 for i in range(MAX_CHAR)] # initialized positions pos = [0 for i in range(MAX_CHAR)] for i in range(len(s)): k = ord(s[i]) if (hash[k] == 0): hash[k] += 1 pos[k] = i elif(hash[k] == 1): hash[k] += 1 for i in range(MAX_CHAR): if (hash[i] == 2): if (p == -1): # base case p = pos[i] elif(p > pos[i]): p = pos[i] return p # Driver codeif __name__ == '__main__': str = "geeksforgeeks" pos = findRepeatFirst(str); if (pos == -1): print("Not found") else: print(str[pos]) # This code is contributed by# Shashank_Sharma // C# Program to find the first character // that is repeatedusing System;public class GFG{ public static int findRepeatFirst(string s) { // this is optimized method int p = -1, i, k; // initialized counts of occurrences of // elements as zero int MAX_CHAR = 256; int []hash = new int[MAX_CHAR]; // initialized positions int []pos = new int[MAX_CHAR]; for (i = 0; i < s.Length; i++) { k = (int)s[i]; if (hash[k] == 0) { hash[k]++; pos[k] = i; } else if (hash[k] == 1) hash[k]++; } for (i = 0; i < MAX_CHAR; i++) { if (hash[i] == 2) { if (p == -1) // base case p = pos[i]; else if (p > pos[i]) p = pos[i]; } } return p; } // Driver code public static void Main() { string str = "geeksforgeeks"; int pos = findRepeatFirst(str); if (pos == -1) Console.Write("Not found"); else Console.Write(str[pos]); }} // This code is contributed by nitin mittal. <script> // Javascript Program to find the first character that is repeated function findRepeatFirst(s) { // this is optimized method let p = -1, i, k; // initialized counts of occurrences of // elements as zero let MAX_CHAR = 256; let hash = new Array(MAX_CHAR); hash.fill(0); // initialized positions let pos = new Array(MAX_CHAR); pos.fill(0); for (i = 0; i < s.length; i++) { k = s[i].charCodeAt(); if (hash[k] == 0) { hash[k]++; pos[k] = i; } else if (hash[k] == 1) hash[k]++; } for (i = 0; i < MAX_CHAR; i++) { if (hash[i] == 2) { if (p == -1) // base case p = pos[i]; else if (p > pos[i]) p = pos[i]; } } return p; } let str = "geeksforgeeks"; let pos = findRepeatFirst(str); if (pos == -1) document.write("Not found"); else document.write(str[pos]); // This code is contributed by rameshtravel07.</script> g Calculate all frequencies of all characters using Counter() function. Traverse the string and check if any element has frequency greater than 1. Print the character and break the loop Below is the implementation: Python3 # Python implementationfrom collections import Counter # Function which repeats# first repeating characterdef printrepeated(string): # Calculating frequencies # using Counter function freq = Counter(string) # Traverse the string for i in string: if(freq[i] > 1): print(i) break # Driver codestring = "geeksforgeeks" # passing string to printrepeated functionprintrepeated(string) # this code is contributed by vikkycirus g Time Complexity:O(n) Space Complexity:O(n) Method #4: Solving just by single traversal of the given string. Algorithm : 1. Traverse the string from left to right. 2. If current character is not present in hash map, Then push this character along with its Index. 3. If the current character is already present in hash map, Then get the index of current character ( from hash map ) and compare it with the index of the previously found repeating character. 4. If the current index is smaller, then update the index. C++ Javascript #include <iostream>#include<unordered_map>#define INT_MAX 2147483647using namespace std; // Function to find left most repeating character.char firstRep (string s) { unordered_map<char,int> map; char c='#'; int index=INT_MAX; // single traversal of string. for(int i=0;i<s.size();i++) { char p=s[i]; if(map.find(p)==map.end())map.insert({p,i}); else { if(map[p]<index) { index=map[p]; c=p; } } } return c; } // Main function.int main() { // Input string. string s="abccdbd"; cout<<firstRep(s)<<endl; return 0;} // This code is contributed// by rohan007 <script>// JavaScript code to find the first repeating character in a stringconst INT_MAX = 2147483647 // Function to find left most repeating character.function firstRep(s){ map = new Map(); let c = '#'; let index=INT_MAX; // single traversal of string. for(let i = 0; i < s.length; i++) { let p = s[i]; if(!map.has(p))map.set(p,i); else { if(map.get(p) < index) { index = map.get(p); c = p; } } } return c;} // Driver code // Input string.const s="abccdbd";document.write(firstRep(s)); // This code is contributed by shinjanpatra</script> b Time complexity: O(N) Space complexity: O(N) More optimized Solution Repeated Character Whose First Appearance is LeftmostThis article is contributed by Suprotik Dey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal vt_m jit_t Akanksha_Rai ukasp Shashank_Sharma vikkycirus suresh07 rameshtravel07 rohan007 arorakashish0911 shinjanpatra Goldman Sachs Strings Goldman Sachs Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python program to check if a string is palindrome or not Different methods to reverse a string in C/C++ Check for Balanced Brackets in an expression (well-formedness) using Stack Convert string to char array in C++ KMP Algorithm for Pattern Searching Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Reverse words in a given string Check whether two strings are anagram of each other Length of the longest substring without repeating characters
[ { "code": null, "e": 24874, "s": 24846, "text": "\n14 Feb, 2022" }, { "code": null, "e": 24995, "s": 24874, "text": "Given a string, find the repeated character present first in the string.(Not the first repeated character, found here.) " }, { "code": null, "e": 25006, "s": 24995, "text": "Examples: " }, { "code": null, "e": 25073, "s": 25006, "text": "Input : geeksforgeeks\nOutput : g\n(mind that it will be g, not e.)" }, { "code": null, "e": 25109, "s": 25073, "text": "Asked in: Goldman Sachs internship " }, { "code": null, "e": 25312, "s": 25109, "text": "Simple Solution using O(N^2) complexity The solution is to loop through the string for each character and search for the same in the rest of the string. This would need two loops and thus not optimal. " }, { "code": null, "e": 25316, "s": 25312, "text": "C++" }, { "code": null, "e": 25318, "s": 25316, "text": "C" }, { "code": null, "e": 25323, "s": 25318, "text": "Java" }, { "code": null, "e": 25331, "s": 25323, "text": "Python3" }, { "code": null, "e": 25334, "s": 25331, "text": "C#" }, { "code": null, "e": 25338, "s": 25334, "text": "PHP" }, { "code": null, "e": 25349, "s": 25338, "text": "Javascript" }, { "code": "// C++ program to find the first// character that is repeated#include <bits/stdc++.h>#include <string.h> using namespace std;int findRepeatFirstN2(char* s){ // this is O(N^2) method int p = -1, i, j; for (i = 0; i < strlen(s); i++) { for (j = i + 1; j < strlen(s); j++) { if (s[i] == s[j]) { p = i; break; } } if (p != -1) break; } return p;} // Driver codeint main(){ char str[] = \"geeksforgeeks\"; int pos = findRepeatFirstN2(str); if (pos == -1) cout << \"Not found\"; else cout << str[pos]; return 0;} // This code is contributed// by Akanksha Rai", "e": 26048, "s": 25349, "text": null }, { "code": "// C program to find the first character that// is repeated#include <stdio.h>#include <string.h> int findRepeatFirstN2(char* s){ // this is O(N^2) method int p = -1, i, j; for (i = 0; i < strlen(s); i++) { for (j = i + 1; j < strlen(s); j++) { if (s[i] == s[j]) { p = i; break; } } if (p != -1) break; } return p;} // Driver codeint main(){ char str[] = \"geeksforgeeks\"; int pos = findRepeatFirstN2(str); if (pos == -1) printf(\"Not found\"); else printf(\"%c\", str[pos]); return 0;}", "e": 26658, "s": 26048, "text": null }, { "code": "// Java program to find the first character// that is repeatedimport java.io.*;import java.util.*; class GFG { static int findRepeatFirstN2(String s) { // this is O(N^2) method int p = -1, i, j; for (i = 0; i < s.length(); i++) { for (j = i + 1; j < s.length(); j++) { if (s.charAt(i) == s.charAt(j)) { p = i; break; } } if (p != -1) break; } return p; } // Driver code static public void main (String[] args) { String str = \"geeksforgeeks\"; int pos = findRepeatFirstN2(str); if (pos == -1) System.out.println(\"Not found\"); else System.out.println( str.charAt(pos)); }} // This code is contributed by anuj_67.", "e": 27548, "s": 26658, "text": null }, { "code": "# Python3 program to find the first# character that is repeated def findRepeatFirstN2(s): # this is O(N^2) method p = -1 for i in range(len(s)): for j in range (i + 1, len(s)): if (s[i] == s[j]): p = i break if (p != -1): break return p # Driver codeif __name__ == \"__main__\": str = \"geeksforgeeks\" pos = findRepeatFirstN2(str) if (pos == -1): print (\"Not found\") else: print (str[pos]) # This code is contributed# by ChitraNayal", "e": 28116, "s": 27548, "text": null }, { "code": "// C# program to find the first character// that is repeatedusing System; class GFG { static int findRepeatFirstN2(string s) { // this is O(N^2) method int p = -1, i, j; for (i = 0; i < s.Length; i++) { for (j = i + 1; j < s.Length; j++) { if (s[i] == s[j]) { p = i; break; } } if (p != -1) break; } return p; } // Driver code static public void Main () { string str = \"geeksforgeeks\"; int pos = findRepeatFirstN2(str); if (pos == -1) Console.WriteLine(\"Not found\"); else Console.WriteLine( str[pos]); }} // This code is contributed by anuj_67.", "e": 28941, "s": 28116, "text": null }, { "code": "<?php// PHP program to find the first// character that is repeated function findRepeatFirstN2($s){ // this is O(N^2) method $p = -1; for ($i = 0; $i < strlen($s); $i++) { for ($j = ($i + 1); $j < strlen($s); $j++) { if ($s[$i] == $s[$j]) { $p = $i; break; } } if ($p != -1) break; } return $p;} // Driver code$str = \"geeksforgeeks\";$pos = findRepeatFirstN2($str); if ($pos == -1) echo (\"Not found\");else echo ($str[$pos]); // This code is contributed by jit_t?>", "e": 29542, "s": 28941, "text": null }, { "code": "<script> // Javascript program to find the first// character that is repeatedfunction findRepeatFirstN2(s){ // This is O(N^2) method let p = -1, i, j; for(i = 0; i < s.length; i++) { for(j = i + 1; j < s.length; j++) { if (s[i] == s[j]) { p = i; break; } } if (p != -1) break; } return p;} // Driver codelet str = \"geeksforgeeks\";let pos = findRepeatFirstN2(str); if (pos == -1) document.write(\"Not found\");else document.write(str[pos]); // This code is contributed by suresh07 </script>", "e": 30167, "s": 29542, "text": null }, { "code": null, "e": 30169, "s": 30167, "text": "g" }, { "code": null, "e": 30538, "s": 30169, "text": "Optimization by counting occurrencesThis solution is optimized by using the following techniques: 1. We loop through the string and hash the characters using ASCII codes. Store 1 if found and store 2 if found again. Also, store the position of the letter first found in.2. We run a loop on the hash array and now we find the minimum position of any character repeated." }, { "code": null, "e": 30572, "s": 30538, "text": "This will have a runtime of O(N)." }, { "code": null, "e": 30576, "s": 30572, "text": "C++" }, { "code": null, "e": 30578, "s": 30576, "text": "C" }, { "code": null, "e": 30583, "s": 30578, "text": "Java" }, { "code": null, "e": 30591, "s": 30583, "text": "Python3" }, { "code": null, "e": 30594, "s": 30591, "text": "C#" }, { "code": null, "e": 30605, "s": 30594, "text": "Javascript" }, { "code": "// C++ program to find the first character that// is repeated#include<bits/stdc++.h> using namespace std;// 256 is taken just to ensure nothing is left,// actual max ASCII limit is 128#define MAX_CHAR 256 int findRepeatFirst(char* s){ // this is optimized method int p = -1, i, k; // initialized counts of occurrences of // elements as zero int hash[MAX_CHAR] = { 0 }; // initialized positions int pos[MAX_CHAR]; for (i = 0; i < strlen(s); i++) { k = (int)s[i]; if (hash[k] == 0) { hash[k]++; pos[k] = i; } else if (hash[k] == 1) hash[k]++; } for (i = 0; i < MAX_CHAR; i++) { if (hash[i] == 2) { if (p == -1) // base case p = pos[i]; else if (p > pos[i]) p = pos[i]; } } return p;} // Driver codeint main(){ char str[] = \"geeksforgeeks\"; int pos = findRepeatFirst(str); if (pos == -1) cout << \"Not found\"; else cout << str[pos]; return 0;} // This code is contributed// by Akanksha Rai", "e": 31681, "s": 30605, "text": null }, { "code": "// C program to find the first character that// is repeated#include <stdio.h>#include <string.h> // 256 is taken just to ensure nothing is left,// actual max ASCII limit is 128#define MAX_CHAR 256 int findRepeatFirst(char* s){ // this is optimized method int p = -1, i, k; // initialized counts of occurrences of // elements as zero int hash[MAX_CHAR] = { 0 }; // initialized positions int pos[MAX_CHAR]; for (i = 0; i < strlen(s); i++) { k = (int)s[i]; if (hash[k] == 0) { hash[k]++; pos[k] = i; } else if (hash[k] == 1) hash[k]++; } for (i = 0; i < MAX_CHAR; i++) { if (hash[i] == 2) { if (p == -1) // base case p = pos[i]; else if (p > pos[i]) p = pos[i]; } } return p;} // Driver codeint main(){ char str[] = \"geeksforgeeks\"; int pos = findRepeatFirst(str); if (pos == -1) printf(\"Not found\"); else printf(\"%c\", str[pos]); return 0;}", "e": 32709, "s": 31681, "text": null }, { "code": "// Java Program to find the first character // that is repeated import java.util.*;import java.lang.*; public class GFG{ public static int findRepeatFirst(String s) { // this is optimized method int p = -1, i, k; // initialized counts of occurrences of // elements as zero int MAX_CHAR = 256; int hash[] = new int[MAX_CHAR]; // initialized positions int pos[] = new int[MAX_CHAR]; for (i = 0; i < s.length(); i++) { k = (int)s.charAt(i); if (hash[k] == 0) { hash[k]++; pos[k] = i; } else if (hash[k] == 1) hash[k]++; } for (i = 0; i < MAX_CHAR; i++) { if (hash[i] == 2) { if (p == -1) // base case p = pos[i]; else if (p > pos[i]) p = pos[i]; } } return p; } // Driver code public static void main(String[] args) { String str = \"geeksforgeeks\"; int pos = findRepeatFirst(str); if (pos == -1) System.out.println(\"Not found\"); else System.out.println(str.charAt(pos)); }} // Code Contributed by Mohit Gupta_OMG", "e": 33997, "s": 32709, "text": null }, { "code": "# Python 3 program to find the first# character that is repeated # 256 is taken just to ensure nothing# is left, actual max ASCII limit is 128 MAX_CHAR = 256 def findRepeatFirst(s): # this is optimized method p = -1 # initialized counts of occurrences # of elements as zero hash = [0 for i in range(MAX_CHAR)] # initialized positions pos = [0 for i in range(MAX_CHAR)] for i in range(len(s)): k = ord(s[i]) if (hash[k] == 0): hash[k] += 1 pos[k] = i elif(hash[k] == 1): hash[k] += 1 for i in range(MAX_CHAR): if (hash[i] == 2): if (p == -1): # base case p = pos[i] elif(p > pos[i]): p = pos[i] return p # Driver codeif __name__ == '__main__': str = \"geeksforgeeks\" pos = findRepeatFirst(str); if (pos == -1): print(\"Not found\") else: print(str[pos]) # This code is contributed by# Shashank_Sharma", "e": 34980, "s": 33997, "text": null }, { "code": "// C# Program to find the first character // that is repeatedusing System;public class GFG{ public static int findRepeatFirst(string s) { // this is optimized method int p = -1, i, k; // initialized counts of occurrences of // elements as zero int MAX_CHAR = 256; int []hash = new int[MAX_CHAR]; // initialized positions int []pos = new int[MAX_CHAR]; for (i = 0; i < s.Length; i++) { k = (int)s[i]; if (hash[k] == 0) { hash[k]++; pos[k] = i; } else if (hash[k] == 1) hash[k]++; } for (i = 0; i < MAX_CHAR; i++) { if (hash[i] == 2) { if (p == -1) // base case p = pos[i]; else if (p > pos[i]) p = pos[i]; } } return p; } // Driver code public static void Main() { string str = \"geeksforgeeks\"; int pos = findRepeatFirst(str); if (pos == -1) Console.Write(\"Not found\"); else Console.Write(str[pos]); }} // This code is contributed by nitin mittal.", "e": 36217, "s": 34980, "text": null }, { "code": "<script> // Javascript Program to find the first character that is repeated function findRepeatFirst(s) { // this is optimized method let p = -1, i, k; // initialized counts of occurrences of // elements as zero let MAX_CHAR = 256; let hash = new Array(MAX_CHAR); hash.fill(0); // initialized positions let pos = new Array(MAX_CHAR); pos.fill(0); for (i = 0; i < s.length; i++) { k = s[i].charCodeAt(); if (hash[k] == 0) { hash[k]++; pos[k] = i; } else if (hash[k] == 1) hash[k]++; } for (i = 0; i < MAX_CHAR; i++) { if (hash[i] == 2) { if (p == -1) // base case p = pos[i]; else if (p > pos[i]) p = pos[i]; } } return p; } let str = \"geeksforgeeks\"; let pos = findRepeatFirst(str); if (pos == -1) document.write(\"Not found\"); else document.write(str[pos]); // This code is contributed by rameshtravel07.</script>", "e": 37410, "s": 36217, "text": null }, { "code": null, "e": 37412, "s": 37410, "text": "g" }, { "code": null, "e": 37482, "s": 37412, "text": "Calculate all frequencies of all characters using Counter() function." }, { "code": null, "e": 37557, "s": 37482, "text": "Traverse the string and check if any element has frequency greater than 1." }, { "code": null, "e": 37597, "s": 37557, "text": "Print the character and break the loop" }, { "code": null, "e": 37626, "s": 37597, "text": "Below is the implementation:" }, { "code": null, "e": 37634, "s": 37626, "text": "Python3" }, { "code": "# Python implementationfrom collections import Counter # Function which repeats# first repeating characterdef printrepeated(string): # Calculating frequencies # using Counter function freq = Counter(string) # Traverse the string for i in string: if(freq[i] > 1): print(i) break # Driver codestring = \"geeksforgeeks\" # passing string to printrepeated functionprintrepeated(string) # this code is contributed by vikkycirus", "e": 38108, "s": 37634, "text": null }, { "code": null, "e": 38110, "s": 38108, "text": "g" }, { "code": null, "e": 38131, "s": 38110, "text": "Time Complexity:O(n)" }, { "code": null, "e": 38153, "s": 38131, "text": "Space Complexity:O(n)" }, { "code": null, "e": 38218, "s": 38153, "text": "Method #4: Solving just by single traversal of the given string." }, { "code": null, "e": 38230, "s": 38218, "text": "Algorithm :" }, { "code": null, "e": 38273, "s": 38230, "text": "1. Traverse the string from left to right." }, { "code": null, "e": 38372, "s": 38273, "text": "2. If current character is not present in hash map, Then push this character along with its Index." }, { "code": null, "e": 38565, "s": 38372, "text": "3. If the current character is already present in hash map, Then get the index of current character ( from hash map ) and compare it with the index of the previously found repeating character." }, { "code": null, "e": 38624, "s": 38565, "text": "4. If the current index is smaller, then update the index." }, { "code": null, "e": 38628, "s": 38624, "text": "C++" }, { "code": null, "e": 38639, "s": 38628, "text": "Javascript" }, { "code": "#include <iostream>#include<unordered_map>#define INT_MAX 2147483647using namespace std; // Function to find left most repeating character.char firstRep (string s) { unordered_map<char,int> map; char c='#'; int index=INT_MAX; // single traversal of string. for(int i=0;i<s.size();i++) { char p=s[i]; if(map.find(p)==map.end())map.insert({p,i}); else { if(map[p]<index) { index=map[p]; c=p; } } } return c; } // Main function.int main() { // Input string. string s=\"abccdbd\"; cout<<firstRep(s)<<endl; return 0;} // This code is contributed// by rohan007", "e": 39464, "s": 38639, "text": null }, { "code": "<script>// JavaScript code to find the first repeating character in a stringconst INT_MAX = 2147483647 // Function to find left most repeating character.function firstRep(s){ map = new Map(); let c = '#'; let index=INT_MAX; // single traversal of string. for(let i = 0; i < s.length; i++) { let p = s[i]; if(!map.has(p))map.set(p,i); else { if(map.get(p) < index) { index = map.get(p); c = p; } } } return c;} // Driver code // Input string.const s=\"abccdbd\";document.write(firstRep(s)); // This code is contributed by shinjanpatra</script>", "e": 40161, "s": 39464, "text": null }, { "code": null, "e": 40163, "s": 40161, "text": "b" }, { "code": null, "e": 40188, "s": 40163, "text": "Time complexity: O(N)" }, { "code": null, "e": 40212, "s": 40188, "text": "Space complexity: O(N)" }, { "code": null, "e": 40710, "s": 40212, "text": "More optimized Solution Repeated Character Whose First Appearance is LeftmostThis article is contributed by Suprotik Dey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 40723, "s": 40710, "text": "nitin mittal" }, { "code": null, "e": 40728, "s": 40723, "text": "vt_m" }, { "code": null, "e": 40734, "s": 40728, "text": "jit_t" }, { "code": null, "e": 40747, "s": 40734, "text": "Akanksha_Rai" }, { "code": null, "e": 40753, "s": 40747, "text": "ukasp" }, { "code": null, "e": 40769, "s": 40753, "text": "Shashank_Sharma" }, { "code": null, "e": 40780, "s": 40769, "text": "vikkycirus" }, { "code": null, "e": 40789, "s": 40780, "text": "suresh07" }, { "code": null, "e": 40804, "s": 40789, "text": "rameshtravel07" }, { "code": null, "e": 40813, "s": 40804, "text": "rohan007" }, { "code": null, "e": 40830, "s": 40813, "text": "arorakashish0911" }, { "code": null, "e": 40843, "s": 40830, "text": "shinjanpatra" }, { "code": null, "e": 40857, "s": 40843, "text": "Goldman Sachs" }, { "code": null, "e": 40865, "s": 40857, "text": "Strings" }, { "code": null, "e": 40879, "s": 40865, "text": "Goldman Sachs" }, { "code": null, "e": 40887, "s": 40879, "text": "Strings" }, { "code": null, "e": 40985, "s": 40887, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40994, "s": 40985, "text": "Comments" }, { "code": null, "e": 41007, "s": 40994, "text": "Old Comments" }, { "code": null, "e": 41064, "s": 41007, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 41111, "s": 41064, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 41186, "s": 41111, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 41222, "s": 41186, "text": "Convert string to char array in C++" }, { "code": null, "e": 41258, "s": 41222, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 41296, "s": 41258, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 41326, "s": 41296, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 41358, "s": 41326, "text": "Reverse words in a given string" }, { "code": null, "e": 41410, "s": 41358, "text": "Check whether two strings are anagram of each other" } ]
JavaFX - 3D Shapes
In the earlier chapters, we have seen how to draw 2D shapes on an XY plane. In addition to these 2D shapes, we can draw several other 3D shapes as well using JavaFX. In general, a 3D shape is a geometrical figure that can be drawn on the XYZ plane. These include a Cylinder, Sphere and a Box. Each of the above mentioned 3D shape is represented by a class and all these classes belong to the package javafx.scene.shape. The class named Shape3D is the base class of all the 3-Dimensional shapes in JavaFX. To create a 3-Dimensional shape, you need to − Instantiate the respective class of the required 3D shape. Instantiate the respective class of the required 3D shape. Set the properties of the 3D shape. Set the properties of the 3D shape. Add the 3D shape object to the group. Add the 3D shape object to the group. To create a 3-Dimensional shape, first of all you need to instantiate its respective class. For example, if you want to create a 3D box, you need to instantiate the class named Box as follows − Box box = new Box(); After instantiating the class, you need to set the properties for the shape using the setter methods. For example, to draw a 3D box you need to pass its Width, Height, Depth. You can specify these values using their respective setter methods as follows − //Setting the properties of the Box box.setWidth(200.0); box.setHeight(400.0); box.setDepth(200.0); Finally, you need to add the object of the shape to the group by passing it as a parameter of the constructor as shown below. //Creating a Group object Group root = new Group(box); The following table gives you the list of various 3D shapes provided by JavaFX. A cuboid is a three-dimensional shape with a length (depth), width, and a height. In JavaFX a three-dimensional box is represented by a class named Box. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a Box node in JavaFX. This class has 3 properties of the double datatype namely − width − The width of the box. width − The width of the box. height − The height of the box. height − The height of the box. depth − The depth of the box. depth − The depth of the box. A cylinder is a closed solid that has two parallel (mostly circular) bases connected by a curved surface. It is described by two parameters, namely, the radius of its circular base and the height of the cylinder. In JavaFX, a cylinder is represented by a class named Cylinder. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a cylinder node in JavaFX. This class has 2 properties of the double datatype namely − height − The height of the Cylinder. height − The height of the Cylinder. radius − The radius of the Cylinder. radius − The radius of the Cylinder. A sphere is defined as the set of points that are all at the same distance r from a given point in a 3D space. This distance r is the radius of the sphere and the given point is the centre of the sphere. In JavaFX, a sphere is represented by a class named Sphere. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a sphere node in JavaFX. This class has a property named radius of double datatype. It represents the radius of a Sphere. For all the 3 Dimensional objects, you can set various properties like Cull Face, Drawing Mode, Material. The following section discusses the properties of 3D objects. In general, culling is the removal of improperly oriented parts of a shape (which are not visible in the view area). The Cull Face property is of the type CullFace and it represents the Cull Face of a 3D shape. You can set the Cull Face of a shape using the method setCullFace() as shown below − box.setCullFace(CullFace.NONE); The stroke type of a shape can be − None − No culling is performed (CullFace.NONE). None − No culling is performed (CullFace.NONE). Front − All the front facing polygons are culled. (CullFace.FRONT). Front − All the front facing polygons are culled. (CullFace.FRONT). Back − All the back facing polygons are culled. (StrokeType.BACK). Back − All the back facing polygons are culled. (StrokeType.BACK). By default, the cull face of a 3-Dimensional shape is Back. The following program is an example which demonstrates various cull faces of the sphere. Save this code in a file with the name SphereCullFace.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.CullFace; import javafx.stage.Stage; import javafx.scene.shape.Sphere; public class SphereCullFace extends Application { @Override public void start(Stage stage) { //Drawing Sphere1 Sphere sphere1 = new Sphere(); //Setting the radius of the Sphere sphere1.setRadius(50.0); //Setting the position of the sphere sphere1.setTranslateX(100); sphere1.setTranslateY(150); //setting the cull face of the sphere to front sphere1.setCullFace(CullFace.FRONT); //Drawing Sphere2 Sphere sphere2 = new Sphere(); //Setting the radius of the Sphere sphere2.setRadius(50.0); //Setting the position of the sphere sphere2.setTranslateX(300); sphere2.setTranslateY(150); //Setting the cull face of the sphere to back sphere2.setCullFace(CullFace.BACK); //Drawing Sphere3 Sphere sphere3 = new Sphere(); //Setting the radius of the Sphere sphere3.setRadius(50.0); //Setting the position of the sphere sphere3.setTranslateX(500); sphere3.setTranslateY(150); //Setting the cull face of the sphere to none sphere2.setCullFace(CullFace.NONE); //Creating a Group object Group root = new Group(sphere1, sphere2, sphere3); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Drawing a Sphere"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved Java file from the command prompt using the following commands. javac SphereCullFace.java java SphereCullFace On executing, the above program generates a JavaFX window displaying three spheres with cull face values FRONT, BACK and NONE respectively as follows − It is the property is of the type DrawMode and it represents the drawing mode used to draw the current 3D shape. You can choose the draw mode to draw a 3D shape using the method setDrawMode () as follows − box.setDrawMode(DrawMode.FILL); In JavaFX, you can choose two draw modes to draw a 3D shape, which are − Fill − This mode draws and fills a 2D shape (DrawMode.FILL). Fill − This mode draws and fills a 2D shape (DrawMode.FILL). Line − This mode draws a 3D shape using lines (DrawMode.LINE). Line − This mode draws a 3D shape using lines (DrawMode.LINE). By default, the drawing mode of a 3Dimensional shape is fill. The following program is an example which demonstrates various draw modes of a 3D box. Save this code in a file with the name BoxDrawMode.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.PerspectiveCamera; import javafx.scene.Scene; import javafx.scene.shape.Box; import javafx.scene.shape.DrawMode; import javafx.stage.Stage; public class BoxDrawMode extends Application { @Override public void start(Stage stage) { //Drawing a Box Box box1 = new Box(); //Setting the properties of the Box box1.setWidth(100.0); box1.setHeight(100.0); box1.setDepth(100.0); //Setting the position of the box box1.setTranslateX(200); box1.setTranslateY(150); box1.setTranslateZ(0); //Setting the drawing mode of the box box1.setDrawMode(DrawMode.LINE); //Drawing a Box Box box2 = new Box(); //Setting the properties of the Box box2.setWidth(100.0); box2.setHeight(100.0); box2.setDepth(100.0); //Setting the position of the box box2.setTranslateX(450); //450 box2.setTranslateY(150);//150 box2.setTranslateZ(300); //Setting the drawing mode of the box box2.setDrawMode(DrawMode.FILL); //Creating a Group object Group root = new Group(box1, box2); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting camera PerspectiveCamera camera = new PerspectiveCamera(false); camera.setTranslateX(0); camera.setTranslateY(0); camera.setTranslateZ(0); scene.setCamera(camera); //Setting title to the Stage stage.setTitle("Drawing a Box"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac BoxDrawMode.java java BoxDrawMode On executing, the above program generates a JavaFX window displaying two boxes with draw mode values LINE and FILL respectively, as follows − The cull Face property is of the type Material and it is used to choose the surface of the material of a 3D shape. You can set the material of a 3D shape using the method setCullFace() as follows − cylinder.setMaterial(material); As mentioned above for this method, you need to pass an object of the type Material. The PhongMaterial class of the package javafx.scene.paint is a sub class of this class and provides 7 properties that represent a Phong shaded material. You can apply all these type of materials to the surface of a 3D shape using the setter methods of these properties. Following are the type of materials that are available in JavaFX − bumpMap − This represents a normal map stored as a RGB Image. bumpMap − This represents a normal map stored as a RGB Image. diffuseMap − This represents a diffuse map. diffuseMap − This represents a diffuse map. selfIlluminationMap − This represents a self-illumination map of this PhongMaterial. selfIlluminationMap − This represents a self-illumination map of this PhongMaterial. specularMap − This represents a specular map of this PhongMaterial. specularMap − This represents a specular map of this PhongMaterial. diffuseColor − This represents a diffuse color of this PhongMaterial. diffuseColor − This represents a diffuse color of this PhongMaterial. specularColor − This represents a specular color of this PhongMaterial. specularColor − This represents a specular color of this PhongMaterial. specularPower − This represents a specular power of this PhongMaterial. specularPower − This represents a specular power of this PhongMaterial. By default, the material of a 3-Dimensional shape is a PhongMaterial with a diffuse color of light gray. Following is an example which displays various materials on the cylinder. Save this code in a file with the name CylinderMaterials.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.PerspectiveCamera; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.paint.Color; import javafx.scene.paint.PhongMaterial; import javafx.scene.shape.Cylinder; import javafx.stage.Stage; public class CylinderMaterials extends Application { @Override public void start(Stage stage) { //Drawing Cylinder1 Cylinder cylinder1 = new Cylinder(); //Setting the properties of the Cylinder cylinder1.setHeight(130.0f); cylinder1.setRadius(30.0f); //Setting the position of the Cylinder cylinder1.setTranslateX(100); cylinder1.setTranslateY(75); //Preparing the phong material of type bump map PhongMaterial material1 = new PhongMaterial(); material1.setBumpMap(new Image ("http://www.tutorialspoint.com/images/tplogo.gif")); //Setting the bump map material to Cylinder1 cylinder1.setMaterial(material1); //Drawing Cylinder2 Cylinder cylinder2 = new Cylinder(); //Setting the properties of the Cylinder cylinder2.setHeight(130.0f); cylinder2.setRadius(30.0f); //Setting the position of the Cylinder cylinder2.setTranslateX(200); cylinder2.setTranslateY(75); //Preparing the phong material of type diffuse map PhongMaterial material2 = new PhongMaterial(); material2.setDiffuseMap(new Image ("http://www.tutorialspoint.com/images/tp-logo.gif")); //Setting the diffuse map material to Cylinder2 cylinder2.setMaterial(material2); //Drawing Cylinder3 Cylinder cylinder3 = new Cylinder(); //Setting the properties of the Cylinder cylinder3.setHeight(130.0f); cylinder3.setRadius(30.0f); //Setting the position of the Cylinder cylinder3.setTranslateX(300); cylinder3.setTranslateY(75); //Preparing the phong material of type Self Illumination Map PhongMaterial material3 = new PhongMaterial(); material3.setSelfIlluminationMap(new Image ("http://www.tutorialspoint.com/images/tp-logo.gif")); //Setting the Self Illumination Map material to Cylinder3 cylinder3.setMaterial(material3); //Drawing Cylinder4 Cylinder cylinder4 = new Cylinder(); //Setting the properties of the Cylinder cylinder4.setHeight(130.0f); cylinder4.setRadius(30.0f); //Setting the position of the Cylinder cylinder4.setTranslateX(400); cylinder4.setTranslateY(75); //Preparing the phong material of type Specular Map PhongMaterial material4 = new PhongMaterial(); material4.setSpecularMap(new Image ("http://www.tutorialspoint.com/images/tp-logo.gif")); //Setting the Specular Map material to Cylinder4 cylinder4.setMaterial(material4); //Drawing Cylinder5 Cylinder cylinder5 = new Cylinder(); //Setting the properties of the Cylinder cylinder5.setHeight(130.0f); cylinder5.setRadius(30.0f); //Setting the position of the Cylinder cylinder5.setTranslateX(100); cylinder5.setTranslateY(300); //Preparing the phong material of type diffuse color PhongMaterial material5 = new PhongMaterial(); material5.setDiffuseColor(Color.BLANCHEDALMOND); //Setting the diffuse color material to Cylinder5 cylinder5.setMaterial(material5); //Drawing Cylinder6 Cylinder cylinder6 = new Cylinder(); //Setting the properties of the Cylinder cylinder6.setHeight(130.0f); cylinder6.setRadius(30.0f); //Setting the position of the Cylinder cylinder6.setTranslateX(200); cylinder6.setTranslateY(300); //Preparing the phong material of type specular color PhongMaterial material6 = new PhongMaterial(); //setting the specular color map to the material material6.setSpecularColor(Color.BLANCHEDALMOND); //Setting the specular color material to Cylinder6 cylinder6.setMaterial(material6); //Drawing Cylinder7 Cylinder cylinder7 = new Cylinder(); //Setting the properties of the Cylinder cylinder7.setHeight(130.0f); cylinder7.setRadius(30.0f); //Setting the position of the Cylinder cylinder7.setTranslateX(300); cylinder7.setTranslateY(300); //Preparing the phong material of type Specular Power PhongMaterial material7 = new PhongMaterial(); material7.setSpecularPower(0.1); //Setting the Specular Power material to the Cylinder cylinder7.setMaterial(material7); //Creating a Group object Group root = new Group(cylinder1 ,cylinder2, cylinder3, cylinder4, cylinder5, cylinder6, cylinder7); //Creating a scene object Scene scene = new Scene(root, 600, 400); //Setting camera PerspectiveCamera camera = new PerspectiveCamera(false); camera.setTranslateX(0); camera.setTranslateY(0); camera.setTranslateZ(-10); scene.setCamera(camera); //Setting title to the Stage stage.setTitle("Drawing a cylinder"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. Javac CylinderMaterials.java java CylinderMaterials On executing, the above program generates a JavaFX window displaying 7 cylinders with Materials, Bump Map, Diffuse Map, Self-Illumination Map, Specular Map, Diffuse Color, Specular Color, (BLANCHEDALMOND) Specular Power, respectively, as shown in the following screenshot − 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 2066, "s": 1900, "text": "In the earlier chapters, we have seen how to draw 2D shapes on an XY plane. In addition to these 2D shapes, we can draw several other 3D shapes as well using JavaFX." }, { "code": null, "e": 2193, "s": 2066, "text": "In general, a 3D shape is a geometrical figure that can be drawn on the XYZ plane. These include a Cylinder, Sphere and a Box." }, { "code": null, "e": 2405, "s": 2193, "text": "Each of the above mentioned 3D shape is represented by a class and all these classes belong to the package javafx.scene.shape. The class named Shape3D is the base class of all the 3-Dimensional shapes in JavaFX." }, { "code": null, "e": 2452, "s": 2405, "text": "To create a 3-Dimensional shape, you need to −" }, { "code": null, "e": 2511, "s": 2452, "text": "Instantiate the respective class of the required 3D shape." }, { "code": null, "e": 2570, "s": 2511, "text": "Instantiate the respective class of the required 3D shape." }, { "code": null, "e": 2606, "s": 2570, "text": "Set the properties of the 3D shape." }, { "code": null, "e": 2642, "s": 2606, "text": "Set the properties of the 3D shape." }, { "code": null, "e": 2680, "s": 2642, "text": "Add the 3D shape object to the group." }, { "code": null, "e": 2718, "s": 2680, "text": "Add the 3D shape object to the group." }, { "code": null, "e": 2912, "s": 2718, "text": "To create a 3-Dimensional shape, first of all you need to instantiate its respective class. For example, if you want to create a 3D box, you need to instantiate the class named Box as follows −" }, { "code": null, "e": 2934, "s": 2912, "text": "Box box = new Box();\n" }, { "code": null, "e": 3036, "s": 2934, "text": "After instantiating the class, you need to set the properties for the shape using the setter methods." }, { "code": null, "e": 3189, "s": 3036, "text": "For example, to draw a 3D box you need to pass its Width, Height, Depth. You can specify these values using their respective setter methods as follows −" }, { "code": null, "e": 3295, "s": 3189, "text": "//Setting the properties of the Box \nbox.setWidth(200.0); \nbox.setHeight(400.0); \nbox.setDepth(200.0);\n" }, { "code": null, "e": 3421, "s": 3295, "text": "Finally, you need to add the object of the shape to the group by passing it as a parameter of the constructor as shown below." }, { "code": null, "e": 3479, "s": 3421, "text": "//Creating a Group object \nGroup root = new Group(box);\n" }, { "code": null, "e": 3559, "s": 3479, "text": "The following table gives you the list of various 3D shapes provided by JavaFX." }, { "code": null, "e": 3641, "s": 3559, "text": "A cuboid is a three-dimensional shape with a length (depth), width, and a height." }, { "code": null, "e": 3766, "s": 3641, "text": "In JavaFX a three-dimensional box is represented by a class named Box. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 3832, "s": 3766, "text": "By instantiating this class, you can create a Box node in JavaFX." }, { "code": null, "e": 3892, "s": 3832, "text": "This class has 3 properties of the double datatype namely −" }, { "code": null, "e": 3922, "s": 3892, "text": "width − The width of the box." }, { "code": null, "e": 3952, "s": 3922, "text": "width − The width of the box." }, { "code": null, "e": 3984, "s": 3952, "text": "height − The height of the box." }, { "code": null, "e": 4016, "s": 3984, "text": "height − The height of the box." }, { "code": null, "e": 4046, "s": 4016, "text": "depth − The depth of the box." }, { "code": null, "e": 4076, "s": 4046, "text": "depth − The depth of the box." }, { "code": null, "e": 4182, "s": 4076, "text": "A cylinder is a closed solid that has two parallel (mostly circular) bases connected by a curved surface." }, { "code": null, "e": 4289, "s": 4182, "text": "It is described by two parameters, namely, the radius of its circular base and the height of the cylinder." }, { "code": null, "e": 4407, "s": 4289, "text": "In JavaFX, a cylinder is represented by a class named Cylinder. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 4538, "s": 4407, "text": "By instantiating this class, you can create a cylinder node in JavaFX. This class has 2 properties of the double datatype namely −" }, { "code": null, "e": 4575, "s": 4538, "text": "height − The height of the Cylinder." }, { "code": null, "e": 4612, "s": 4575, "text": "height − The height of the Cylinder." }, { "code": null, "e": 4649, "s": 4612, "text": "radius − The radius of the Cylinder." }, { "code": null, "e": 4686, "s": 4649, "text": "radius − The radius of the Cylinder." }, { "code": null, "e": 4890, "s": 4686, "text": "A sphere is defined as the set of points that are all at the same distance r from a given point in a 3D space. This distance r is the radius of the sphere and the given point is the centre of the sphere." }, { "code": null, "e": 5004, "s": 4890, "text": "In JavaFX, a sphere is represented by a class named Sphere. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 5073, "s": 5004, "text": "By instantiating this class, you can create a sphere node in JavaFX." }, { "code": null, "e": 5170, "s": 5073, "text": "This class has a property named radius of double datatype. It represents the radius of a Sphere." }, { "code": null, "e": 5276, "s": 5170, "text": "For all the 3 Dimensional objects, you can set various properties like Cull Face, Drawing Mode, Material." }, { "code": null, "e": 5338, "s": 5276, "text": "The following section discusses the properties of 3D objects." }, { "code": null, "e": 5455, "s": 5338, "text": "In general, culling is the removal of improperly oriented parts of a shape (which are not visible in the view area)." }, { "code": null, "e": 5635, "s": 5455, "text": "The Cull Face property is of the type CullFace and it represents the Cull Face of a 3D shape. You can set the Cull Face of a shape using the method setCullFace() as shown below −" }, { "code": null, "e": 5668, "s": 5635, "text": "box.setCullFace(CullFace.NONE);\n" }, { "code": null, "e": 5704, "s": 5668, "text": "The stroke type of a shape can be −" }, { "code": null, "e": 5752, "s": 5704, "text": "None − No culling is performed (CullFace.NONE)." }, { "code": null, "e": 5800, "s": 5752, "text": "None − No culling is performed (CullFace.NONE)." }, { "code": null, "e": 5868, "s": 5800, "text": "Front − All the front facing polygons are culled. (CullFace.FRONT)." }, { "code": null, "e": 5936, "s": 5868, "text": "Front − All the front facing polygons are culled. (CullFace.FRONT)." }, { "code": null, "e": 6003, "s": 5936, "text": "Back − All the back facing polygons are culled. (StrokeType.BACK)." }, { "code": null, "e": 6070, "s": 6003, "text": "Back − All the back facing polygons are culled. (StrokeType.BACK)." }, { "code": null, "e": 6130, "s": 6070, "text": "By default, the cull face of a 3-Dimensional shape is Back." }, { "code": null, "e": 6279, "s": 6130, "text": "The following program is an example which demonstrates various cull faces of the sphere. Save this code in a file with the name SphereCullFace.java." }, { "code": null, "e": 8238, "s": 6279, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.shape.CullFace; \nimport javafx.stage.Stage; \nimport javafx.scene.shape.Sphere; \n \npublic class SphereCullFace extends Application { \n @Override \n public void start(Stage stage) { \n //Drawing Sphere1 \n Sphere sphere1 = new Sphere();\n \n //Setting the radius of the Sphere \n sphere1.setRadius(50.0); \n \n //Setting the position of the sphere \n sphere1.setTranslateX(100); \n sphere1.setTranslateY(150); \n \n //setting the cull face of the sphere to front \n sphere1.setCullFace(CullFace.FRONT); \n \n //Drawing Sphere2 \n Sphere sphere2 = new Sphere(); \n \n //Setting the radius of the Sphere \n sphere2.setRadius(50.0); \n \n //Setting the position of the sphere \n sphere2.setTranslateX(300); \n sphere2.setTranslateY(150); \n \n //Setting the cull face of the sphere to back \n sphere2.setCullFace(CullFace.BACK); \n \n //Drawing Sphere3 \n Sphere sphere3 = new Sphere(); \n \n //Setting the radius of the Sphere \n sphere3.setRadius(50.0); \n \n //Setting the position of the sphere \n sphere3.setTranslateX(500); \n sphere3.setTranslateY(150); \n \n //Setting the cull face of the sphere to none \n sphere2.setCullFace(CullFace.NONE); \n \n //Creating a Group object \n Group root = new Group(sphere1, sphere2, sphere3); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage\n stage.setTitle(\"Drawing a Sphere\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}" }, { "code": null, "e": 8332, "s": 8238, "text": "Compile and execute the saved Java file from the command prompt using the following commands." }, { "code": null, "e": 8381, "s": 8332, "text": "javac SphereCullFace.java \njava SphereCullFace \n" }, { "code": null, "e": 8533, "s": 8381, "text": "On executing, the above program generates a JavaFX window displaying three spheres with cull face values FRONT, BACK and NONE respectively as follows −" }, { "code": null, "e": 8740, "s": 8533, "text": "It is the property is of the type DrawMode and it represents the drawing mode used to draw the current 3D shape. You can choose the draw mode to draw a 3D shape using the method setDrawMode () as follows −" }, { "code": null, "e": 8774, "s": 8740, "text": "box.setDrawMode(DrawMode.FILL); \n" }, { "code": null, "e": 8847, "s": 8774, "text": "In JavaFX, you can choose two draw modes to draw a 3D shape, which are −" }, { "code": null, "e": 8908, "s": 8847, "text": "Fill − This mode draws and fills a 2D shape (DrawMode.FILL)." }, { "code": null, "e": 8969, "s": 8908, "text": "Fill − This mode draws and fills a 2D shape (DrawMode.FILL)." }, { "code": null, "e": 9032, "s": 8969, "text": "Line − This mode draws a 3D shape using lines (DrawMode.LINE)." }, { "code": null, "e": 9095, "s": 9032, "text": "Line − This mode draws a 3D shape using lines (DrawMode.LINE)." }, { "code": null, "e": 9157, "s": 9095, "text": "By default, the drawing mode of a 3Dimensional shape is fill." }, { "code": null, "e": 9301, "s": 9157, "text": "The following program is an example which demonstrates various draw modes of a 3D box. Save this code in a file with the name BoxDrawMode.java." }, { "code": null, "e": 11235, "s": 9301, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.PerspectiveCamera; \nimport javafx.scene.Scene; \nimport javafx.scene.shape.Box; \nimport javafx.scene.shape.DrawMode; \nimport javafx.stage.Stage; \n \npublic class BoxDrawMode extends Application { \n @Override \n public void start(Stage stage) { \n //Drawing a Box \n Box box1 = new Box(); \n \n //Setting the properties of the Box \n box1.setWidth(100.0); \n box1.setHeight(100.0); \n box1.setDepth(100.0); \n \n //Setting the position of the box \n box1.setTranslateX(200); \n box1.setTranslateY(150); \n box1.setTranslateZ(0);\n \n //Setting the drawing mode of the box \n box1.setDrawMode(DrawMode.LINE); \n \n //Drawing a Box \n Box box2 = new Box(); \n \n //Setting the properties of the Box \n box2.setWidth(100.0); \n box2.setHeight(100.0); \n box2.setDepth(100.0); \n \n //Setting the position of the box \n box2.setTranslateX(450); //450 \n box2.setTranslateY(150);//150 \n box2.setTranslateZ(300); \n \n //Setting the drawing mode of the box \n box2.setDrawMode(DrawMode.FILL); \n \n //Creating a Group object \n Group root = new Group(box1, box2); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting camera \n PerspectiveCamera camera = new PerspectiveCamera(false); \n camera.setTranslateX(0); \n camera.setTranslateY(0); \n camera.setTranslateZ(0); \n scene.setCamera(camera); \n \n //Setting title to the Stage \n stage.setTitle(\"Drawing a Box\"); \n \n //Adding scene to the stage \n stage.setScene(scene);\n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}" }, { "code": null, "e": 11329, "s": 11235, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 11372, "s": 11329, "text": "javac BoxDrawMode.java \njava BoxDrawMode \n" }, { "code": null, "e": 11514, "s": 11372, "text": "On executing, the above program generates a JavaFX window displaying two boxes with draw mode values LINE and FILL respectively, as follows −" }, { "code": null, "e": 11712, "s": 11514, "text": "The cull Face property is of the type Material and it is used to choose the surface of the material of a 3D shape. You can set the material of a 3D shape using the method setCullFace() as follows −" }, { "code": null, "e": 11745, "s": 11712, "text": "cylinder.setMaterial(material);\n" }, { "code": null, "e": 12100, "s": 11745, "text": "As mentioned above for this method, you need to pass an object of the type Material. The PhongMaterial class of the package javafx.scene.paint is a sub class of this class and provides 7 properties that represent a Phong shaded material. You can apply all these type of materials to the surface of a 3D shape using the setter methods of these properties." }, { "code": null, "e": 12167, "s": 12100, "text": "Following are the type of materials that are available in JavaFX −" }, { "code": null, "e": 12229, "s": 12167, "text": "bumpMap − This represents a normal map stored as a RGB Image." }, { "code": null, "e": 12291, "s": 12229, "text": "bumpMap − This represents a normal map stored as a RGB Image." }, { "code": null, "e": 12335, "s": 12291, "text": "diffuseMap − This represents a diffuse map." }, { "code": null, "e": 12379, "s": 12335, "text": "diffuseMap − This represents a diffuse map." }, { "code": null, "e": 12464, "s": 12379, "text": "selfIlluminationMap − This represents a self-illumination map of this PhongMaterial." }, { "code": null, "e": 12549, "s": 12464, "text": "selfIlluminationMap − This represents a self-illumination map of this PhongMaterial." }, { "code": null, "e": 12617, "s": 12549, "text": "specularMap − This represents a specular map of this PhongMaterial." }, { "code": null, "e": 12685, "s": 12617, "text": "specularMap − This represents a specular map of this PhongMaterial." }, { "code": null, "e": 12755, "s": 12685, "text": "diffuseColor − This represents a diffuse color of this PhongMaterial." }, { "code": null, "e": 12825, "s": 12755, "text": "diffuseColor − This represents a diffuse color of this PhongMaterial." }, { "code": null, "e": 12897, "s": 12825, "text": "specularColor − This represents a specular color of this PhongMaterial." }, { "code": null, "e": 12969, "s": 12897, "text": "specularColor − This represents a specular color of this PhongMaterial." }, { "code": null, "e": 13041, "s": 12969, "text": "specularPower − This represents a specular power of this PhongMaterial." }, { "code": null, "e": 13113, "s": 13041, "text": "specularPower − This represents a specular power of this PhongMaterial." }, { "code": null, "e": 13218, "s": 13113, "text": "By default, the material of a 3-Dimensional shape is a PhongMaterial with a diffuse color of light gray." }, { "code": null, "e": 13355, "s": 13218, "text": "Following is an example which displays various materials on the cylinder. Save this code in a file with the name CylinderMaterials.java." }, { "code": null, "e": 19212, "s": 13355, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.PerspectiveCamera; \nimport javafx.scene.Scene; \nimport javafx.scene.image.Image; \nimport javafx.scene.paint.Color; \nimport javafx.scene.paint.PhongMaterial; \nimport javafx.scene.shape.Cylinder; \nimport javafx.stage.Stage;\n\npublic class CylinderMaterials extends Application { \n @Override \n public void start(Stage stage) { \n //Drawing Cylinder1 \n Cylinder cylinder1 = new Cylinder(); \n \n //Setting the properties of the Cylinder \n cylinder1.setHeight(130.0f); \n cylinder1.setRadius(30.0f); \n \n //Setting the position of the Cylinder \n cylinder1.setTranslateX(100); \n cylinder1.setTranslateY(75); \n \n //Preparing the phong material of type bump map \n PhongMaterial material1 = new PhongMaterial(); \n material1.setBumpMap(new Image\n (\"http://www.tutorialspoint.com/images/tplogo.gif\")); \n \n //Setting the bump map material to Cylinder1 \n cylinder1.setMaterial(material1); \n \n //Drawing Cylinder2 \n Cylinder cylinder2 = new Cylinder(); \n \n //Setting the properties of the Cylinder \n cylinder2.setHeight(130.0f); \n cylinder2.setRadius(30.0f); \n \n //Setting the position of the Cylinder \n cylinder2.setTranslateX(200); \n cylinder2.setTranslateY(75); \n \n //Preparing the phong material of type diffuse map \n PhongMaterial material2 = new PhongMaterial();\n material2.setDiffuseMap(new Image\n (\"http://www.tutorialspoint.com/images/tp-logo.gif\")); \n \n //Setting the diffuse map material to Cylinder2 \n cylinder2.setMaterial(material2); \n \n //Drawing Cylinder3 \n Cylinder cylinder3 = new Cylinder(); \n \n //Setting the properties of the Cylinder \n cylinder3.setHeight(130.0f); \n cylinder3.setRadius(30.0f); \n \n //Setting the position of the Cylinder \n cylinder3.setTranslateX(300); \n cylinder3.setTranslateY(75); \n \n //Preparing the phong material of type Self Illumination Map \n PhongMaterial material3 = new PhongMaterial(); \n material3.setSelfIlluminationMap(new Image\n (\"http://www.tutorialspoint.com/images/tp-logo.gif\")); \n \n //Setting the Self Illumination Map material to Cylinder3 \n cylinder3.setMaterial(material3); \n \n //Drawing Cylinder4 \n Cylinder cylinder4 = new Cylinder(); \n \n //Setting the properties of the Cylinder \n cylinder4.setHeight(130.0f); \n cylinder4.setRadius(30.0f); \n \n //Setting the position of the Cylinder \n cylinder4.setTranslateX(400); \n cylinder4.setTranslateY(75); \n \n //Preparing the phong material of type Specular Map \n PhongMaterial material4 = new PhongMaterial(); \n material4.setSpecularMap(new Image\n (\"http://www.tutorialspoint.com/images/tp-logo.gif\")); \n \n //Setting the Specular Map material to Cylinder4 \n cylinder4.setMaterial(material4); \n \n //Drawing Cylinder5 \n Cylinder cylinder5 = new Cylinder(); \n \n //Setting the properties of the Cylinder \n cylinder5.setHeight(130.0f); \n cylinder5.setRadius(30.0f); \n \n //Setting the position of the Cylinder \n cylinder5.setTranslateX(100); \n cylinder5.setTranslateY(300); \n \n //Preparing the phong material of type diffuse color \n PhongMaterial material5 = new PhongMaterial(); \n material5.setDiffuseColor(Color.BLANCHEDALMOND); \n \n //Setting the diffuse color material to Cylinder5 \n cylinder5.setMaterial(material5); \n \n //Drawing Cylinder6 \n Cylinder cylinder6 = new Cylinder(); \n \n //Setting the properties of the Cylinder \n cylinder6.setHeight(130.0f); \n cylinder6.setRadius(30.0f); \n \n //Setting the position of the Cylinder \n cylinder6.setTranslateX(200); \n cylinder6.setTranslateY(300); \n \n //Preparing the phong material of type specular color \n PhongMaterial material6 = new PhongMaterial(); \n \n //setting the specular color map to the material \n material6.setSpecularColor(Color.BLANCHEDALMOND); \n \n //Setting the specular color material to Cylinder6 \n cylinder6.setMaterial(material6); \n \n //Drawing Cylinder7 \n Cylinder cylinder7 = new Cylinder();\n \n //Setting the properties of the Cylinder \n cylinder7.setHeight(130.0f); \n cylinder7.setRadius(30.0f); \n \n //Setting the position of the Cylinder \n cylinder7.setTranslateX(300); \n cylinder7.setTranslateY(300); \n \n //Preparing the phong material of type Specular Power \n PhongMaterial material7 = new PhongMaterial(); \n material7.setSpecularPower(0.1); \n \n //Setting the Specular Power material to the Cylinder \n cylinder7.setMaterial(material7); \n \n //Creating a Group object \n Group root = new Group(cylinder1 ,cylinder2, cylinder3, \n cylinder4, cylinder5, cylinder6, cylinder7); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 400); \n \n //Setting camera \n PerspectiveCamera camera = new PerspectiveCamera(false); \n camera.setTranslateX(0); \n camera.setTranslateY(0); \n camera.setTranslateZ(-10); \n scene.setCamera(camera); \n \n //Setting title to the Stage \n stage.setTitle(\"Drawing a cylinder\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}" }, { "code": null, "e": 19306, "s": 19212, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 19361, "s": 19306, "text": "Javac CylinderMaterials.java \njava CylinderMaterials \n" }, { "code": null, "e": 19635, "s": 19361, "text": "On executing, the above program generates a JavaFX window displaying 7 cylinders with Materials, Bump Map, Diffuse Map, Self-Illumination Map, Specular Map, Diffuse Color, Specular Color, (BLANCHEDALMOND) Specular Power, respectively, as shown in the following screenshot −" }, { "code": null, "e": 19670, "s": 19635, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 19681, "s": 19670, "text": " Syed Raza" }, { "code": null, "e": 19717, "s": 19681, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 19753, "s": 19717, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 19786, "s": 19753, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 19822, "s": 19786, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 19829, "s": 19822, "text": " Print" }, { "code": null, "e": 19840, "s": 19829, "text": " Add Notes" } ]
Angular 10 formatNumber() Method - GeeksforGeeks
02 Jun, 2021 In this article, we are going to see what is formatNumber in Angular 10 and how to use it. formatNumber is used to format a number based on our requirement in decimal form. Syntax: formatNumber(value, locale, digitsInfo) Parameters: value: The number to format. locale: A locale code for the locale format. digitsInfo: Decimal representation options. Return Value: string: the formatted text string. NgModule: Module used by formatNumber is: CommonModule Approach: Create the Angular app to be used. In app.module.ts import LOCALE_ID because we need locale to be imported for using get formatNumber.import { LOCALE_ID, NgModule } from '@angular/core'; import { LOCALE_ID, NgModule } from '@angular/core'; In app.component.ts import formatNumber and LOCALE_ID inject LOCALE_ID as a public variable. In app.component.html show the local variable using string interpolation Serve the angular app using ng serve to see the output. Example 1: app.component.ts import { formatNumber } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatNumber(1000,this.locale, '7.1-5');constructor( @Inject(LOCALE_ID) public locale: string,){}} app.component.html <h1> GeeksforGeeks</h1> <p>Locale Number is : {{curr}}</p> Output: Example 2: app.component.ts import { formatNumber } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatNumber(100,this.locale, '2.1-5');constructor( @Inject(LOCALE_ID) public locale: string,){}} app.component.html <h1> GeeksforGeeks</h1> <p>Locale Number is : {{curr}}</p> Output: Example 3: app.component.ts import { formatNumber } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatNumber(3234,this.locale, '3.1-4');constructor( @Inject(LOCALE_ID) public locale: string,){}} app.component.html <h1> GeeksforGeeks</h1> <p>Locale Number is : {{curr}}</p> Output: Reference: https://angular.io/api/common/formatNumber Angular10 AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers How to use <mat-chip-list> and <mat-chip> in Angular Material ? How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event Angular PrimeNG Dropdown Component Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25109, "s": 25081, "text": "\n02 Jun, 2021" }, { "code": null, "e": 25200, "s": 25109, "text": "In this article, we are going to see what is formatNumber in Angular 10 and how to use it." }, { "code": null, "e": 25282, "s": 25200, "text": "formatNumber is used to format a number based on our requirement in decimal form." }, { "code": null, "e": 25290, "s": 25282, "text": "Syntax:" }, { "code": null, "e": 25330, "s": 25290, "text": "formatNumber(value, locale, digitsInfo)" }, { "code": null, "e": 25342, "s": 25330, "text": "Parameters:" }, { "code": null, "e": 25371, "s": 25342, "text": "value: The number to format." }, { "code": null, "e": 25416, "s": 25371, "text": "locale: A locale code for the locale format." }, { "code": null, "e": 25460, "s": 25416, "text": "digitsInfo: Decimal representation options." }, { "code": null, "e": 25476, "s": 25462, "text": "Return Value:" }, { "code": null, "e": 25511, "s": 25476, "text": "string: the formatted text string." }, { "code": null, "e": 25553, "s": 25511, "text": "NgModule: Module used by formatNumber is:" }, { "code": null, "e": 25566, "s": 25553, "text": "CommonModule" }, { "code": null, "e": 25577, "s": 25566, "text": "Approach: " }, { "code": null, "e": 25612, "s": 25577, "text": "Create the Angular app to be used." }, { "code": null, "e": 25764, "s": 25612, "text": "In app.module.ts import LOCALE_ID because we need locale to be imported for using get formatNumber.import { LOCALE_ID, NgModule } from '@angular/core';" }, { "code": null, "e": 25817, "s": 25764, "text": "import { LOCALE_ID, NgModule } from '@angular/core';" }, { "code": null, "e": 25871, "s": 25817, "text": "In app.component.ts import formatNumber and LOCALE_ID" }, { "code": null, "e": 25910, "s": 25871, "text": "inject LOCALE_ID as a public variable." }, { "code": null, "e": 25983, "s": 25910, "text": "In app.component.html show the local variable using string interpolation" }, { "code": null, "e": 26039, "s": 25983, "text": "Serve the angular app using ng serve to see the output." }, { "code": null, "e": 26050, "s": 26039, "text": "Example 1:" }, { "code": null, "e": 26067, "s": 26050, "text": "app.component.ts" }, { "code": "import { formatNumber } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatNumber(1000,this.locale, '7.1-5');constructor( @Inject(LOCALE_ID) public locale: string,){}}", "e": 26396, "s": 26067, "text": null }, { "code": null, "e": 26415, "s": 26396, "text": "app.component.html" }, { "code": "<h1> GeeksforGeeks</h1> <p>Locale Number is : {{curr}}</p>", "e": 26476, "s": 26415, "text": null }, { "code": null, "e": 26484, "s": 26476, "text": "Output:" }, { "code": null, "e": 26495, "s": 26484, "text": "Example 2:" }, { "code": null, "e": 26512, "s": 26495, "text": "app.component.ts" }, { "code": "import { formatNumber } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatNumber(100,this.locale, '2.1-5');constructor( @Inject(LOCALE_ID) public locale: string,){}}", "e": 26840, "s": 26512, "text": null }, { "code": null, "e": 26859, "s": 26840, "text": "app.component.html" }, { "code": "<h1> GeeksforGeeks</h1> <p>Locale Number is : {{curr}}</p>", "e": 26920, "s": 26859, "text": null }, { "code": null, "e": 26928, "s": 26920, "text": "Output:" }, { "code": null, "e": 26939, "s": 26928, "text": "Example 3:" }, { "code": null, "e": 26956, "s": 26939, "text": "app.component.ts" }, { "code": "import { formatNumber } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatNumber(3234,this.locale, '3.1-4');constructor( @Inject(LOCALE_ID) public locale: string,){}}", "e": 27285, "s": 26956, "text": null }, { "code": null, "e": 27304, "s": 27285, "text": "app.component.html" }, { "code": "<h1> GeeksforGeeks</h1> <p>Locale Number is : {{curr}}</p>", "e": 27365, "s": 27304, "text": null }, { "code": null, "e": 27373, "s": 27365, "text": "Output:" }, { "code": null, "e": 27427, "s": 27373, "text": "Reference: https://angular.io/api/common/formatNumber" }, { "code": null, "e": 27437, "s": 27427, "text": "Angular10" }, { "code": null, "e": 27458, "s": 27437, "text": "AngularJS-Directives" }, { "code": null, "e": 27468, "s": 27458, "text": "AngularJS" }, { "code": null, "e": 27485, "s": 27468, "text": "Web Technologies" }, { "code": null, "e": 27583, "s": 27485, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27592, "s": 27583, "text": "Comments" }, { "code": null, "e": 27605, "s": 27592, "text": "Old Comments" }, { "code": null, "e": 27649, "s": 27605, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 27713, "s": 27649, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 27766, "s": 27713, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 27790, "s": 27766, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 27825, "s": 27790, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 27867, "s": 27825, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27900, "s": 27867, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27943, "s": 27900, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28005, "s": 27943, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Sankey Diagram Basics with Python’s Plotly | by Thiago Carvalho | Towards Data Science
In this article, I’ll go through the basics of using Plotly and Python for drawing Sankey Diagrams. They’re a convenient chart for visualizing any kind of measurable flow — Some examples are the flow of travelers, spellers, and money. The creation of this diagram is credited to the Irish Captain Matthew H. P. R. Sankey, who used it to visualize the energy efficiency of steam engines. The idea of Sankey’s diagram is similar to a network chart, where links connect nodes. The main difference being that in Sankey’s model, the links have different widths that encode a measurable variable they have in common. For the following examples, I’ll use Plotly with Jupyter Lab to explore how to create a Sankey. import plotly.graph_objects as go There are different ways of building a chart with Plotly; I’ll use Graphical Objects, visualize the graphs with the Jupiter widgets, and export an HTML for the final visualization. Building a Sankey can be quite a struggle especially if you have too many nodes and connections, I’ll use lists for the examples to make it simpler, but you can adapt this logic with a JSON file or a Pandas Dataframe. We will use go.Sankey to build the chart, which requires a link. That link is a dictionary containing data about the connections we want to draw. source = [0, 0, 1, 1, 0]target = [2, 3, 4, 5, 4]value = [8, 2, 2, 8, 4] The source and target are lists of indexes for the nodes Plotly will connect, and the value is a list of numbers that will define the width of these connections. link = dict(source = source, target = target, value = value)data = go.Sankey(link = link)print(data) We saved the Sankey object to a variable called data, and now we can pass that data to a Figure; fig = go.Figure(data) And display the chart. fig.show() That’s the idea. Let’s try identifying those nodes so we can have a more unobstructed view of what is connecting what. We’ll need a dictionary with the node’s data, which should contain a list with the labels. We can also add more parameters such as pad to customize the distance between the nodes, or thickness to define the size of their handles. # datalabel = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE"]source = [0, 0, 1, 1, 0]target = [2, 3, 4, 5, 4]value = [8, 2, 2, 8, 4]# data to dict, dict to sankeylink = dict(source = source, target = target, value = value)node = dict(label = label, pad=50, thickness=5)data = go.Sankey(link = link, node=node)# plotfig = go.Figure(data)fig.show() That’s easier to understand. We can read the lists, and visualize how they connect. Now let’s try this with some real data, I’ll try to change this visualization from Vancouver’s 2020 Budget. I want to see the proportion of money flowing from the operational expenditures, to areas, to services. I will start with a node for the total expenditures, that will connect to the four areas, which will then link to their subdivisions — Let’s make a quick sketch of the idea. I’ve used the percentages to find the values, and build the following lists for the links. source = [0, 0, 0, 0, # Op Expeditures 1, 1, # Public Safety 2, 2, # Eng n Util 3, 3, 3, 3, 3, 3, # Community Serv 4, 4, 4] # Corp Supporttarget = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]value = [484500, 468350, 355300, 306850, 339150, 145350, 371450, 96900, 129200, 80750, 48450, 48450, 32300, 16150, 113050, 129200, 64600] Let’s also define the labels for the nodes. label = ['Operating Expeditures', 'Public Safety', 'Engineering and Utilities', 'Community-Related Services', 'Corporate Support', 'Police', 'Fire', 'Utilities', 'Engineering Public Works', 'Parks and Recreation', 'Arts, Culture, and Community Services', 'Library', 'Development, Buildings, and Licensing', 'Planning, Urban Design, and Sustainability', 'Other', 'Corporate Support', 'Debt and Capital (Non-Utility)', 'Contingencies and Transfers'] Once we have the data ready, all that’s left to do is define our figure and plot. Nice, it’s getting better. There’s another encoding we can use in our diagram, the color. We can define the colors of both the node and the links; to do so, we need a list with one color per element. color_node = ['#808B96', '#EC7063', '#F7DC6F', '#48C9B0', '#AF7AC5','#EC7063', '#EC7063','#F7DC6F', '#F7DC6F','#48C9B0', '#48C9B0', '#48C9B0', '#48C9B0', '#48C9B0', '#48C9B0','#AF7AC5', '#AF7AC5', '#AF7AC5']color_link = ['#EBBAB5', '#FEF3C7', '#A6E3D7', '#CBB4D5','#EBBAB5', '#EBBAB5','#FEF3C7', '#FEF3C7','#A6E3D7', '#A6E3D7', '#A6E3D7', '#A6E3D7', '#A6E3D7', '#A6E3D7','#CBB4D5', '#CBB4D5', '#CBB4D5'] Here I’m trying to highlight the area of each expenditure, I’m using similar colors for the nodes and links, with one being a little brighter than the other. Almost ready, all that’s left to do is add a title, adjust the details, and export the HTML file. We can update the layout of our figure before plotting, and this allows us to change the fonts, background colors, define the information on our tooltip, and much more. fig.update_layout( hovermode = 'x', title="Vancouver Operating Expeditures by Area of Service", font=dict(size = 10, color = 'white'), paper_bgcolor='#5B5958') Once the visualization is ready, we can export it to HTML. That is maybe the most natural part, all we have to do is call .write_html(‘filename.html’). Here you can see another example, where I added the operating revenues. I’ve tried to remove the white text-shadow, but I couldn’t find a solution within Plotly, the best answer I found was to override the CSS. You can find the code for this article here, and the webpage with the interactive Sankey here. Thanks for taking the time to read my article, I hope you enjoyed it. More Resources:Plotly — Graph Objects Plotly — Sankey Diagrams
[ { "code": null, "e": 272, "s": 172, "text": "In this article, I’ll go through the basics of using Plotly and Python for drawing Sankey Diagrams." }, { "code": null, "e": 407, "s": 272, "text": "They’re a convenient chart for visualizing any kind of measurable flow — Some examples are the flow of travelers, spellers, and money." }, { "code": null, "e": 559, "s": 407, "text": "The creation of this diagram is credited to the Irish Captain Matthew H. P. R. Sankey, who used it to visualize the energy efficiency of steam engines." }, { "code": null, "e": 646, "s": 559, "text": "The idea of Sankey’s diagram is similar to a network chart, where links connect nodes." }, { "code": null, "e": 783, "s": 646, "text": "The main difference being that in Sankey’s model, the links have different widths that encode a measurable variable they have in common." }, { "code": null, "e": 879, "s": 783, "text": "For the following examples, I’ll use Plotly with Jupyter Lab to explore how to create a Sankey." }, { "code": null, "e": 913, "s": 879, "text": "import plotly.graph_objects as go" }, { "code": null, "e": 1094, "s": 913, "text": "There are different ways of building a chart with Plotly; I’ll use Graphical Objects, visualize the graphs with the Jupiter widgets, and export an HTML for the final visualization." }, { "code": null, "e": 1312, "s": 1094, "text": "Building a Sankey can be quite a struggle especially if you have too many nodes and connections, I’ll use lists for the examples to make it simpler, but you can adapt this logic with a JSON file or a Pandas Dataframe." }, { "code": null, "e": 1377, "s": 1312, "text": "We will use go.Sankey to build the chart, which requires a link." }, { "code": null, "e": 1458, "s": 1377, "text": "That link is a dictionary containing data about the connections we want to draw." }, { "code": null, "e": 1530, "s": 1458, "text": "source = [0, 0, 1, 1, 0]target = [2, 3, 4, 5, 4]value = [8, 2, 2, 8, 4]" }, { "code": null, "e": 1692, "s": 1530, "text": "The source and target are lists of indexes for the nodes Plotly will connect, and the value is a list of numbers that will define the width of these connections." }, { "code": null, "e": 1793, "s": 1692, "text": "link = dict(source = source, target = target, value = value)data = go.Sankey(link = link)print(data)" }, { "code": null, "e": 1890, "s": 1793, "text": "We saved the Sankey object to a variable called data, and now we can pass that data to a Figure;" }, { "code": null, "e": 1912, "s": 1890, "text": "fig = go.Figure(data)" }, { "code": null, "e": 1935, "s": 1912, "text": "And display the chart." }, { "code": null, "e": 1946, "s": 1935, "text": "fig.show()" }, { "code": null, "e": 2065, "s": 1946, "text": "That’s the idea. Let’s try identifying those nodes so we can have a more unobstructed view of what is connecting what." }, { "code": null, "e": 2295, "s": 2065, "text": "We’ll need a dictionary with the node’s data, which should contain a list with the labels. We can also add more parameters such as pad to customize the distance between the nodes, or thickness to define the size of their handles." }, { "code": null, "e": 2642, "s": 2295, "text": "# datalabel = [\"ZERO\", \"ONE\", \"TWO\", \"THREE\", \"FOUR\", \"FIVE\"]source = [0, 0, 1, 1, 0]target = [2, 3, 4, 5, 4]value = [8, 2, 2, 8, 4]# data to dict, dict to sankeylink = dict(source = source, target = target, value = value)node = dict(label = label, pad=50, thickness=5)data = go.Sankey(link = link, node=node)# plotfig = go.Figure(data)fig.show()" }, { "code": null, "e": 2726, "s": 2642, "text": "That’s easier to understand. We can read the lists, and visualize how they connect." }, { "code": null, "e": 2834, "s": 2726, "text": "Now let’s try this with some real data, I’ll try to change this visualization from Vancouver’s 2020 Budget." }, { "code": null, "e": 2938, "s": 2834, "text": "I want to see the proportion of money flowing from the operational expenditures, to areas, to services." }, { "code": null, "e": 3112, "s": 2938, "text": "I will start with a node for the total expenditures, that will connect to the four areas, which will then link to their subdivisions — Let’s make a quick sketch of the idea." }, { "code": null, "e": 3203, "s": 3112, "text": "I’ve used the percentages to find the values, and build the following lists for the links." }, { "code": null, "e": 3697, "s": 3203, "text": "source = [0, 0, 0, 0, # Op Expeditures 1, 1, # Public Safety 2, 2, # Eng n Util 3, 3, 3, 3, 3, 3, # Community Serv 4, 4, 4] # Corp Supporttarget = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]value = [484500, 468350, 355300, 306850, 339150, 145350, 371450, 96900, 129200, 80750, 48450, 48450, 32300, 16150, 113050, 129200, 64600]" }, { "code": null, "e": 3741, "s": 3697, "text": "Let’s also define the labels for the nodes." }, { "code": null, "e": 4336, "s": 3741, "text": "label = ['Operating Expeditures', 'Public Safety', 'Engineering and Utilities', 'Community-Related Services', 'Corporate Support', 'Police', 'Fire', 'Utilities', 'Engineering Public Works', 'Parks and Recreation', 'Arts, Culture, and Community Services', 'Library', 'Development, Buildings, and Licensing', 'Planning, Urban Design, and Sustainability', 'Other', 'Corporate Support', 'Debt and Capital (Non-Utility)', 'Contingencies and Transfers']" }, { "code": null, "e": 4418, "s": 4336, "text": "Once we have the data ready, all that’s left to do is define our figure and plot." }, { "code": null, "e": 4445, "s": 4418, "text": "Nice, it’s getting better." }, { "code": null, "e": 4508, "s": 4445, "text": "There’s another encoding we can use in our diagram, the color." }, { "code": null, "e": 4618, "s": 4508, "text": "We can define the colors of both the node and the links; to do so, we need a list with one color per element." }, { "code": null, "e": 5022, "s": 4618, "text": "color_node = ['#808B96', '#EC7063', '#F7DC6F', '#48C9B0', '#AF7AC5','#EC7063', '#EC7063','#F7DC6F', '#F7DC6F','#48C9B0', '#48C9B0', '#48C9B0', '#48C9B0', '#48C9B0', '#48C9B0','#AF7AC5', '#AF7AC5', '#AF7AC5']color_link = ['#EBBAB5', '#FEF3C7', '#A6E3D7', '#CBB4D5','#EBBAB5', '#EBBAB5','#FEF3C7', '#FEF3C7','#A6E3D7', '#A6E3D7', '#A6E3D7', '#A6E3D7', '#A6E3D7', '#A6E3D7','#CBB4D5', '#CBB4D5', '#CBB4D5']" }, { "code": null, "e": 5180, "s": 5022, "text": "Here I’m trying to highlight the area of each expenditure, I’m using similar colors for the nodes and links, with one being a little brighter than the other." }, { "code": null, "e": 5278, "s": 5180, "text": "Almost ready, all that’s left to do is add a title, adjust the details, and export the HTML file." }, { "code": null, "e": 5447, "s": 5278, "text": "We can update the layout of our figure before plotting, and this allows us to change the fonts, background colors, define the information on our tooltip, and much more." }, { "code": null, "e": 5619, "s": 5447, "text": "fig.update_layout( hovermode = 'x', title=\"Vancouver Operating Expeditures by Area of Service\", font=dict(size = 10, color = 'white'), paper_bgcolor='#5B5958')" }, { "code": null, "e": 5771, "s": 5619, "text": "Once the visualization is ready, we can export it to HTML. That is maybe the most natural part, all we have to do is call .write_html(‘filename.html’)." }, { "code": null, "e": 5843, "s": 5771, "text": "Here you can see another example, where I added the operating revenues." }, { "code": null, "e": 5982, "s": 5843, "text": "I’ve tried to remove the white text-shadow, but I couldn’t find a solution within Plotly, the best answer I found was to override the CSS." }, { "code": null, "e": 6077, "s": 5982, "text": "You can find the code for this article here, and the webpage with the interactive Sankey here." }, { "code": null, "e": 6147, "s": 6077, "text": "Thanks for taking the time to read my article, I hope you enjoyed it." } ]
Check if an array is empty or not in JavaScript - GeeksforGeeks
20 Jul, 2021 Method 1: Using Array.isArray() method and array.length property: The array can be check if it is actually an array and it exists by the Array.isArray() method. This method returns true if the Object passed as a parameter is an array. It also checks for the case if the array is undefined or null. The array can be checked if it is empty by using the array.length property. This property returns the number of elements in the array. If the number is greater than 0, it evaluates to true.This method and property can be both used together with the AND(&&) operator to determine whether the array exists and is not empty. Syntax: Array.isArray(emptyArray) && emptyArray.length Example: <!DOCTYPE html><html> <head> <title> Check if an array is empty or exists </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Check if an array is empty or exists </b> <p> Click on the button to check if array exists and is not empty </p> <p>emptyArray = []</p> <p>nonExistantArray = undefined</p> <p>fineArray = [1, 2, 3, 4, 5]</p> <p> Output for emptyArray: <span class="output-empty"></span> </p> <p> Output for nonExistantArray: <span class="output-non"></span> </p> <p> Output for fineArray: <span class="output-ok"></span> </p> <button onclick="checkArray()"> Check Array </button> <script type="text/javascript"> function checkArray() { let emptyArray = []; let nonExistantArray = undefined; let fineArray = [1, 2, 3, 4, 5]; if (Array.isArray(emptyArray) && emptyArray.length) output = true; else output = false; document.querySelector('.output-empty').textContent = output; if (Array.isArray(nonExistantArray) && nonExistantArray.length) output = true; else output = false; document.querySelector('.output-non').textContent = output; if (Array.isArray(fineArray) && fineArray.length) output = true; else output = false; document.querySelector('.output-ok').textContent = output; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: Checking the type and length of the array: The array can be checked if it exists by checking if the type of the array is ‘undefined’ with the typeof operator. The array is also checked if it is ‘null’. These two things verify that the array exists. The array can be checked if it is empty by using the array.length property. By checking if the property exists, it can make sure that it is an array, and by checking if the length returned is greater than 0, it can be made sure that the array is not empty. These properties can then be used together with the AND(&&) operator to determine whether the array exists and is not empty. Syntax: typeof emptyArray != "undefined" && emptyArray != null && emptyArray.length != null && emptyArray.length > 0 Example: <!DOCTYPE html><html> <head> <title> Check if an array is empty or exists </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Check if an array is empty or exists </b> <p> Click on the button to check if array exists and is not empty </p> <p>emptyArray = []</p> <p>nonExistantArray = undefined</p> <p>fineArray = [1, 2, 3, 4, 5]</p> <p>Output for emptyArray: <span class="output-empty"></span> </p> <p> Output for nonExistantArray: <span class="output-non"></span> </p> <p> Output for fineArray: <span class="output-ok"></span> </p> <button onclick="checkArray()"> Check Array </button> <script type="text/javascript"> function checkArray() { let emptyArray = []; let nonExistantArray = undefined; let fineArray = [1, 2, 3, 4, 5]; if (typeof emptyArray != "undefined" && emptyArray != null && emptyArray.length != null && emptyArray.length > 0) output = true; else output = false; document.querySelector('.output-empty').textContent = output; if (typeof nonExistantArray != "undefined" && nonExistantArray != null && nonExistantArray.length != null && nonExistantArray.length > 0) output = true; else output = false; document.querySelector('.output-non').textContent = output; if (typeof fineArray != "undefined" && fineArray != null && fineArray.length != null && fineArray.length > 0) output = true; else output = false; document.querySelector('.output-ok').textContent = output; } </script></body> </html> Output: Before clicking the button: After clicking the button: JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. javascript-string Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 30060, "s": 30032, "text": "\n20 Jul, 2021" }, { "code": null, "e": 30358, "s": 30060, "text": "Method 1: Using Array.isArray() method and array.length property: The array can be check if it is actually an array and it exists by the Array.isArray() method. This method returns true if the Object passed as a parameter is an array. It also checks for the case if the array is undefined or null." }, { "code": null, "e": 30680, "s": 30358, "text": "The array can be checked if it is empty by using the array.length property. This property returns the number of elements in the array. If the number is greater than 0, it evaluates to true.This method and property can be both used together with the AND(&&) operator to determine whether the array exists and is not empty." }, { "code": null, "e": 30688, "s": 30680, "text": "Syntax:" }, { "code": null, "e": 30735, "s": 30688, "text": "Array.isArray(emptyArray) && emptyArray.length" }, { "code": null, "e": 30744, "s": 30735, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Check if an array is empty or exists </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Check if an array is empty or exists </b> <p> Click on the button to check if array exists and is not empty </p> <p>emptyArray = []</p> <p>nonExistantArray = undefined</p> <p>fineArray = [1, 2, 3, 4, 5]</p> <p> Output for emptyArray: <span class=\"output-empty\"></span> </p> <p> Output for nonExistantArray: <span class=\"output-non\"></span> </p> <p> Output for fineArray: <span class=\"output-ok\"></span> </p> <button onclick=\"checkArray()\"> Check Array </button> <script type=\"text/javascript\"> function checkArray() { let emptyArray = []; let nonExistantArray = undefined; let fineArray = [1, 2, 3, 4, 5]; if (Array.isArray(emptyArray) && emptyArray.length) output = true; else output = false; document.querySelector('.output-empty').textContent = output; if (Array.isArray(nonExistantArray) && nonExistantArray.length) output = true; else output = false; document.querySelector('.output-non').textContent = output; if (Array.isArray(fineArray) && fineArray.length) output = true; else output = false; document.querySelector('.output-ok').textContent = output; } </script></body> </html> ", "e": 32447, "s": 30744, "text": null }, { "code": null, "e": 32455, "s": 32447, "text": "Output:" }, { "code": null, "e": 32483, "s": 32455, "text": "Before clicking the button:" }, { "code": null, "e": 32510, "s": 32483, "text": "After clicking the button:" }, { "code": null, "e": 32769, "s": 32510, "text": "Method 2: Checking the type and length of the array: The array can be checked if it exists by checking if the type of the array is ‘undefined’ with the typeof operator. The array is also checked if it is ‘null’. These two things verify that the array exists." }, { "code": null, "e": 33026, "s": 32769, "text": "The array can be checked if it is empty by using the array.length property. By checking if the property exists, it can make sure that it is an array, and by checking if the length returned is greater than 0, it can be made sure that the array is not empty." }, { "code": null, "e": 33151, "s": 33026, "text": "These properties can then be used together with the AND(&&) operator to determine whether the array exists and is not empty." }, { "code": null, "e": 33159, "s": 33151, "text": "Syntax:" }, { "code": null, "e": 33268, "s": 33159, "text": "typeof emptyArray != \"undefined\" && emptyArray != null && emptyArray.length != null\n&& emptyArray.length > 0" }, { "code": null, "e": 33277, "s": 33268, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Check if an array is empty or exists </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Check if an array is empty or exists </b> <p> Click on the button to check if array exists and is not empty </p> <p>emptyArray = []</p> <p>nonExistantArray = undefined</p> <p>fineArray = [1, 2, 3, 4, 5]</p> <p>Output for emptyArray: <span class=\"output-empty\"></span> </p> <p> Output for nonExistantArray: <span class=\"output-non\"></span> </p> <p> Output for fineArray: <span class=\"output-ok\"></span> </p> <button onclick=\"checkArray()\"> Check Array </button> <script type=\"text/javascript\"> function checkArray() { let emptyArray = []; let nonExistantArray = undefined; let fineArray = [1, 2, 3, 4, 5]; if (typeof emptyArray != \"undefined\" && emptyArray != null && emptyArray.length != null && emptyArray.length > 0) output = true; else output = false; document.querySelector('.output-empty').textContent = output; if (typeof nonExistantArray != \"undefined\" && nonExistantArray != null && nonExistantArray.length != null && nonExistantArray.length > 0) output = true; else output = false; document.querySelector('.output-non').textContent = output; if (typeof fineArray != \"undefined\" && fineArray != null && fineArray.length != null && fineArray.length > 0) output = true; else output = false; document.querySelector('.output-ok').textContent = output; } </script></body> </html> ", "e": 35455, "s": 33277, "text": null }, { "code": null, "e": 35463, "s": 35455, "text": "Output:" }, { "code": null, "e": 35491, "s": 35463, "text": "Before clicking the button:" }, { "code": null, "e": 35518, "s": 35491, "text": "After clicking the button:" }, { "code": null, "e": 35737, "s": 35518, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 35755, "s": 35737, "text": "javascript-string" }, { "code": null, "e": 35762, "s": 35755, "text": "Picked" }, { "code": null, "e": 35773, "s": 35762, "text": "JavaScript" }, { "code": null, "e": 35790, "s": 35773, "text": "Web Technologies" }, { "code": null, "e": 35817, "s": 35790, "text": "Web technologies Questions" }, { "code": null, "e": 35915, "s": 35817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35960, "s": 35915, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 36021, "s": 35960, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 36090, "s": 36021, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 36162, "s": 36090, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 36214, "s": 36162, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 36256, "s": 36214, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 36289, "s": 36256, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 36332, "s": 36289, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 36394, "s": 36332, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Functions Overview
In programming terms, a function is a block of statements that performs a specific task. Functions accept data, process it, and return a result. Functions are written primarily to support the concept of reusability. Once a function is written, it can be called easily, without having to write the same code again and again. Different functional languages use different syntax to write a function. Before writing a function, a programmer must know the following points − Purpose of function should be known to the programmer. Purpose of function should be known to the programmer. Algorithm of the function should be known to the programmer. Algorithm of the function should be known to the programmer. Functions data variables & their goal should be known to the programmer. Functions data variables & their goal should be known to the programmer. Function's data should be known to the programmer that is called by the user. Function's data should be known to the programmer that is called by the user. When a function is "called", the program "transfers" the control to execute the function and its "flow of control" is as below − The program reaches to the statement containing a "function call". The program reaches to the statement containing a "function call". The first line inside the function is executed. The first line inside the function is executed. All the statements inside the function are executed from top to bottom. All the statements inside the function are executed from top to bottom. When the function is executed successfully, the control goes back to the statement where it started from. When the function is executed successfully, the control goes back to the statement where it started from. Any data computed and returned by the function is used in place of the function in the original line of code. Any data computed and returned by the function is used in place of the function in the original line of code. The general syntax of a function looks as follows − returnType functionName(type1 argument1, type2 argument2, . . . ) { // function body } Let’s take an example to understand how a function can be defined in C++ which is an object-oriented programming language. The following code has a function that adds two numbers and provides its result as the output. #include <stdio.h> int addNum(int a, int b); // function prototype int main() { int sum; sum = addNum(5,6); // function call printf("sum = %d",sum); return 0; } int addNum (int a,int b) { // function definition int result; result = a + b; return result; // return statement } It will produce the following output − Sum = 11 Let’s see how the same function can be defined in Erlang, which is a functional programming language. -module(helloworld). -export([add/2,start/0]). add(A,B) -> C = A + B, io:fwrite("~w~n",[C]). start() -> add(5,6). It will produce the following output − 11 A function prototype is a declaration of the function that includes return-type, function-name & arguments-list. It is similar to function definition without function-body. For Example − Some programming languages supports function prototyping & some are not. In C++, we can make function prototype of function ‘sum’ like this − int sum(int a, int b) Note − Programming languages like Python, Erlang, etc doesn’t supports function prototyping, we need to declare the complete function. The function prototype is used by the compiler when the function is called. Compiler uses it to ensure correct return-type, proper arguments list are passed-in, & their return-type is correct. A function signature is similar to function prototype in which number of parameters, datatype of parameters & order of appearance should be in similar order. For Example − void Sum(int a, int b, int c); // function 1 void Sum(float a, float b, float c); // function 2 void Sum(float a, float b, float c); // function 3 Function1 and Function2 have different signatures. Function2 and Function3 have same signatures. Note − Function overloading and Function overriding which we will discuss in the subsequent chapters are based on the concept of function signatures. Function overloading is possible when a class has multiple functions with the same name but different signatures. Function overloading is possible when a class has multiple functions with the same name but different signatures. Function overriding is possible when a derived class function has the same name and signature as its base class. Function overriding is possible when a derived class function has the same name and signature as its base class. 32 Lectures 3.5 hours Pavan Lalwani 11 Lectures 1 hours Prof. Paul Cline, Ed.D 72 Lectures 10.5 hours Arun Ammasai 51 Lectures 2 hours Skillbakerystudios 43 Lectures 4 hours Mohammad Nauman 8 Lectures 1 hours Santharam Sivalenka Print Add Notes Bookmark this page
[ { "code": null, "e": 2145, "s": 1821, "text": "In programming terms, a function is a block of statements that performs a specific task. Functions accept data, process it, and return a result. Functions are written primarily to support the concept of reusability. Once a function is written, it can be called easily, without having to write the same code again and again." }, { "code": null, "e": 2218, "s": 2145, "text": "Different functional languages use different syntax to write a function." }, { "code": null, "e": 2291, "s": 2218, "text": "Before writing a function, a programmer must know the following points −" }, { "code": null, "e": 2346, "s": 2291, "text": "Purpose of function should be known to the programmer." }, { "code": null, "e": 2401, "s": 2346, "text": "Purpose of function should be known to the programmer." }, { "code": null, "e": 2462, "s": 2401, "text": "Algorithm of the function should be known to the programmer." }, { "code": null, "e": 2523, "s": 2462, "text": "Algorithm of the function should be known to the programmer." }, { "code": null, "e": 2596, "s": 2523, "text": "Functions data variables & their goal should be known to the programmer." }, { "code": null, "e": 2669, "s": 2596, "text": "Functions data variables & their goal should be known to the programmer." }, { "code": null, "e": 2747, "s": 2669, "text": "Function's data should be known to the programmer that is called by the user." }, { "code": null, "e": 2825, "s": 2747, "text": "Function's data should be known to the programmer that is called by the user." }, { "code": null, "e": 2954, "s": 2825, "text": "When a function is \"called\", the program \"transfers\" the control to execute the function and its \"flow of control\" is as below −" }, { "code": null, "e": 3021, "s": 2954, "text": "The program reaches to the statement containing a \"function call\"." }, { "code": null, "e": 3088, "s": 3021, "text": "The program reaches to the statement containing a \"function call\"." }, { "code": null, "e": 3136, "s": 3088, "text": "The first line inside the function is executed." }, { "code": null, "e": 3184, "s": 3136, "text": "The first line inside the function is executed." }, { "code": null, "e": 3256, "s": 3184, "text": "All the statements inside the function are executed from top to bottom." }, { "code": null, "e": 3328, "s": 3256, "text": "All the statements inside the function are executed from top to bottom." }, { "code": null, "e": 3434, "s": 3328, "text": "When the function is executed successfully, the control goes back to the statement where it started from." }, { "code": null, "e": 3540, "s": 3434, "text": "When the function is executed successfully, the control goes back to the statement where it started from." }, { "code": null, "e": 3650, "s": 3540, "text": "Any data computed and returned by the function is used in place of the function in the original line of code." }, { "code": null, "e": 3760, "s": 3650, "text": "Any data computed and returned by the function is used in place of the function in the original line of code." }, { "code": null, "e": 3812, "s": 3760, "text": "The general syntax of a function looks as follows −" }, { "code": null, "e": 3910, "s": 3812, "text": "returnType functionName(type1 argument1, type2 argument2, . . . ) { \n // function body \n} \n" }, { "code": null, "e": 4128, "s": 3910, "text": "Let’s take an example to understand how a function can be defined in C++ which is an object-oriented programming language. The following code has a function that adds two numbers and provides its result as the output." }, { "code": null, "e": 4477, "s": 4128, "text": "#include <stdio.h> \n\nint addNum(int a, int b); // function prototype \n\nint main() { \n int sum; \n sum = addNum(5,6); // function call \n printf(\"sum = %d\",sum); \n return 0; \n} \nint addNum (int a,int b) { // function definition \n int result; \n result = a + b; \n return result; // return statement \n} " }, { "code": null, "e": 4516, "s": 4477, "text": "It will produce the following output −" }, { "code": null, "e": 4526, "s": 4516, "text": "Sum = 11\n" }, { "code": null, "e": 4628, "s": 4526, "text": "Let’s see how the same function can be defined in Erlang, which is a functional programming language." }, { "code": null, "e": 4764, "s": 4628, "text": "-module(helloworld). \n-export([add/2,start/0]). \n\nadd(A,B) ->\n C = A + B, \n io:fwrite(\"~w~n\",[C]). \nstart() -> \n add(5,6). " }, { "code": null, "e": 4803, "s": 4764, "text": "It will produce the following output −" }, { "code": null, "e": 4807, "s": 4803, "text": "11\n" }, { "code": null, "e": 4980, "s": 4807, "text": "A function prototype is a declaration of the function that includes return-type, function-name & arguments-list. It is similar to function definition without function-body." }, { "code": null, "e": 5067, "s": 4980, "text": "For Example − Some programming languages supports function prototyping & some are not." }, { "code": null, "e": 5136, "s": 5067, "text": "In C++, we can make function prototype of function ‘sum’ like this −" }, { "code": null, "e": 5160, "s": 5136, "text": "int sum(int a, int b) \n" }, { "code": null, "e": 5295, "s": 5160, "text": "Note − Programming languages like Python, Erlang, etc doesn’t supports function prototyping, we need to declare the complete function." }, { "code": null, "e": 5488, "s": 5295, "text": "The function prototype is used by the compiler when the function is called. Compiler uses it to ensure correct return-type, proper arguments list are passed-in, & their return-type is correct." }, { "code": null, "e": 5660, "s": 5488, "text": "A function signature is similar to function prototype in which number of parameters, datatype of parameters & order of appearance should be in similar order. For Example −" }, { "code": null, "e": 5825, "s": 5660, "text": "void Sum(int a, int b, int c); // function 1 \nvoid Sum(float a, float b, float c); // function 2 \nvoid Sum(float a, float b, float c); // function 3 \n" }, { "code": null, "e": 5922, "s": 5825, "text": "Function1 and Function2 have different signatures. Function2 and Function3 have same signatures." }, { "code": null, "e": 6072, "s": 5922, "text": "Note − Function overloading and Function overriding which we will discuss in the subsequent chapters are based on the concept of function signatures." }, { "code": null, "e": 6186, "s": 6072, "text": "Function overloading is possible when a class has multiple functions with the same name but different signatures." }, { "code": null, "e": 6300, "s": 6186, "text": "Function overloading is possible when a class has multiple functions with the same name but different signatures." }, { "code": null, "e": 6413, "s": 6300, "text": "Function overriding is possible when a derived class function has the same name and signature as its base class." }, { "code": null, "e": 6526, "s": 6413, "text": "Function overriding is possible when a derived class function has the same name and signature as its base class." }, { "code": null, "e": 6561, "s": 6526, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6576, "s": 6561, "text": " Pavan Lalwani" }, { "code": null, "e": 6609, "s": 6576, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 6633, "s": 6609, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 6669, "s": 6633, "text": "\n 72 Lectures \n 10.5 hours \n" }, { "code": null, "e": 6683, "s": 6669, "text": " Arun Ammasai" }, { "code": null, "e": 6716, "s": 6683, "text": "\n 51 Lectures \n 2 hours \n" }, { "code": null, "e": 6736, "s": 6716, "text": " Skillbakerystudios" }, { "code": null, "e": 6769, "s": 6736, "text": "\n 43 Lectures \n 4 hours \n" }, { "code": null, "e": 6786, "s": 6769, "text": " Mohammad Nauman" }, { "code": null, "e": 6818, "s": 6786, "text": "\n 8 Lectures \n 1 hours \n" }, { "code": null, "e": 6839, "s": 6818, "text": " Santharam Sivalenka" }, { "code": null, "e": 6846, "s": 6839, "text": " Print" }, { "code": null, "e": 6857, "s": 6846, "text": " Add Notes" } ]
PyQt - QLineEdit Widget
QLineEdit object is the most commonly used input field. It provides a box in which one line of text can be entered. In order to enter multi-line text, QTextEdit object is required. The following table lists a few important methods of QLineEdit class − Given below are the most commonly used methods of QLineEdit. setAlignment() Aligns the text as per alignment constants Qt.AlignLeft Qt.AlignRight Qt.AlignCenter Qt.AlignJustify clear() Erases the contents setEchoMode() Controls the appearance of the text inside the box. Echomode values are − QLineEdit.Normal QLineEdit.NoEcho QLineEdit.Password QLineEdit.PasswordEchoOnEdit setMaxLength() Sets the maximum number of characters for input setReadOnly() Makes the text box non-editable setText() Programmatically sets the text text() Retrieves text in the field setValidator() Sets the validation rules. Available validators are QIntValidator − Restricts input to integer QDoubleValidator − Fraction part of number limited to specified decimals QRegexpValidator − Checks input against a Regex expression setInputMask() Applies mask of combination of characters for input setFont() Displays the contents QFont object QLineEdit object emits the following signals − Given below are the most commonly used methods of signals. cursorPositionChanged() Whenever the cursor moves editingFinished() When you press ‘Enter’ or the field loses focus returnPressed() When you press ‘Enter’ selectionChanged() Whenever the selected text changes textChanged() As text in the box changes either by input or by programmatic means textEdited() Whenever the text is edited QLineEdit objects in this example demonstrate use of some of these methods. First field e1 shows text using a custom font, in right alignment and allows integer input. Second field restricts input to a number with 2 digits after decimal point. An input mask for entering the phone number is applied on the third field. textChanged() signal on the field e4 is connected to textchanged() slot method. Contents of e5 field are echoed in password form as its EchoMode property is set to Password. Its editingfinished() signal is connected to presenter() method. So, once the user presses the Enter key, the function will be executed. The field e6 shows a default text, which cannot be edited as it is set to read only. import sys from PyQt4.QtCore import * from PyQt4.QtGui import * def window(): app = QApplication(sys.argv) win = QWidget() e1 = QLineEdit() e1.setValidator(QIntValidator()) e1.setMaxLength(4) e1.setAlignment(Qt.AlignRight) e1.setFont(QFont("Arial",20)) e2 = QLineEdit() e2.setValidator(QDoubleValidator(0.99,99.99,2)) flo = QFormLayout() flo.addRow("integer validator", e1) flo.addRow("Double validator",e2) e3 = QLineEdit() e3.setInputMask('+99_9999_999999') flo.addRow("Input Mask",e3) e4 = QLineEdit() e4.textChanged.connect(textchanged) flo.addRow("Text changed",e4) e5 = QLineEdit() e5.setEchoMode(QLineEdit.Password) flo.addRow("Password",e5) e6 = QLineEdit("Hello Python") e6.setReadOnly(True) flo.addRow("Read Only",e6) e5.editingFinished.connect(enterPress) win.setLayout(flo) win.setWindowTitle("PyQt") win.show() sys.exit(app.exec_()) def textchanged(text): print "contents of text box: "+text def enterPress(): print "edited" if __name__ == '__main__': window() The above code produces the following output − contents of text box: h contents of text box: he contents of text box: hel contents of text box: hell contents of text box: hello editing finished 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2107, "s": 1926, "text": "QLineEdit object is the most commonly used input field. It provides a box in which one line of text can be entered. In order to enter multi-line text, QTextEdit object is required." }, { "code": null, "e": 2178, "s": 2107, "text": "The following table lists a few important methods of QLineEdit class −" }, { "code": null, "e": 2239, "s": 2178, "text": "Given below are the most commonly used methods of QLineEdit." }, { "code": null, "e": 2254, "s": 2239, "text": "setAlignment()" }, { "code": null, "e": 2297, "s": 2254, "text": "Aligns the text as per alignment constants" }, { "code": null, "e": 2310, "s": 2297, "text": "Qt.AlignLeft" }, { "code": null, "e": 2324, "s": 2310, "text": "Qt.AlignRight" }, { "code": null, "e": 2339, "s": 2324, "text": "Qt.AlignCenter" }, { "code": null, "e": 2355, "s": 2339, "text": "Qt.AlignJustify" }, { "code": null, "e": 2363, "s": 2355, "text": "clear()" }, { "code": null, "e": 2383, "s": 2363, "text": "Erases the contents" }, { "code": null, "e": 2397, "s": 2383, "text": "setEchoMode()" }, { "code": null, "e": 2471, "s": 2397, "text": "Controls the appearance of the text inside the box. Echomode values are −" }, { "code": null, "e": 2488, "s": 2471, "text": "QLineEdit.Normal" }, { "code": null, "e": 2505, "s": 2488, "text": "QLineEdit.NoEcho" }, { "code": null, "e": 2524, "s": 2505, "text": "QLineEdit.Password" }, { "code": null, "e": 2553, "s": 2524, "text": "QLineEdit.PasswordEchoOnEdit" }, { "code": null, "e": 2568, "s": 2553, "text": "setMaxLength()" }, { "code": null, "e": 2616, "s": 2568, "text": "Sets the maximum number of characters for input" }, { "code": null, "e": 2630, "s": 2616, "text": "setReadOnly()" }, { "code": null, "e": 2662, "s": 2630, "text": "Makes the text box non-editable" }, { "code": null, "e": 2672, "s": 2662, "text": "setText()" }, { "code": null, "e": 2703, "s": 2672, "text": "Programmatically sets the text" }, { "code": null, "e": 2710, "s": 2703, "text": "text()" }, { "code": null, "e": 2738, "s": 2710, "text": "Retrieves text in the field" }, { "code": null, "e": 2753, "s": 2738, "text": "setValidator()" }, { "code": null, "e": 2805, "s": 2753, "text": "Sets the validation rules. Available validators are" }, { "code": null, "e": 2848, "s": 2805, "text": "QIntValidator − Restricts input to integer" }, { "code": null, "e": 2921, "s": 2848, "text": "QDoubleValidator − Fraction part of number limited to specified decimals" }, { "code": null, "e": 2980, "s": 2921, "text": "QRegexpValidator − Checks input against a Regex expression" }, { "code": null, "e": 2995, "s": 2980, "text": "setInputMask()" }, { "code": null, "e": 3047, "s": 2995, "text": "Applies mask of combination of characters for input" }, { "code": null, "e": 3057, "s": 3047, "text": "setFont()" }, { "code": null, "e": 3092, "s": 3057, "text": "Displays the contents QFont object" }, { "code": null, "e": 3139, "s": 3092, "text": "QLineEdit object emits the following signals −" }, { "code": null, "e": 3198, "s": 3139, "text": "Given below are the most commonly used methods of signals." }, { "code": null, "e": 3222, "s": 3198, "text": "cursorPositionChanged()" }, { "code": null, "e": 3248, "s": 3222, "text": "Whenever the cursor moves" }, { "code": null, "e": 3266, "s": 3248, "text": "editingFinished()" }, { "code": null, "e": 3314, "s": 3266, "text": "When you press ‘Enter’ or the field loses focus" }, { "code": null, "e": 3330, "s": 3314, "text": "returnPressed()" }, { "code": null, "e": 3353, "s": 3330, "text": "When you press ‘Enter’" }, { "code": null, "e": 3372, "s": 3353, "text": "selectionChanged()" }, { "code": null, "e": 3407, "s": 3372, "text": "Whenever the selected text changes" }, { "code": null, "e": 3421, "s": 3407, "text": "textChanged()" }, { "code": null, "e": 3489, "s": 3421, "text": "As text in the box changes either by input or by programmatic means" }, { "code": null, "e": 3502, "s": 3489, "text": "textEdited()" }, { "code": null, "e": 3530, "s": 3502, "text": "Whenever the text is edited" }, { "code": null, "e": 3606, "s": 3530, "text": "QLineEdit objects in this example demonstrate use of some of these methods." }, { "code": null, "e": 3929, "s": 3606, "text": "First field e1 shows text using a custom font, in right alignment and allows integer input. Second field restricts input to a number with 2 digits after decimal point. An input mask for entering the phone number is applied on the third field. textChanged() signal on the field e4 is connected to textchanged() slot method." }, { "code": null, "e": 4245, "s": 3929, "text": "Contents of e5 field are echoed in password form as its EchoMode property is set to Password. Its editingfinished() signal is connected to presenter() method. So, once the user presses the Enter key, the function will be executed. The field e6 shows a default text, which cannot be edited as it is set to read only." }, { "code": null, "e": 5338, "s": 4245, "text": "import sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\ndef window():\n app = QApplication(sys.argv)\n win = QWidget()\n\t\n e1 = QLineEdit()\n e1.setValidator(QIntValidator())\n e1.setMaxLength(4)\n e1.setAlignment(Qt.AlignRight)\n e1.setFont(QFont(\"Arial\",20))\n\t\n e2 = QLineEdit()\n e2.setValidator(QDoubleValidator(0.99,99.99,2))\n\t\n flo = QFormLayout()\n flo.addRow(\"integer validator\", e1)\n flo.addRow(\"Double validator\",e2)\n\t\n e3 = QLineEdit()\n e3.setInputMask('+99_9999_999999')\n flo.addRow(\"Input Mask\",e3)\n\t\n e4 = QLineEdit()\n e4.textChanged.connect(textchanged)\n flo.addRow(\"Text changed\",e4)\n\t\n e5 = QLineEdit()\n e5.setEchoMode(QLineEdit.Password)\n flo.addRow(\"Password\",e5)\n\t\n e6 = QLineEdit(\"Hello Python\")\n e6.setReadOnly(True)\n flo.addRow(\"Read Only\",e6)\n\t\n e5.editingFinished.connect(enterPress)\n win.setLayout(flo)\n win.setWindowTitle(\"PyQt\")\n win.show()\n\t\n sys.exit(app.exec_())\n\ndef textchanged(text):\n print \"contents of text box: \"+text\n\t\ndef enterPress():\n print \"edited\"\n\nif __name__ == '__main__':\n window()" }, { "code": null, "e": 5385, "s": 5338, "text": "The above code produces the following output −" }, { "code": null, "e": 5533, "s": 5385, "text": "contents of text box: h\ncontents of text box: he\ncontents of text box: hel\ncontents of text box: hell\ncontents of text box: hello\nediting finished\n" }, { "code": null, "e": 5570, "s": 5533, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 5580, "s": 5570, "text": " ALAA EID" }, { "code": null, "e": 5587, "s": 5580, "text": " Print" }, { "code": null, "e": 5598, "s": 5587, "text": " Add Notes" } ]
Deep Q-Learning - GeeksforGeeks
18 Jun, 2019 Prerequisites: Q-Learning The process of Q-Learning creates an exact matrix for the working agent which it can “refer to” to maximize its reward in the long run. Although this approach is not wrong in itself, this is only practical for very small environments and quickly loses it’s feasibility when the number of states and actions in the environment increases. The solution for the above problem comes from the realization that the values in the matrix only have relative importance ie the values only have importance with respect to the other values. Thus, this thinking leads us to Deep Q-Learning which uses a deep neural network to approximate the values. This approximation of values does not hurt as long as the relative importance is preserved. The basic working step for Deep Q-Learning is that the initial state is fed into the neural network and it returns the Q-value of all possible actions as on output. The difference between Q-Learning and Deep Q-Learning can be illustrated as follows:- Pseudo Code: Initialize for all pairs (s,a) s = initial state k = 0 while(convergence is not achieved) { simulate action a and reach state s' if(s' is a terminal state) { target = R(s,a,s') } else { target = R(s,a,s') + } s = s' } Observe that in the equation target = R(s,a,s’) + , the term is a variable term. Therefore in this process, the target for the neural network is variable unlike other typical Deep Learning processes where the target is stationary. This problem is overcome by having two neural networks instead of one. One neural network is used to adjust the parameters of the network and the other is used for computing the target and which has the same architecture as the first network but has frozen parameters. After an x number of iterations in the primary network, the parameters are copied to the target network. Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Python | Decision tree implementation Search Algorithms in AI Decision Tree Introduction with example ML | Underfitting and Overfitting 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": 24220, "s": 24192, "text": "\n18 Jun, 2019" }, { "code": null, "e": 24246, "s": 24220, "text": "Prerequisites: Q-Learning" }, { "code": null, "e": 24583, "s": 24246, "text": "The process of Q-Learning creates an exact matrix for the working agent which it can “refer to” to maximize its reward in the long run. Although this approach is not wrong in itself, this is only practical for very small environments and quickly loses it’s feasibility when the number of states and actions in the environment increases." }, { "code": null, "e": 24974, "s": 24583, "text": "The solution for the above problem comes from the realization that the values in the matrix only have relative importance ie the values only have importance with respect to the other values. Thus, this thinking leads us to Deep Q-Learning which uses a deep neural network to approximate the values. This approximation of values does not hurt as long as the relative importance is preserved." }, { "code": null, "e": 25139, "s": 24974, "text": "The basic working step for Deep Q-Learning is that the initial state is fed into the neural network and it returns the Q-value of all possible actions as on output." }, { "code": null, "e": 25225, "s": 25139, "text": "The difference between Q-Learning and Deep Q-Learning can be illustrated as follows:-" }, { "code": null, "e": 25238, "s": 25225, "text": "Pseudo Code:" }, { "code": null, "e": 25512, "s": 25238, "text": "Initialize for all pairs (s,a)\ns = initial state\nk = 0\nwhile(convergence is not achieved)\n{\n simulate action a and reach state s'\n if(s' is a terminal state)\n {\n target = R(s,a,s')\n }\n else\n {\n target = R(s,a,s') + \n }\n \n s = s'\n}\n" }, { "code": null, "e": 25743, "s": 25512, "text": "Observe that in the equation target = R(s,a,s’) + , the term is a variable term. Therefore in this process, the target for the neural network is variable unlike other typical Deep Learning processes where the target is stationary." }, { "code": null, "e": 26117, "s": 25743, "text": "This problem is overcome by having two neural networks instead of one. One neural network is used to adjust the parameters of the network and the other is used for computing the target and which has the same architecture as the first network but has frozen parameters. After an x number of iterations in the primary network, the parameters are copied to the target network." }, { "code": null, "e": 26134, "s": 26117, "text": "Machine Learning" }, { "code": null, "e": 26141, "s": 26134, "text": "Python" }, { "code": null, "e": 26158, "s": 26141, "text": "Machine Learning" }, { "code": null, "e": 26256, "s": 26158, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26270, "s": 26256, "text": "Decision Tree" }, { "code": null, "e": 26308, "s": 26270, "text": "Python | Decision tree implementation" }, { "code": null, "e": 26332, "s": 26308, "text": "Search Algorithms in AI" }, { "code": null, "e": 26372, "s": 26332, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 26406, "s": 26372, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 26434, "s": 26406, "text": "Read JSON file using Python" }, { "code": null, "e": 26484, "s": 26434, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26506, "s": 26484, "text": "Python map() function" } ]
C++ Program for Common Divisors of Two Numbers - GeeksforGeeks
04 Dec, 2018 Given two integer numbers, the task is to find the count of all common divisors of given numbers. Input : a = 12, b = 24 Output: 6 // all common divisors are 1, 2, 3, // 4, 6 and 12 Input : a = 3, b = 17 Output: 1 // all common divisors are 1 Input : a = 20, b = 36 Output: 3 // all common divisors are 1, 2, 4 // C++ implementation of program#include <bits/stdc++.h>using namespace std; // Function to calculate gcd of two numbersint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to calculate all common divisors// of two given numbers// a, b --> input integer numbersint commDiv(int a, int b){ // find gcd of a, b int n = gcd(a, b); // Count divisors of n. int result = 0; for (int i = 1; i <= sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) result += 1; else result += 2; } } return result;} // Driver program to run the caseint main(){ int a = 12, b = 24; cout << commDiv(a, b); return 0;} 6 Please refer complete article on Common Divisors of Two Numbers for more details! divisors GCD-LCM C++ Programs Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Dynamic _Cast in C++ 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": 24632, "s": 24604, "text": "\n04 Dec, 2018" }, { "code": null, "e": 24730, "s": 24632, "text": "Given two integer numbers, the task is to find the count of all common divisors of given numbers." }, { "code": null, "e": 24947, "s": 24730, "text": "Input : a = 12, b = 24\nOutput: 6\n// all common divisors are 1, 2, 3, \n// 4, 6 and 12\n\nInput : a = 3, b = 17\nOutput: 1\n// all common divisors are 1\n\nInput : a = 20, b = 36\nOutput: 3\n// all common divisors are 1, 2, 4\n" }, { "code": "// C++ implementation of program#include <bits/stdc++.h>using namespace std; // Function to calculate gcd of two numbersint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to calculate all common divisors// of two given numbers// a, b --> input integer numbersint commDiv(int a, int b){ // find gcd of a, b int n = gcd(a, b); // Count divisors of n. int result = 0; for (int i = 1; i <= sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) result += 1; else result += 2; } } return result;} // Driver program to run the caseint main(){ int a = 12, b = 24; cout << commDiv(a, b); return 0;}", "e": 25750, "s": 24947, "text": null }, { "code": null, "e": 25753, "s": 25750, "text": "6\n" }, { "code": null, "e": 25835, "s": 25753, "text": "Please refer complete article on Common Divisors of Two Numbers for more details!" }, { "code": null, "e": 25844, "s": 25835, "text": "divisors" }, { "code": null, "e": 25852, "s": 25844, "text": "GCD-LCM" }, { "code": null, "e": 25865, "s": 25852, "text": "C++ Programs" }, { "code": null, "e": 25878, "s": 25865, "text": "Mathematical" }, { "code": null, "e": 25891, "s": 25878, "text": "Mathematical" }, { "code": null, "e": 25989, "s": 25891, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26030, "s": 25989, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 26089, "s": 26030, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 26110, "s": 26089, "text": "Const keyword in C++" }, { "code": null, "e": 26122, "s": 26110, "text": "cout in C++" }, { "code": null, "e": 26143, "s": 26122, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 26173, "s": 26143, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 26233, "s": 26173, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 26248, "s": 26233, "text": "C++ Data Types" }, { "code": null, "e": 26291, "s": 26248, "text": "Set in C++ Standard Template Library (STL)" } ]
Best Simple Python Projects for Beginners | Towards Data Science
Hello readers, in this story, let’s talk about making some fun Python Projects to have a better understanding of Python and to have some fun playing with Python and its amazing libraries. These projects are small and you can easily do these within 1–2 hours. These will help you understand Python and its various libraries in a better way. These are beginner-friendly so everyone should try his/her hands on these projects. So, without further ado, let’s dive into the projects one by one. This is one of the very simple python projects for you to do but is an interesting one to try. It makes use of the Google Text to Speech API of Python, so we need to import the library first using the command below: pip install gTTS Now, after we have installed the required libraries, we can build our python program to convert text to speech. If we want to listen to the audio within our program, we can import the os library in the python code. So, let’s write the code for the program. Below is the required code: #importing the gTTS libraryfrom gtts import gTTS#Asking the user for the required textmt = input("Enter the required text:\t")#Setting the output languagelanguage = ‘en’#Converting text to speech and choosing speed as fastvoice = gTTS(text=mt, lang=language, slow=False)#Saving the speech as mp3 filevoice.save(“conv.mp3”) So, in this way, you can very easily make a text to speech conversion using Python. The file will be saved in the same folder where you are executing this python code (the current working folder). You can make this better in many ways like you can extract text from a pdf and then convert it to speech for reading out a pdf completely. You can also extract text from images and then do the same stuff. So, let’s move to our second simple Python project. You can easily extract text from images. We will be using Open CV and pytesseract library. We need to install both openCV and pytesseract libraries first. To do so, we will use the following command to install openCV in the system. pip install opencv-python To install pytesseract, we need to perform more tasks. It’s the toughest part of the tutorial. First of all, we need to use the following command: pip install pytesseract Then, we need to download the following file and install it in our system. Download the most suitable file for your system from here. After doing all of this stuff, we are good to go with the final code of our program. #Importing the librariesimport cv2import pytesseractpytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'#Opening the image with open-cvimage = cv2.imread('pic.png')#Extracting text from imagest = pytesseract.image_to_string(image)#Printing the textprint(st) So, we have made our text from image extractor easily with the help of pytesseract library. It has high accuracy in detecting the text from the images. So, with relatively simple code, we have made a high accuracy text from image extractor. We can do a lot of stuff with PDFs using Python. We can convert it into text, slice the PDF, merge PDFs, add watermarks and much more. So, let’s write a simple Python Code to perform all such cool stuff on PDFs using Python. We will be using the PyPDF2 library for performing the operations on PDFs. This library helps us to gain all those powers to do so. So, let’s install this library by using the following command: pip install PyPDF2 This command will install the required packages into your system. Now, we are ready to write our Python Code. So, first, let’s import the package and load the required pdf. #Importing the packageimport PyPDF2#Loading the PDF filepdffile = open('first.pdf', 'rb')#Reader object to read PDFsReader = PyPDF2.PdfFileReader(pdffile) Now, let’s extract some information from the PDF. #Display the number of pagesprint(Reader.numPages)#Getting a page by page numberpage = Reader.getPage(1)#Extracting text from the pageprint(page.extractText()) We can also merge PDF files, rotate the pages in PDF file, split PDFs into multiple parts and many more such things. But, we can not cover all of these here. For more information on this library and its usages, visit PyPDF2 here. There is an amazing API which will help us translate from one language to the other. This is the Google Translate API. We will need to install goslate in our system to run the Python code needed to perform the translation. pip install goslate Now, let’s delve into the actual Python Code. We can translate to many languages which all are supported by Google Translate API. We will be taking the input from the user as a string but we can also take input as a form of a text file, convert into a string and perform the operation on it. Also, we can make a real-time translator in which we can speak out and the code will convert the language. This will require some more digging in the topic, so we will leave it for some other day. For now, we will be building a simple language translator. #Importing the library packageimport goslate#Taking input from usertext = input("Enter the text:\t")#Calling the goslate functiongs = goslate.Goslate()#Translating the text to our preferred languagetrans = gs.translate(text,'hi')#Displaying the outputprint(trans) So, the above code does the required work for us. It takes an English sentence and translates into Hindi. You can choose any language of your choice. So, with the above four Python Projects, I hope you learnt something and will make better versions of these simple projects with much more options and in-depth analysis. Take these projects as starter codes and use them to build better projects. You can also create many more Python projects once you develop the right skills. So, keep practising and keep going forward. After you have finished reading this one, I would like to suggest a few more great stories to read which offers good knowledge and helps you learn new things. shubhamstudent5.medium.com medium.com medium.com shubhamstudent5.medium.com towardsdatascience.com Thanks for reading the article. I hope you liked the article.
[ { "code": null, "e": 359, "s": 171, "text": "Hello readers, in this story, let’s talk about making some fun Python Projects to have a better understanding of Python and to have some fun playing with Python and its amazing libraries." }, { "code": null, "e": 595, "s": 359, "text": "These projects are small and you can easily do these within 1–2 hours. These will help you understand Python and its various libraries in a better way. These are beginner-friendly so everyone should try his/her hands on these projects." }, { "code": null, "e": 661, "s": 595, "text": "So, without further ado, let’s dive into the projects one by one." }, { "code": null, "e": 877, "s": 661, "text": "This is one of the very simple python projects for you to do but is an interesting one to try. It makes use of the Google Text to Speech API of Python, so we need to import the library first using the command below:" }, { "code": null, "e": 894, "s": 877, "text": "pip install gTTS" }, { "code": null, "e": 1006, "s": 894, "text": "Now, after we have installed the required libraries, we can build our python program to convert text to speech." }, { "code": null, "e": 1109, "s": 1006, "text": "If we want to listen to the audio within our program, we can import the os library in the python code." }, { "code": null, "e": 1179, "s": 1109, "text": "So, let’s write the code for the program. Below is the required code:" }, { "code": null, "e": 1502, "s": 1179, "text": "#importing the gTTS libraryfrom gtts import gTTS#Asking the user for the required textmt = input(\"Enter the required text:\\t\")#Setting the output languagelanguage = ‘en’#Converting text to speech and choosing speed as fastvoice = gTTS(text=mt, lang=language, slow=False)#Saving the speech as mp3 filevoice.save(“conv.mp3”)" }, { "code": null, "e": 1699, "s": 1502, "text": "So, in this way, you can very easily make a text to speech conversion using Python. The file will be saved in the same folder where you are executing this python code (the current working folder)." }, { "code": null, "e": 1904, "s": 1699, "text": "You can make this better in many ways like you can extract text from a pdf and then convert it to speech for reading out a pdf completely. You can also extract text from images and then do the same stuff." }, { "code": null, "e": 1956, "s": 1904, "text": "So, let’s move to our second simple Python project." }, { "code": null, "e": 2047, "s": 1956, "text": "You can easily extract text from images. We will be using Open CV and pytesseract library." }, { "code": null, "e": 2188, "s": 2047, "text": "We need to install both openCV and pytesseract libraries first. To do so, we will use the following command to install openCV in the system." }, { "code": null, "e": 2214, "s": 2188, "text": "pip install opencv-python" }, { "code": null, "e": 2309, "s": 2214, "text": "To install pytesseract, we need to perform more tasks. It’s the toughest part of the tutorial." }, { "code": null, "e": 2361, "s": 2309, "text": "First of all, we need to use the following command:" }, { "code": null, "e": 2385, "s": 2361, "text": "pip install pytesseract" }, { "code": null, "e": 2519, "s": 2385, "text": "Then, we need to download the following file and install it in our system. Download the most suitable file for your system from here." }, { "code": null, "e": 2604, "s": 2519, "text": "After doing all of this stuff, we are good to go with the final code of our program." }, { "code": null, "e": 2900, "s": 2604, "text": "#Importing the librariesimport cv2import pytesseractpytesseract.pytesseract.tesseract_cmd = r'C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe'#Opening the image with open-cvimage = cv2.imread('pic.png')#Extracting text from imagest = pytesseract.image_to_string(image)#Printing the textprint(st)" }, { "code": null, "e": 2992, "s": 2900, "text": "So, we have made our text from image extractor easily with the help of pytesseract library." }, { "code": null, "e": 3141, "s": 2992, "text": "It has high accuracy in detecting the text from the images. So, with relatively simple code, we have made a high accuracy text from image extractor." }, { "code": null, "e": 3366, "s": 3141, "text": "We can do a lot of stuff with PDFs using Python. We can convert it into text, slice the PDF, merge PDFs, add watermarks and much more. So, let’s write a simple Python Code to perform all such cool stuff on PDFs using Python." }, { "code": null, "e": 3498, "s": 3366, "text": "We will be using the PyPDF2 library for performing the operations on PDFs. This library helps us to gain all those powers to do so." }, { "code": null, "e": 3561, "s": 3498, "text": "So, let’s install this library by using the following command:" }, { "code": null, "e": 3580, "s": 3561, "text": "pip install PyPDF2" }, { "code": null, "e": 3690, "s": 3580, "text": "This command will install the required packages into your system. Now, we are ready to write our Python Code." }, { "code": null, "e": 3753, "s": 3690, "text": "So, first, let’s import the package and load the required pdf." }, { "code": null, "e": 3908, "s": 3753, "text": "#Importing the packageimport PyPDF2#Loading the PDF filepdffile = open('first.pdf', 'rb')#Reader object to read PDFsReader = PyPDF2.PdfFileReader(pdffile)" }, { "code": null, "e": 3958, "s": 3908, "text": "Now, let’s extract some information from the PDF." }, { "code": null, "e": 4118, "s": 3958, "text": "#Display the number of pagesprint(Reader.numPages)#Getting a page by page numberpage = Reader.getPage(1)#Extracting text from the pageprint(page.extractText())" }, { "code": null, "e": 4276, "s": 4118, "text": "We can also merge PDF files, rotate the pages in PDF file, split PDFs into multiple parts and many more such things. But, we can not cover all of these here." }, { "code": null, "e": 4348, "s": 4276, "text": "For more information on this library and its usages, visit PyPDF2 here." }, { "code": null, "e": 4571, "s": 4348, "text": "There is an amazing API which will help us translate from one language to the other. This is the Google Translate API. We will need to install goslate in our system to run the Python code needed to perform the translation." }, { "code": null, "e": 4591, "s": 4571, "text": "pip install goslate" }, { "code": null, "e": 4883, "s": 4591, "text": "Now, let’s delve into the actual Python Code. We can translate to many languages which all are supported by Google Translate API. We will be taking the input from the user as a string but we can also take input as a form of a text file, convert into a string and perform the operation on it." }, { "code": null, "e": 5080, "s": 4883, "text": "Also, we can make a real-time translator in which we can speak out and the code will convert the language. This will require some more digging in the topic, so we will leave it for some other day." }, { "code": null, "e": 5139, "s": 5080, "text": "For now, we will be building a simple language translator." }, { "code": null, "e": 5403, "s": 5139, "text": "#Importing the library packageimport goslate#Taking input from usertext = input(\"Enter the text:\\t\")#Calling the goslate functiongs = goslate.Goslate()#Translating the text to our preferred languagetrans = gs.translate(text,'hi')#Displaying the outputprint(trans)" }, { "code": null, "e": 5553, "s": 5403, "text": "So, the above code does the required work for us. It takes an English sentence and translates into Hindi. You can choose any language of your choice." }, { "code": null, "e": 5723, "s": 5553, "text": "So, with the above four Python Projects, I hope you learnt something and will make better versions of these simple projects with much more options and in-depth analysis." }, { "code": null, "e": 5924, "s": 5723, "text": "Take these projects as starter codes and use them to build better projects. You can also create many more Python projects once you develop the right skills. So, keep practising and keep going forward." }, { "code": null, "e": 6083, "s": 5924, "text": "After you have finished reading this one, I would like to suggest a few more great stories to read which offers good knowledge and helps you learn new things." }, { "code": null, "e": 6110, "s": 6083, "text": "shubhamstudent5.medium.com" }, { "code": null, "e": 6121, "s": 6110, "text": "medium.com" }, { "code": null, "e": 6132, "s": 6121, "text": "medium.com" }, { "code": null, "e": 6159, "s": 6132, "text": "shubhamstudent5.medium.com" }, { "code": null, "e": 6182, "s": 6159, "text": "towardsdatascience.com" } ]
Teradata - Views
Views are database objects that are built by the query. Views can be built using a single table or multiple tables by way of join. Their definition is stored permanently in data dictionary but they don't store copy of the data. Data for the view is built dynamically. A view may contain a subset of rows of the table or a subset of columns of the table. Views are created using CREATE VIEW statement. Following is the syntax for creating a view. CREATE/REPLACE VIEW <viewname> AS <select query>; Consider the following Employee table. The following example creates a view on Employee table. CREATE VIEW Employee_View AS SELECT EmployeeNo, FirstName, LastName, FROM Employee; You can use regular SELECT statement to retrieve data from Views. The following example retrieves the records from Employee_View; SELECT EmployeeNo, FirstName, LastName FROM Employee_View; When the above query is executed, it produces the following output. *** Query completed. 5 rows found. 3 columns returned. *** Total elapsed time was 1 second. EmployeeNo FirstName LastName ----------- ------------------------------ --------------------------- 101 Mike James 104 Alex Stuart 102 Robert Williams 105 Robert James 103 Peter Paul An existing view can be modified using REPLACE VIEW statement. Following is the syntax to modify a view. REPLACE VIEW <viewname> AS <select query>; The following example modifies the view Employee_View for adding additional columns. REPLACE VIEW Employee_View AS SELECT EmployeeNo, FirstName, BirthDate, JoinedDate DepartmentNo FROM Employee; An existing view can be dropped using DROP VIEW statement. Following is the syntax of DROP VIEW. DROP VIEW <viewname>; Following is an example to drop the view Employee_View. DROP VIEW Employee_View; Views provide additional level of security by restricting the rows or columns of a table. Views provide additional level of security by restricting the rows or columns of a table. Users can be given access only to views instead of base tables. Users can be given access only to views instead of base tables. Simplifies the use of multiple tables by pre-joining them using Views. Simplifies the use of multiple tables by pre-joining them using Views. Print Add Notes Bookmark this page
[ { "code": null, "e": 2898, "s": 2630, "text": "Views are database objects that are built by the query. Views can be built using a single table or multiple tables by way of join. Their definition is stored permanently in data dictionary but they don't store copy of the data. Data for the view is built dynamically." }, { "code": null, "e": 2984, "s": 2898, "text": "A view may contain a subset of rows of the table or a subset of columns of the table." }, { "code": null, "e": 3031, "s": 2984, "text": "Views are created using CREATE VIEW statement." }, { "code": null, "e": 3076, "s": 3031, "text": "Following is the syntax for creating a view." }, { "code": null, "e": 3131, "s": 3076, "text": "CREATE/REPLACE VIEW <viewname> \nAS \n<select query>; \n" }, { "code": null, "e": 3170, "s": 3131, "text": "Consider the following Employee table." }, { "code": null, "e": 3226, "s": 3170, "text": "The following example creates a view on Employee table." }, { "code": null, "e": 3318, "s": 3226, "text": "CREATE VIEW Employee_View \nAS \nSELECT \nEmployeeNo, \nFirstName, \nLastName, \nFROM \nEmployee;" }, { "code": null, "e": 3384, "s": 3318, "text": "You can use regular SELECT statement to retrieve data from Views." }, { "code": null, "e": 3448, "s": 3384, "text": "The following example retrieves the records from Employee_View;" }, { "code": null, "e": 3507, "s": 3448, "text": "SELECT EmployeeNo, FirstName, LastName FROM Employee_View;" }, { "code": null, "e": 3575, "s": 3507, "text": "When the above query is executed, it produces the following output." }, { "code": null, "e": 4128, "s": 3575, "text": "*** Query completed. 5 rows found. 3 columns returned. \n*** Total elapsed time was 1 second. \n EmployeeNo FirstName LastName \n----------- ------------------------------ --------------------------- \n 101 Mike James \n 104 Alex Stuart \n 102 Robert Williams \n 105 Robert James \n 103 Peter Paul \n" }, { "code": null, "e": 4191, "s": 4128, "text": "An existing view can be modified using REPLACE VIEW statement." }, { "code": null, "e": 4233, "s": 4191, "text": "Following is the syntax to modify a view." }, { "code": null, "e": 4280, "s": 4233, "text": "REPLACE VIEW <viewname> \nAS \n<select query>;\n" }, { "code": null, "e": 4365, "s": 4280, "text": "The following example modifies the view Employee_View for adding additional columns." }, { "code": null, "e": 4485, "s": 4365, "text": "REPLACE VIEW Employee_View \nAS \nSELECT \nEmployeeNo, \nFirstName, \nBirthDate,\nJoinedDate \nDepartmentNo \nFROM \nEmployee; " }, { "code": null, "e": 4544, "s": 4485, "text": "An existing view can be dropped using DROP VIEW statement." }, { "code": null, "e": 4582, "s": 4544, "text": "Following is the syntax of DROP VIEW." }, { "code": null, "e": 4606, "s": 4582, "text": "DROP VIEW <viewname>; \n" }, { "code": null, "e": 4662, "s": 4606, "text": "Following is an example to drop the view Employee_View." }, { "code": null, "e": 4688, "s": 4662, "text": "DROP VIEW Employee_View; " }, { "code": null, "e": 4778, "s": 4688, "text": "Views provide additional level of security by restricting the rows or columns of a table." }, { "code": null, "e": 4868, "s": 4778, "text": "Views provide additional level of security by restricting the rows or columns of a table." }, { "code": null, "e": 4932, "s": 4868, "text": "Users can be given access only to views instead of base tables." }, { "code": null, "e": 4996, "s": 4932, "text": "Users can be given access only to views instead of base tables." }, { "code": null, "e": 5067, "s": 4996, "text": "Simplifies the use of multiple tables by pre-joining them using Views." }, { "code": null, "e": 5138, "s": 5067, "text": "Simplifies the use of multiple tables by pre-joining them using Views." }, { "code": null, "e": 5145, "s": 5138, "text": " Print" }, { "code": null, "e": 5156, "s": 5145, "text": " Add Notes" } ]
Polygon Filling Algorithm
Polygon is an ordered list of vertices as shown in the following figure. For filling polygons with particular colors, you need to determine the pixels falling on the border of the polygon and those which fall inside the polygon. In this chapter, we will see how we can fill polygons using different techniques. This algorithm works by intersecting scanline with polygon edges and fills the polygon between pairs of intersections. The following steps depict how this algorithm works. Step 1 − Find out the Ymin and Ymax from the given polygon. Step 2 − ScanLine intersects with each edge of the polygon from Ymin to Ymax. Name each intersection point of the polygon. As per the figure shown above, they are named as p0, p1, p2, p3. Step 3 − Sort the intersection point in the increasing order of X coordinate i.e. p0,p1, p1,p2, and p2,p3. Step 4 − Fill all those pair of coordinates that are inside polygons and ignore the alternate pairs. Sometimes we come across an object where we want to fill the area and its boundary with different colors. We can paint such objects with a specified interior color instead of searching for particular boundary color as in boundary filling algorithm. Instead of relying on the boundary of the object, it relies on the fill color. In other words, it replaces the interior color of the object with the fill color. When no more pixels of the original interior color exist, the algorithm is completed. Once again, this algorithm relies on the Four-connect or Eight-connect method of filling in the pixels. But instead of looking for the boundary color, it is looking for all adjacent pixels that are a part of the interior. The boundary fill algorithm works as its name. This algorithm picks a point inside an object and starts to fill until it hits the boundary of the object. The color of the boundary and the color that we fill should be different for this algorithm to work. In this algorithm, we assume that color of the boundary is same for the entire object. The boundary fill algorithm can be implemented by 4-connected pixels or 8-connected pixels. In this technique 4-connected pixels are used as shown in the figure. We are putting the pixels above, below, to the right, and to the left side of the current pixels and this process will continue until we find a boundary with different color. Step 1 − Initialize the value of seed point seedx,seedy, fcolor and dcol. Step 2 − Define the boundary values of the polygon. Step 3 − Check if the current seed point is of default color, then repeat the steps 4 and 5 till the boundary pixels reached. If getpixel(x, y) = dcol then repeat step 4 and 5 Step 4 − Change the default color with the fill color at the seed point. setPixel(seedx, seedy, fcol) Step 5 − Recursively follow the procedure with four neighborhood points. FloodFill (seedx – 1, seedy, fcol, dcol) FloodFill (seedx + 1, seedy, fcol, dcol) FloodFill (seedx, seedy - 1, fcol, dcol) FloodFill (seedx – 1, seedy + 1, fcol, dcol) Step 6 − Exit There is a problem with this technique. Consider the case as shown below where we tried to fill the entire region. Here, the image is filled only partially. In such cases, 4-connected pixels technique cannot be used. In this technique 8-connected pixels are used as shown in the figure. We are putting pixels above, below, right and left side of the current pixels as we were doing in 4-connected technique. In addition to this, we are also putting pixels in diagonals so that entire area of the current pixel is covered. This process will continue until we find a boundary with different color. Step 1 − Initialize the value of seed point seedx,seedy, fcolor and dcol. Step 2 − Define the boundary values of the polygon. Step 3 − Check if the current seed point is of default color then repeat the steps 4 and 5 till the boundary pixels reached If getpixel(x,y) = dcol then repeat step 4 and 5 Step 4 − Change the default color with the fill color at the seed point. setPixel(seedx, seedy, fcol) Step 5 − Recursively follow the procedure with four neighbourhood points FloodFill (seedx – 1, seedy, fcol, dcol) FloodFill (seedx + 1, seedy, fcol, dcol) FloodFill (seedx, seedy - 1, fcol, dcol) FloodFill (seedx, seedy + 1, fcol, dcol) FloodFill (seedx – 1, seedy + 1, fcol, dcol) FloodFill (seedx + 1, seedy + 1, fcol, dcol) FloodFill (seedx + 1, seedy - 1, fcol, dcol) FloodFill (seedx – 1, seedy - 1, fcol, dcol) Step 6 − Exit The 4-connected pixel technique failed to fill the area as marked in the following figure which won’t happen with the 8-connected technique. This method is also known as counting number method. While filling an object, we often need to identify whether particular point is inside the object or outside it. There are two methods by which we can identify whether particular point is inside an object or outside. Odd-Even Rule Nonzero winding number rule In this technique, we will count the edge crossing along the line from any point x,y to infinity. If the number of interactions is odd, then the point x,y is an interior point; and if the number of interactions is even, then the point x,y is an exterior point. The following example depicts this concept. From the above figure, we can see that from the point x,y, the number of interactions point on the left side is 5 and on the right side is 3. From both ends, the number of interaction points is odd, so the point is considered within the object. This method is also used with the simple polygons to test the given point is interior or not. It can be simply understood with the help of a pin and a rubber band. Fix up the pin on one of the edge of the polygon and tie-up the rubber band in it and then stretch the rubber band along the edges of the polygon. When all the edges of the polygon are covered by the rubber band, check out the pin which has been fixed up at the point to be test. If we find at least one wind at the point consider it within the polygon, else we can say that the point is not inside the polygon. In another alternative method, give directions to all the edges of the polygon. Draw a scan line from the point to be test towards the left most of X direction. Give the value 1 to all the edges which are going to upward direction and all other -1 as direction values. Give the value 1 to all the edges which are going to upward direction and all other -1 as direction values. Check the edge direction values from which the scan line is passing and sum up them. Check the edge direction values from which the scan line is passing and sum up them. If the total sum of this direction value is non-zero, then this point to be tested is an interior point, otherwise it is an exterior point. If the total sum of this direction value is non-zero, then this point to be tested is an interior point, otherwise it is an exterior point. In the above figure, we sum up the direction values from which the scan line is passing then the total is 1 – 1 + 1 = 1; which is non-zero. So the point is said to be an interior point. In the above figure, we sum up the direction values from which the scan line is passing then the total is 1 – 1 + 1 = 1; which is non-zero. So the point is said to be an interior point. 107 Lectures 13.5 hours Arnab Chakraborty 106 Lectures 8 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 46 Lectures 2.5 hours Shweta 70 Lectures 9 hours Abhilash Nelson 52 Lectures 7 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2230, "s": 1919, "text": "Polygon is an ordered list of vertices as shown in the following figure. For filling polygons with particular colors, you need to determine the pixels falling on the border of the polygon and those which fall inside the polygon. In this chapter, we will see how we can fill polygons using different techniques." }, { "code": null, "e": 2402, "s": 2230, "text": "This algorithm works by intersecting scanline with polygon edges and fills the polygon between pairs of intersections. The following steps depict how this algorithm works." }, { "code": null, "e": 2462, "s": 2402, "text": "Step 1 − Find out the Ymin and Ymax from the given polygon." }, { "code": null, "e": 2650, "s": 2462, "text": "Step 2 − ScanLine intersects with each edge of the polygon from Ymin to Ymax. Name each intersection point of the polygon. As per the figure shown above, they are named as p0, p1, p2, p3." }, { "code": null, "e": 2757, "s": 2650, "text": "Step 3 − Sort the intersection point in the increasing order of X coordinate i.e. p0,p1, p1,p2, and p2,p3." }, { "code": null, "e": 2858, "s": 2757, "text": "Step 4 − Fill all those pair of coordinates that are inside polygons and ignore the alternate pairs." }, { "code": null, "e": 3107, "s": 2858, "text": "Sometimes we come across an object where we want to fill the area and its boundary with different colors. We can paint such objects with a specified interior color instead of searching for particular boundary color as in boundary filling algorithm." }, { "code": null, "e": 3354, "s": 3107, "text": "Instead of relying on the boundary of the object, it relies on the fill color. In other words, it replaces the interior color of the object with the fill color. When no more pixels of the original interior color exist, the algorithm is completed." }, { "code": null, "e": 3576, "s": 3354, "text": "Once again, this algorithm relies on the Four-connect or Eight-connect method of filling in the pixels. But instead of looking for the boundary color, it is looking for all adjacent pixels that are a part of the interior." }, { "code": null, "e": 3831, "s": 3576, "text": "The boundary fill algorithm works as its name. This algorithm picks a point inside an object and starts to fill until it hits the boundary of the object. The color of the boundary and the color that we fill should be different for this algorithm to work." }, { "code": null, "e": 4010, "s": 3831, "text": "In this algorithm, we assume that color of the boundary is same for the entire object. The boundary fill algorithm can be implemented by 4-connected pixels or 8-connected pixels." }, { "code": null, "e": 4255, "s": 4010, "text": "In this technique 4-connected pixels are used as shown in the figure. We are putting the pixels above, below, to the right, and to the left side of the current pixels and this process will continue until we find a boundary with different color." }, { "code": null, "e": 4329, "s": 4255, "text": "Step 1 − Initialize the value of seed point seedx,seedy, fcolor and dcol." }, { "code": null, "e": 4381, "s": 4329, "text": "Step 2 − Define the boundary values of the polygon." }, { "code": null, "e": 4507, "s": 4381, "text": "Step 3 − Check if the current seed point is of default color, then repeat the steps 4 and 5 till the boundary pixels reached." }, { "code": null, "e": 4557, "s": 4507, "text": "If getpixel(x, y) = dcol then repeat step 4 and 5" }, { "code": null, "e": 4630, "s": 4557, "text": "Step 4 − Change the default color with the fill color at the seed point." }, { "code": null, "e": 4660, "s": 4630, "text": "setPixel(seedx, seedy, fcol)\n" }, { "code": null, "e": 4733, "s": 4660, "text": "Step 5 − Recursively follow the procedure with four neighborhood points." }, { "code": null, "e": 4902, "s": 4733, "text": "FloodFill (seedx – 1, seedy, fcol, dcol)\nFloodFill (seedx + 1, seedy, fcol, dcol)\nFloodFill (seedx, seedy - 1, fcol, dcol)\nFloodFill (seedx – 1, seedy + 1, fcol, dcol)\n" }, { "code": null, "e": 4916, "s": 4902, "text": "Step 6 − Exit" }, { "code": null, "e": 5133, "s": 4916, "text": "There is a problem with this technique. Consider the case as shown below where we tried to fill the entire region. Here, the image is filled only partially. In such cases, 4-connected pixels technique cannot be used." }, { "code": null, "e": 5324, "s": 5133, "text": "In this technique 8-connected pixels are used as shown in the figure. We are putting pixels above, below, right and left side of the current pixels as we were doing in 4-connected technique." }, { "code": null, "e": 5512, "s": 5324, "text": "In addition to this, we are also putting pixels in diagonals so that entire area of the current pixel is covered. This process will continue until we find a boundary with different color." }, { "code": null, "e": 5586, "s": 5512, "text": "Step 1 − Initialize the value of seed point seedx,seedy, fcolor and dcol." }, { "code": null, "e": 5638, "s": 5586, "text": "Step 2 − Define the boundary values of the polygon." }, { "code": null, "e": 5762, "s": 5638, "text": "Step 3 − Check if the current seed point is of default color then repeat the steps 4 and 5 till the boundary pixels reached" }, { "code": null, "e": 5812, "s": 5762, "text": "If getpixel(x,y) = dcol then repeat step 4 and 5\n" }, { "code": null, "e": 5885, "s": 5812, "text": "Step 4 − Change the default color with the fill color at the seed point." }, { "code": null, "e": 5915, "s": 5885, "text": "setPixel(seedx, seedy, fcol)\n" }, { "code": null, "e": 5988, "s": 5915, "text": "Step 5 − Recursively follow the procedure with four neighbourhood points" }, { "code": null, "e": 6333, "s": 5988, "text": "FloodFill (seedx – 1, seedy, fcol, dcol)\nFloodFill (seedx + 1, seedy, fcol, dcol)\nFloodFill (seedx, seedy - 1, fcol, dcol)\nFloodFill (seedx, seedy + 1, fcol, dcol)\nFloodFill (seedx – 1, seedy + 1, fcol, dcol)\nFloodFill (seedx + 1, seedy + 1, fcol, dcol)\nFloodFill (seedx + 1, seedy - 1, fcol, dcol)\nFloodFill (seedx – 1, seedy - 1, fcol, dcol)\n" }, { "code": null, "e": 6347, "s": 6333, "text": "Step 6 − Exit" }, { "code": null, "e": 6488, "s": 6347, "text": "The 4-connected pixel technique failed to fill the area as marked in the following figure which won’t happen with the 8-connected technique." }, { "code": null, "e": 6757, "s": 6488, "text": "This method is also known as counting number method. While filling an object, we often need to identify whether particular point is inside the object or outside it. There are two methods by which we can identify whether particular point is inside an object or outside." }, { "code": null, "e": 6771, "s": 6757, "text": "Odd-Even Rule" }, { "code": null, "e": 6799, "s": 6771, "text": "Nonzero winding number rule" }, { "code": null, "e": 7104, "s": 6799, "text": "In this technique, we will count the edge crossing along the line from any point x,y to infinity. If the number of interactions is odd, then the point x,y is an interior point; and if the number of interactions is even, then the point x,y is an exterior point. The following example depicts this concept." }, { "code": null, "e": 7349, "s": 7104, "text": "From the above figure, we can see that from the point x,y, the number of interactions point on the left side is 5 and on the right side is 3. From both ends, the number of interaction points is odd, so the point is considered within the object." }, { "code": null, "e": 7660, "s": 7349, "text": "This method is also used with the simple polygons to test the given point is interior or not. It can be simply understood with the help of a pin and a rubber band. Fix up the pin on one of the edge of the polygon and tie-up the rubber band in it and then stretch the rubber band along the edges of the polygon." }, { "code": null, "e": 7925, "s": 7660, "text": "When all the edges of the polygon are covered by the rubber band, check out the pin which has been fixed up at the point to be test. If we find at least one wind at the point consider it within the polygon, else we can say that the point is not inside the polygon." }, { "code": null, "e": 8086, "s": 7925, "text": "In another alternative method, give directions to all the edges of the polygon. Draw a scan line from the point to be test towards the left most of X direction." }, { "code": null, "e": 8194, "s": 8086, "text": "Give the value 1 to all the edges which are going to upward direction and all other -1 as direction values." }, { "code": null, "e": 8302, "s": 8194, "text": "Give the value 1 to all the edges which are going to upward direction and all other -1 as direction values." }, { "code": null, "e": 8387, "s": 8302, "text": "Check the edge direction values from which the scan line is passing and sum up them." }, { "code": null, "e": 8472, "s": 8387, "text": "Check the edge direction values from which the scan line is passing and sum up them." }, { "code": null, "e": 8612, "s": 8472, "text": "If the total sum of this direction value is non-zero, then this point to be tested is an interior point, otherwise it is an exterior point." }, { "code": null, "e": 8752, "s": 8612, "text": "If the total sum of this direction value is non-zero, then this point to be tested is an interior point, otherwise it is an exterior point." }, { "code": null, "e": 8938, "s": 8752, "text": "In the above figure, we sum up the direction values from which the scan line is passing then the total is 1 – 1 + 1 = 1; which is non-zero. So the point is said to be an interior point." }, { "code": null, "e": 9124, "s": 8938, "text": "In the above figure, we sum up the direction values from which the scan line is passing then the total is 1 – 1 + 1 = 1; which is non-zero. So the point is said to be an interior point." }, { "code": null, "e": 9161, "s": 9124, "text": "\n 107 Lectures \n 13.5 hours \n" }, { "code": null, "e": 9180, "s": 9161, "text": " Arnab Chakraborty" }, { "code": null, "e": 9214, "s": 9180, "text": "\n 106 Lectures \n 8 hours \n" }, { "code": null, "e": 9233, "s": 9214, "text": " Arnab Chakraborty" }, { "code": null, "e": 9266, "s": 9233, "text": "\n 99 Lectures \n 6 hours \n" }, { "code": null, "e": 9285, "s": 9266, "text": " Arnab Chakraborty" }, { "code": null, "e": 9320, "s": 9285, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9328, "s": 9320, "text": " Shweta" }, { "code": null, "e": 9361, "s": 9328, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 9378, "s": 9361, "text": " Abhilash Nelson" }, { "code": null, "e": 9411, "s": 9378, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 9433, "s": 9411, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 9440, "s": 9433, "text": " Print" }, { "code": null, "e": 9451, "s": 9440, "text": " Add Notes" } ]
Sentence Scoring Based on Noun and Numerical Values | by Mofiz Mojib Haider | Towards Data Science
Sentence scoring is one of the most used processes in the area of Natural Language Processing (NLP) while working on textual data. It is a process to associate a numerical value with a sentence based on the used algorithm’s priority. This process is highly used especially on text summarization. There are many popular methods for sentence scoring like TF-IDF, TextRank and so on. Here, we are going to examine a new approach to score a sentence based on the occurrence of nouns, numerical values, and word2vec mean similarity. Step-1: Import libraries Step-2: Text processing and methods A random paragraph from a random news article from BBC has been selected to examine. Processing steps are mentioned below: Split each of the sentences using sentence tokenizer from NLTK sent_tokenize. Split each of the sentences using sentence tokenizer from NLTK sent_tokenize. 2. Special characters like %, $, #, @, etc has been removed. 3. All the words of each sentence have been tokenized. 4. Stop words like and, but, or, which are included in the stop word list has been removed. 5. It has been ensured that all the words of a sentence has only one occurrence. 6. Lemmatization has been used to find the root word Step-3: Gensim Word2Vec Make a vector list of the lemmatized text list using the Gensim Word2Vec skip-gram method. Step-4: Sentence Scoring To score a sentence two methods have been used named meanOfWord() and checkNum(). This method has two lists of pos values which include nouns and digits. But the problem is numbers like ‘ 234’, ‘ 34.5’ (blank space before the number) considered as a noun in NLTK pos_tag(). So, another method has been used checkNum() which confirms its a number or not. The procedure used in meanOfWord() has mentioned below: Find the similarity of each word from the word2vec model and calculate the mean similarityCheck the word if it is a number or notIf number then add 1 with the mean similarity if noun then adds 0.25 with the mean similarityReturn the updated mean value Find the similarity of each word from the word2vec model and calculate the mean similarity Check the word if it is a number or not If number then add 1 with the mean similarity if noun then adds 0.25 with the mean similarity Return the updated mean value For each sentence from the lemmatized list, the mean score has been calculated and pushed into the score list. The output of the score will be the index number of the sentence and the numerical score of that sentence. My output is: [[0, 2.875715106488629], [1, 3.3718763930364872], [2,2.117822954338044], [3, 4.115576311542342]] which indicates: 'China remains the main area of concern for BMW after sales there fell 16% last year.' got 2.875715106488629 score.'However, BMW is hopeful of a much better year in 2005 as its direct investment in China begins to pay dividends.' got 3.3718763930364872 score.'The company only began assembling luxury high-powered sedans in China in 2003.' got 2.117822954338044 score.'2004 was generally a good year for BMW, which saw revenues from its core car-making operations rise 11%.' got 4.115576311542342 score. The 4th sentence has got the highest score because it contains more nouns and numerical values than other sentences. It may vary, as the word2vec model may generate a different vector for different iteration. The complete code is given as follows: Caution: This approach will give a better performance where the amount of nouns and numerical values is very much higher. If you find this approach useful then you can use it and share it with others. Feel free to write suggestions on the comment section.
[ { "code": null, "e": 405, "s": 171, "text": "Sentence scoring is one of the most used processes in the area of Natural Language Processing (NLP) while working on textual data. It is a process to associate a numerical value with a sentence based on the used algorithm’s priority." }, { "code": null, "e": 699, "s": 405, "text": "This process is highly used especially on text summarization. There are many popular methods for sentence scoring like TF-IDF, TextRank and so on. Here, we are going to examine a new approach to score a sentence based on the occurrence of nouns, numerical values, and word2vec mean similarity." }, { "code": null, "e": 724, "s": 699, "text": "Step-1: Import libraries" }, { "code": null, "e": 760, "s": 724, "text": "Step-2: Text processing and methods" }, { "code": null, "e": 883, "s": 760, "text": "A random paragraph from a random news article from BBC has been selected to examine. Processing steps are mentioned below:" }, { "code": null, "e": 961, "s": 883, "text": "Split each of the sentences using sentence tokenizer from NLTK sent_tokenize." }, { "code": null, "e": 1039, "s": 961, "text": "Split each of the sentences using sentence tokenizer from NLTK sent_tokenize." }, { "code": null, "e": 1100, "s": 1039, "text": "2. Special characters like %, $, #, @, etc has been removed." }, { "code": null, "e": 1155, "s": 1100, "text": "3. All the words of each sentence have been tokenized." }, { "code": null, "e": 1247, "s": 1155, "text": "4. Stop words like and, but, or, which are included in the stop word list has been removed." }, { "code": null, "e": 1328, "s": 1247, "text": "5. It has been ensured that all the words of a sentence has only one occurrence." }, { "code": null, "e": 1381, "s": 1328, "text": "6. Lemmatization has been used to find the root word" }, { "code": null, "e": 1405, "s": 1381, "text": "Step-3: Gensim Word2Vec" }, { "code": null, "e": 1496, "s": 1405, "text": "Make a vector list of the lemmatized text list using the Gensim Word2Vec skip-gram method." }, { "code": null, "e": 1521, "s": 1496, "text": "Step-4: Sentence Scoring" }, { "code": null, "e": 1931, "s": 1521, "text": "To score a sentence two methods have been used named meanOfWord() and checkNum(). This method has two lists of pos values which include nouns and digits. But the problem is numbers like ‘ 234’, ‘ 34.5’ (blank space before the number) considered as a noun in NLTK pos_tag(). So, another method has been used checkNum() which confirms its a number or not. The procedure used in meanOfWord() has mentioned below:" }, { "code": null, "e": 2183, "s": 1931, "text": "Find the similarity of each word from the word2vec model and calculate the mean similarityCheck the word if it is a number or notIf number then add 1 with the mean similarity if noun then adds 0.25 with the mean similarityReturn the updated mean value" }, { "code": null, "e": 2274, "s": 2183, "text": "Find the similarity of each word from the word2vec model and calculate the mean similarity" }, { "code": null, "e": 2314, "s": 2274, "text": "Check the word if it is a number or not" }, { "code": null, "e": 2408, "s": 2314, "text": "If number then add 1 with the mean similarity if noun then adds 0.25 with the mean similarity" }, { "code": null, "e": 2438, "s": 2408, "text": "Return the updated mean value" }, { "code": null, "e": 2656, "s": 2438, "text": "For each sentence from the lemmatized list, the mean score has been calculated and pushed into the score list. The output of the score will be the index number of the sentence and the numerical score of that sentence." }, { "code": null, "e": 2670, "s": 2656, "text": "My output is:" }, { "code": null, "e": 2767, "s": 2670, "text": "[[0, 2.875715106488629], [1, 3.3718763930364872], [2,2.117822954338044], [3, 4.115576311542342]]" }, { "code": null, "e": 2784, "s": 2767, "text": "which indicates:" }, { "code": null, "e": 3288, "s": 2784, "text": "'China remains the main area of concern for BMW after sales there fell 16% last year.' got 2.875715106488629 score.'However, BMW is hopeful of a much better year in 2005 as its direct investment in China begins to pay dividends.' got 3.3718763930364872 score.'The company only began assembling luxury high-powered sedans in China in 2003.' got 2.117822954338044 score.'2004 was generally a good year for BMW, which saw revenues from its core car-making operations rise 11%.' got 4.115576311542342 score." }, { "code": null, "e": 3497, "s": 3288, "text": "The 4th sentence has got the highest score because it contains more nouns and numerical values than other sentences. It may vary, as the word2vec model may generate a different vector for different iteration." }, { "code": null, "e": 3536, "s": 3497, "text": "The complete code is given as follows:" }, { "code": null, "e": 3545, "s": 3536, "text": "Caution:" }, { "code": null, "e": 3658, "s": 3545, "text": "This approach will give a better performance where the amount of nouns and numerical values is very much higher." } ]
Swift - Break Statement
The break statement in C programming language has the following two usages − When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in switch statement (covered in the next chapter). It can be used to terminate a case in switch statement (covered in the next chapter). If you are using nested loops (i.e., one loop inside another loop), then the break statement will stop the execution of the innermost loop and start executing the next line of the code after the block. The syntax for a break statement in Swift 4 is as follows − break var index = 10 repeat { index = index + 1 if( index == 15 ){ break } print( "Value of index is \(index)") } while index < 20 When the above code is compiled and executed, it produces the following result − Value of index is 11 Value of index is 12 Value of index is 13 Value of index is 14 38 Lectures 1 hours Ashish Sharma 13 Lectures 2 hours Three Millennials 7 Lectures 1 hours Three Millennials 22 Lectures 1 hours Frahaan Hussain 12 Lectures 39 mins Devasena Rajendran 40 Lectures 2.5 hours Grant Klimaytys Print Add Notes Bookmark this page
[ { "code": null, "e": 2330, "s": 2253, "text": "The break statement in C programming language has the following two usages −" }, { "code": null, "e": 2492, "s": 2330, "text": "When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop." }, { "code": null, "e": 2654, "s": 2492, "text": "When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop." }, { "code": null, "e": 2740, "s": 2654, "text": "It can be used to terminate a case in switch statement (covered in the next chapter)." }, { "code": null, "e": 2826, "s": 2740, "text": "It can be used to terminate a case in switch statement (covered in the next chapter)." }, { "code": null, "e": 3028, "s": 2826, "text": "If you are using nested loops (i.e., one loop inside another loop), then the break statement will stop the execution of the innermost loop and start executing the next line of the code after the block." }, { "code": null, "e": 3088, "s": 3028, "text": "The syntax for a break statement in Swift 4 is as follows −" }, { "code": null, "e": 3095, "s": 3088, "text": "break\n" }, { "code": null, "e": 3239, "s": 3095, "text": "var index = 10\n\nrepeat {\n index = index + 1\n if( index == 15 ){\n break\n }\n print( \"Value of index is \\(index)\")\n} while index < 20" }, { "code": null, "e": 3320, "s": 3239, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3405, "s": 3320, "text": "Value of index is 11\nValue of index is 12\nValue of index is 13\nValue of index is 14\n" }, { "code": null, "e": 3438, "s": 3405, "text": "\n 38 Lectures \n 1 hours \n" }, { "code": null, "e": 3453, "s": 3438, "text": " Ashish Sharma" }, { "code": null, "e": 3486, "s": 3453, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 3505, "s": 3486, "text": " Three Millennials" }, { "code": null, "e": 3537, "s": 3505, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 3556, "s": 3537, "text": " Three Millennials" }, { "code": null, "e": 3589, "s": 3556, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 3606, "s": 3589, "text": " Frahaan Hussain" }, { "code": null, "e": 3638, "s": 3606, "text": "\n 12 Lectures \n 39 mins\n" }, { "code": null, "e": 3658, "s": 3638, "text": " Devasena Rajendran" }, { "code": null, "e": 3693, "s": 3658, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3710, "s": 3693, "text": " Grant Klimaytys" }, { "code": null, "e": 3717, "s": 3710, "text": " Print" }, { "code": null, "e": 3728, "s": 3717, "text": " Add Notes" } ]
How will you keep the CURSOR open after firing COMMIT in a COBOL-DB2 program?
Whenever we issue a COMMIT statement, all the open cursors will get closed. This is a very common case when we have to frequently use the commit statement after a UPDATE while working with a cursor. In this case we can use the “WITH HOLD” clause during the cursor declaration. The “WITH HOLD” clause will keep the cursor open even after firing the COMMIT statement. We can give the “WITH HOLD” clause in the following way. EXEC SQL DECLARE ORDER_CUR CURSOR WITH HOLD FOR SELECT ORDER_ID, TRANSACTION_ID FROM ORDERS WHERE ORDER_DATE = ‘2020-07-28’ END-EXEC
[ { "code": null, "e": 1339, "s": 1062, "text": "Whenever we issue a COMMIT statement, all the open cursors will get closed. This is a very common case when we have to frequently use the commit statement after a UPDATE while working with a cursor. In this case we can use the “WITH HOLD” clause during the cursor declaration." }, { "code": null, "e": 1485, "s": 1339, "text": "The “WITH HOLD” clause will keep the cursor open even after firing the COMMIT statement. We can give the “WITH HOLD” clause in the following way." }, { "code": null, "e": 1645, "s": 1485, "text": "EXEC SQL\n DECLARE ORDER_CUR CURSOR WITH HOLD FOR\n SELECT ORDER_ID, TRANSACTION_ID FROM ORDERS\n WHERE ORDER_DATE = ‘2020-07-28’\nEND-EXEC" } ]
Tryit Editor v3.7
HTML Input attributes Tryit: The autocomplete attribute
[ { "code": null, "e": 32, "s": 10, "text": "HTML Input attributes" } ]
io.MultiWriter() Function in Golang with Examples - GeeksforGeeks
05 May, 2020 In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The MultiWriter() function in Go language is used to create a writer that copies its writes to each and every given writers, which is the same as the Unix command tee(1). Here, each and every write is written to each of the included writer, one by one. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions. Syntax: func MultiWriter(writers ...Writer) Writer Here, “writers” is the number of writers stated as a parameter in this function. Return value: It returns a Writer which includes the number of bytes present in the stated buffer and also returns an error if any. And if a stated writer returns an error then the entire write operation ceases and doesn’t extend down the list. Example 1: // Golang program to illustrate the usage of// io.MultiWriter() function // Including main packagepackage main // Importing fmt, io, bytes, and stringsimport ( "bytes" "fmt" "io" "strings") // Calling mainfunc main() { // Defining reader using NewReader method reader := strings.NewReader("Geeks") // Defining two buffers var buffer1, buffer2 bytes.Buffer // Calling MultiWriter method with its parameters writer := io.MultiWriter(&buffer1, &buffer2) // Calling Copy method with its parameters n, err := io.Copy(writer, reader) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf("Number of bytes in the buffer: %v\n", n) fmt.Printf("Buffer1: %v\n", buffer1.String()) fmt.Printf("Buffer2: %v\n", buffer2.String())} Output: Number of bytes in the buffer: 5 Buffer1: Geeks Buffer2: Geeks Here, Copy() method is used to return the number of bytes contained in the buffer. And here the content of both the buffer is the same as the stated writer duplicates its write to all the other writers. Example 2: // Golang program to illustrate the usage of// io.MultiWriter() function // Including main packagepackage main // Importing fmt, io, bytes, and stringsimport ( "bytes" "fmt" "io" "strings") // Calling mainfunc main() { // Defining reader using NewReader method reader := strings.NewReader("GeeksforGeeks\nis\na\nCS-Portal!") // Defining two buffers var buffer1, buffer2 bytes.Buffer // Calling MultiWriter method with its parameters writer := io.MultiWriter(&buffer1, &buffer2) // Calling Copy method with its parameters n, err := io.Copy(writer, reader) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf("Number of bytes in the buffer: %v\n", n) fmt.Printf("Buffer1: %v\n", buffer1.String()) fmt.Printf("Buffer2: %v\n", buffer2.String())} Output: Number of bytes in the buffer: 29 Buffer1: GeeksforGeeks is a CS-Portal! Buffer2: GeeksforGeeks is a CS-Portal! Golang-io Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples How to Split a String in Golang? Arrays in Go Golang Maps Slices in Golang How to convert a string in lower case in Golang? How to compare times in Golang? How to Trim a String in Golang? Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang?
[ { "code": null, "e": 24310, "s": 24282, "text": "\n05 May, 2020" }, { "code": null, "e": 24868, "s": 24310, "text": "In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The MultiWriter() function in Go language is used to create a writer that copies its writes to each and every given writers, which is the same as the Unix command tee(1). Here, each and every write is written to each of the included writer, one by one. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions." }, { "code": null, "e": 24876, "s": 24868, "text": "Syntax:" }, { "code": null, "e": 24920, "s": 24876, "text": "func MultiWriter(writers ...Writer) Writer\n" }, { "code": null, "e": 25001, "s": 24920, "text": "Here, “writers” is the number of writers stated as a parameter in this function." }, { "code": null, "e": 25246, "s": 25001, "text": "Return value: It returns a Writer which includes the number of bytes present in the stated buffer and also returns an error if any. And if a stated writer returns an error then the entire write operation ceases and doesn’t extend down the list." }, { "code": null, "e": 25257, "s": 25246, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// io.MultiWriter() function // Including main packagepackage main // Importing fmt, io, bytes, and stringsimport ( \"bytes\" \"fmt\" \"io\" \"strings\") // Calling mainfunc main() { // Defining reader using NewReader method reader := strings.NewReader(\"Geeks\") // Defining two buffers var buffer1, buffer2 bytes.Buffer // Calling MultiWriter method with its parameters writer := io.MultiWriter(&buffer1, &buffer2) // Calling Copy method with its parameters n, err := io.Copy(writer, reader) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf(\"Number of bytes in the buffer: %v\\n\", n) fmt.Printf(\"Buffer1: %v\\n\", buffer1.String()) fmt.Printf(\"Buffer2: %v\\n\", buffer2.String())}", "e": 26091, "s": 25257, "text": null }, { "code": null, "e": 26099, "s": 26091, "text": "Output:" }, { "code": null, "e": 26163, "s": 26099, "text": "Number of bytes in the buffer: 5\nBuffer1: Geeks\nBuffer2: Geeks\n" }, { "code": null, "e": 26366, "s": 26163, "text": "Here, Copy() method is used to return the number of bytes contained in the buffer. And here the content of both the buffer is the same as the stated writer duplicates its write to all the other writers." }, { "code": null, "e": 26377, "s": 26366, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// io.MultiWriter() function // Including main packagepackage main // Importing fmt, io, bytes, and stringsimport ( \"bytes\" \"fmt\" \"io\" \"strings\") // Calling mainfunc main() { // Defining reader using NewReader method reader := strings.NewReader(\"GeeksforGeeks\\nis\\na\\nCS-Portal!\") // Defining two buffers var buffer1, buffer2 bytes.Buffer // Calling MultiWriter method with its parameters writer := io.MultiWriter(&buffer1, &buffer2) // Calling Copy method with its parameters n, err := io.Copy(writer, reader) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf(\"Number of bytes in the buffer: %v\\n\", n) fmt.Printf(\"Buffer1: %v\\n\", buffer1.String()) fmt.Printf(\"Buffer2: %v\\n\", buffer2.String())}", "e": 27238, "s": 26377, "text": null }, { "code": null, "e": 27246, "s": 27238, "text": "Output:" }, { "code": null, "e": 27359, "s": 27246, "text": "Number of bytes in the buffer: 29\nBuffer1: GeeksforGeeks\nis\na\nCS-Portal!\nBuffer2: GeeksforGeeks\nis\na\nCS-Portal!\n" }, { "code": null, "e": 27369, "s": 27359, "text": "Golang-io" }, { "code": null, "e": 27381, "s": 27369, "text": "Go Language" }, { "code": null, "e": 27479, "s": 27381, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27530, "s": 27479, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 27563, "s": 27530, "text": "How to Split a String in Golang?" }, { "code": null, "e": 27576, "s": 27563, "text": "Arrays in Go" }, { "code": null, "e": 27588, "s": 27576, "text": "Golang Maps" }, { "code": null, "e": 27605, "s": 27588, "text": "Slices in Golang" }, { "code": null, "e": 27654, "s": 27605, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 27686, "s": 27654, "text": "How to compare times in Golang?" }, { "code": null, "e": 27718, "s": 27686, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 27772, "s": 27718, "text": "Different Ways to Find the Type of Variable in Golang" } ]
Enhance your Python code’s readability with pycodestyle | by Kenneth Leung | Towards Data Science
Programming is an indispensable skill of a data practitioner’s toolkit, and while it is easy to create a script to execute basic functions, writing good readable code at scale requires more work and thought. Given Python’s popularity in data science, I will be delving into the use of pycodestyle for style guide checking to improve the quality and readability of Python code. (1) About PEP-8(2) Motivation(3) Installation(4) Basic Usage(5) Advanced Usage The pycodestyle checker provides code recommendations based on the PEP-8 style conventions. So what exactly is PEP-8? PEP stands for Python Enhancement Proposal, and PEP-8 is a guide that outlines the best practices of writing Python code. Authored in 2001, its main objective is to improve overall code consistency and readability by standardizing code styles. One thing to note is that PEP-8 is meant to serve as a guide, and not intended to be interpreted as biblical instructions to always strictly adhere to. A quick look at the PEP-8 documentation will immediately make it evident that there are way too many best practices to remember. Furthermore, having already spent so much effort in writing the many lines of code, surely you do not wish to waste more time in inspecting the scripts manually for gaps in readability. This is where pycodestyle comes in to automatically analyze your Python scripts and pinpoint the specific areas where the code can be improved. The package was called pep8, but was renamed as pycodestyle in a bid to reduce confusion. This is after Python’s creator (Guido van Rossum) highlighted that tools should not be named after style guides, as people may ‘pick a fight’ with PEP-8 (styling guide) based on the behavior of pep8 (tool). pip is the preferred installer program to use, and you can install or upgrade pycodestyle by running the following commands in your terminal: # Install pycodestylepip install pycodestyle# Upgrade pycodestylepip install --upgrade pycodestyle The most straightforward use is to run pycodestyle on a Python script (.py file) as a command in the terminal. Let’s use the following sample script (named pycodestyle_sample_script.py) for demonstration: We put pycodestyle to work by running this simple command: pycodestyle pycodestyle_sample_script.py The output specifies the code locations where PEP-8 style convention is violated: The pair of digits separated by the colon (e.g. 3:19) in each line refers to the line number and character number respectively. For example, the output of 6:64 E202 whitespace before ')' means that in line 6, there is an unexpected whitespace at 64th character mark. You can review the frequency of error occurrences by parsing the statistics argument: pycodestyle --statistics -qq pycodestyle_sample_script.py In the output above, we see that there are 4 occurrences of unexpected whitespace before a closing bracket ‘)’. We can also import pycodestyle directly into our Python code to execute automated tests. This is useful for automated testing of coding style conformance of multiple scripts. For example, the following class can be written to automatically check for conformance to PEP-8 convention: import unittestimport pycodestyleclass TestCodeFormat(unittest.TestCase): def test_conformance(self): """Test that the scripts conform to PEP-8.""" style = pycodestyle.StyleGuide(quiet=True) result = style.check_files(['file1.py', 'file2.py']) self.assertEqual(result.total_errors, 0, "Found style errors") The tool can also be configured such that tests are done based on the style rule preferences we define. For example, we can remove specific error(s) that we do not want to be detected in the checks: style = pycodestyle.StyleGuide(ignore=['E201', 'E202', 'E501']) Alternatively, we can direct pycodestyle to use a different configuration file (containing a specific set of style rules) altogether. import pycodestylestyle = pycodestyle.StyleGuide(config_file='/path/to/tox.ini') There are more functionalities available to suit your needs, so do visit the pycodestyle’s documentation page for more details. In this article, we looked at how to use the pycodestyle tool to check that our Python scripts comply with PEP-8 code styling conventions. Code is read more often than it is written, so it is vital that our code is consistent, understandable, and neatly structured. Trust me, your collaborators and your future self will thank you for this. I welcome you to join me on a data science learning journey! Give this Medium page a follow to stay in the loop of more data science content, or reach out to me on LinkedIn. Happy coding! PEP-8 — Style Guide for Python Code pycodestyle official documentation towardsdatascience.com towardsdatascience.com Feel free to check out Remote Python Jobs, a job board for remote Python-related opportunities.
[ { "code": null, "e": 379, "s": 171, "text": "Programming is an indispensable skill of a data practitioner’s toolkit, and while it is easy to create a script to execute basic functions, writing good readable code at scale requires more work and thought." }, { "code": null, "e": 548, "s": 379, "text": "Given Python’s popularity in data science, I will be delving into the use of pycodestyle for style guide checking to improve the quality and readability of Python code." }, { "code": null, "e": 627, "s": 548, "text": "(1) About PEP-8(2) Motivation(3) Installation(4) Basic Usage(5) Advanced Usage" }, { "code": null, "e": 745, "s": 627, "text": "The pycodestyle checker provides code recommendations based on the PEP-8 style conventions. So what exactly is PEP-8?" }, { "code": null, "e": 989, "s": 745, "text": "PEP stands for Python Enhancement Proposal, and PEP-8 is a guide that outlines the best practices of writing Python code. Authored in 2001, its main objective is to improve overall code consistency and readability by standardizing code styles." }, { "code": null, "e": 1141, "s": 989, "text": "One thing to note is that PEP-8 is meant to serve as a guide, and not intended to be interpreted as biblical instructions to always strictly adhere to." }, { "code": null, "e": 1270, "s": 1141, "text": "A quick look at the PEP-8 documentation will immediately make it evident that there are way too many best practices to remember." }, { "code": null, "e": 1456, "s": 1270, "text": "Furthermore, having already spent so much effort in writing the many lines of code, surely you do not wish to waste more time in inspecting the scripts manually for gaps in readability." }, { "code": null, "e": 1600, "s": 1456, "text": "This is where pycodestyle comes in to automatically analyze your Python scripts and pinpoint the specific areas where the code can be improved." }, { "code": null, "e": 1897, "s": 1600, "text": "The package was called pep8, but was renamed as pycodestyle in a bid to reduce confusion. This is after Python’s creator (Guido van Rossum) highlighted that tools should not be named after style guides, as people may ‘pick a fight’ with PEP-8 (styling guide) based on the behavior of pep8 (tool)." }, { "code": null, "e": 2039, "s": 1897, "text": "pip is the preferred installer program to use, and you can install or upgrade pycodestyle by running the following commands in your terminal:" }, { "code": null, "e": 2138, "s": 2039, "text": "# Install pycodestylepip install pycodestyle# Upgrade pycodestylepip install --upgrade pycodestyle" }, { "code": null, "e": 2343, "s": 2138, "text": "The most straightforward use is to run pycodestyle on a Python script (.py file) as a command in the terminal. Let’s use the following sample script (named pycodestyle_sample_script.py) for demonstration:" }, { "code": null, "e": 2402, "s": 2343, "text": "We put pycodestyle to work by running this simple command:" }, { "code": null, "e": 2443, "s": 2402, "text": "pycodestyle pycodestyle_sample_script.py" }, { "code": null, "e": 2525, "s": 2443, "text": "The output specifies the code locations where PEP-8 style convention is violated:" }, { "code": null, "e": 2653, "s": 2525, "text": "The pair of digits separated by the colon (e.g. 3:19) in each line refers to the line number and character number respectively." }, { "code": null, "e": 2792, "s": 2653, "text": "For example, the output of 6:64 E202 whitespace before ')' means that in line 6, there is an unexpected whitespace at 64th character mark." }, { "code": null, "e": 2878, "s": 2792, "text": "You can review the frequency of error occurrences by parsing the statistics argument:" }, { "code": null, "e": 2936, "s": 2878, "text": "pycodestyle --statistics -qq pycodestyle_sample_script.py" }, { "code": null, "e": 3048, "s": 2936, "text": "In the output above, we see that there are 4 occurrences of unexpected whitespace before a closing bracket ‘)’." }, { "code": null, "e": 3223, "s": 3048, "text": "We can also import pycodestyle directly into our Python code to execute automated tests. This is useful for automated testing of coding style conformance of multiple scripts." }, { "code": null, "e": 3331, "s": 3223, "text": "For example, the following class can be written to automatically check for conformance to PEP-8 convention:" }, { "code": null, "e": 3678, "s": 3331, "text": "import unittestimport pycodestyleclass TestCodeFormat(unittest.TestCase): def test_conformance(self): \"\"\"Test that the scripts conform to PEP-8.\"\"\" style = pycodestyle.StyleGuide(quiet=True) result = style.check_files(['file1.py', 'file2.py']) self.assertEqual(result.total_errors, 0, \"Found style errors\")" }, { "code": null, "e": 3877, "s": 3678, "text": "The tool can also be configured such that tests are done based on the style rule preferences we define. For example, we can remove specific error(s) that we do not want to be detected in the checks:" }, { "code": null, "e": 3941, "s": 3877, "text": "style = pycodestyle.StyleGuide(ignore=['E201', 'E202', 'E501'])" }, { "code": null, "e": 4075, "s": 3941, "text": "Alternatively, we can direct pycodestyle to use a different configuration file (containing a specific set of style rules) altogether." }, { "code": null, "e": 4156, "s": 4075, "text": "import pycodestylestyle = pycodestyle.StyleGuide(config_file='/path/to/tox.ini')" }, { "code": null, "e": 4284, "s": 4156, "text": "There are more functionalities available to suit your needs, so do visit the pycodestyle’s documentation page for more details." }, { "code": null, "e": 4423, "s": 4284, "text": "In this article, we looked at how to use the pycodestyle tool to check that our Python scripts comply with PEP-8 code styling conventions." }, { "code": null, "e": 4625, "s": 4423, "text": "Code is read more often than it is written, so it is vital that our code is consistent, understandable, and neatly structured. Trust me, your collaborators and your future self will thank you for this." }, { "code": null, "e": 4813, "s": 4625, "text": "I welcome you to join me on a data science learning journey! Give this Medium page a follow to stay in the loop of more data science content, or reach out to me on LinkedIn. Happy coding!" }, { "code": null, "e": 4849, "s": 4813, "text": "PEP-8 — Style Guide for Python Code" }, { "code": null, "e": 4884, "s": 4849, "text": "pycodestyle official documentation" }, { "code": null, "e": 4907, "s": 4884, "text": "towardsdatascience.com" }, { "code": null, "e": 4930, "s": 4907, "text": "towardsdatascience.com" } ]
Data analysis and Visualization with Python - GeeksforGeeks
21 Feb, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier. In this article, I have used Pandas to analyze data on Country Data.csv file from UN public Data Sets of a popular ‘statweb.stanford.edu’ website.As I have analyzed the Indian Country Data, I have introduced Pandas key concepts as below. Before going through this article, have a rough idea of basics from matplotlib and csv. InstallationEasiest way to install pandas is to use pip: pip install pandas or, Download it from here Creating A DataFrame in Pandas Creation of dataframe is done by passing multiple Series into the DataFrame class using pd.Series method. Here, it is passed in the two Series objects, s1 as the first row, and s2 as the second row.Example: # assigning two series to s1 and s2s1 = pd.Series([1,2])s2 = pd.Series(["Ashish", "Sid"])# framing series objects into datadf = pd.DataFrame([s1,s2])# show the data framedf # data framing in another way# taking index and column valuesdframe = pd.DataFrame([[1,2],["Ashish", "Sid"]], index=["r1", "r2"], columns=["c1", "c2"])dframe # framing in another way # dict-like containerdframe = pd.DataFrame({ "c1": [1, "Ashish"], "c2": [2, "Sid"]})dframe Output: Importing Data with Pandas The first step is to read the data. The data is stored as a comma-separated values, or csv, file, where each row is separated by a new line, and each column by a comma (,). In order to be able to work with the data in Python, it is needed to read the csv file into a Pandas DataFrame. A DataFrame is a way to represent and work with tabular data. Tabular data has rows and columns, just like this csv file(Click Download).Example: # Import the pandas library, renamed as pdimport pandas as pd # Read IND_data.csv into a DataFrame, assigned to dfdf = pd.read_csv("IND_data.csv") # Prints the first 5 rows of a DataFrame as defaultdf.head() # Prints no. of rows and columns of a DataFramedf.shape Output: 29,10 Indexing DataFrames with Pandas Indexing can be possible using the pandas.DataFrame.iloc method. The iloc method allows to retrieve as many as rows and columns by position.Examples: # prints first 5 rows and every column which replicates df.head()df.iloc[0:5,:]# prints entire rows and columnsdf.iloc[:,:]# prints from 5th rows and first 5 columnsdf.iloc[5:,:5] Indexing Using Labels in Pandas Indexing can be worked with labels using the pandas.DataFrame.loc method, which allows to index using labels instead of positions.Examples: # prints first five rows including 5th index and every columns of dfdf.loc[0:5,:]# prints from 5th rows onwards and entire columnsdf = df.loc[5:,:] The above doesn’t actually look much different from df.iloc[0:5,:]. This is because while row labels can take on any values, our row labels match the positions exactly. But column labels can make things much easier when working with data. Example: # Prints the first 5 rows of Time period# value df.loc[:5,"Time period"] DataFrame Math with Pandas Computation of data frames can be done by using Statistical Functions of pandas tools.Examples: # computes various summary statistics, excluding NaN valuesdf.describe()# for computing correlationsdf.corr()# computes numerical data ranksdf.rank() Pandas Plotting Plots in these examples are made using standard convention for referencing the matplotlib API which provides the basics in pandas to easily create decent looking plots.Examples: # import the required module import matplotlib.pyplot as plt# plot a histogram df['Observation Value'].hist(bins=10) # shows presence of a lot of outliers/extreme valuesdf.boxplot(column='Observation Value', by = 'Time period') # plotting points as a scatter plotx = df["Observation Value"]y = df["Time period"]plt.scatter(x, y, label= "stars", color= "m", marker= "*", s=30)# x-axis labelplt.xlabel('Observation Value')# frequency labelplt.ylabel('Time period')# function to show the plotplt.show() Data Analysis and Visualization with Python | Set 2 Reference: http://pandas.pydata.org/pandas-docs/stable/tutorials.html https://www.datacamp.com This article is contributed by Afzal_Saan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24974, "s": 24946, "text": "\n21 Feb, 2018" }, { "code": null, "e": 25515, "s": 24974, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier. In this article, I have used Pandas to analyze data on Country Data.csv file from UN public Data Sets of a popular ‘statweb.stanford.edu’ website.As I have analyzed the Indian Country Data, I have introduced Pandas key concepts as below. Before going through this article, have a rough idea of basics from matplotlib and csv." }, { "code": null, "e": 25572, "s": 25515, "text": "InstallationEasiest way to install pandas is to use pip:" }, { "code": null, "e": 25591, "s": 25572, "text": "pip install pandas" }, { "code": null, "e": 25617, "s": 25591, "text": "or, Download it from here" }, { "code": null, "e": 25648, "s": 25617, "text": "Creating A DataFrame in Pandas" }, { "code": null, "e": 25855, "s": 25648, "text": "Creation of dataframe is done by passing multiple Series into the DataFrame class using pd.Series method. Here, it is passed in the two Series objects, s1 as the first row, and s2 as the second row.Example:" }, { "code": "# assigning two series to s1 and s2s1 = pd.Series([1,2])s2 = pd.Series([\"Ashish\", \"Sid\"])# framing series objects into datadf = pd.DataFrame([s1,s2])# show the data framedf # data framing in another way# taking index and column valuesdframe = pd.DataFrame([[1,2],[\"Ashish\", \"Sid\"]], index=[\"r1\", \"r2\"], columns=[\"c1\", \"c2\"])dframe # framing in another way # dict-like containerdframe = pd.DataFrame({ \"c1\": [1, \"Ashish\"], \"c2\": [2, \"Sid\"]})dframe", "e": 26332, "s": 25855, "text": null }, { "code": null, "e": 26340, "s": 26332, "text": "Output:" }, { "code": null, "e": 26373, "s": 26346, "text": "Importing Data with Pandas" }, { "code": null, "e": 26804, "s": 26373, "text": "The first step is to read the data. The data is stored as a comma-separated values, or csv, file, where each row is separated by a new line, and each column by a comma (,). In order to be able to work with the data in Python, it is needed to read the csv file into a Pandas DataFrame. A DataFrame is a way to represent and work with tabular data. Tabular data has rows and columns, just like this csv file(Click Download).Example:" }, { "code": "# Import the pandas library, renamed as pdimport pandas as pd # Read IND_data.csv into a DataFrame, assigned to dfdf = pd.read_csv(\"IND_data.csv\") # Prints the first 5 rows of a DataFrame as defaultdf.head() # Prints no. of rows and columns of a DataFramedf.shape", "e": 27071, "s": 26804, "text": null }, { "code": null, "e": 27079, "s": 27071, "text": "Output:" }, { "code": null, "e": 27088, "s": 27081, "text": "29,10\n" }, { "code": null, "e": 27120, "s": 27088, "text": "Indexing DataFrames with Pandas" }, { "code": null, "e": 27271, "s": 27120, "text": "Indexing can be possible using the pandas.DataFrame.iloc method. The iloc method allows to retrieve as many as rows and columns by position.Examples:" }, { "code": "# prints first 5 rows and every column which replicates df.head()df.iloc[0:5,:]# prints entire rows and columnsdf.iloc[:,:]# prints from 5th rows and first 5 columnsdf.iloc[5:,:5]", "e": 27451, "s": 27271, "text": null }, { "code": null, "e": 27483, "s": 27451, "text": "Indexing Using Labels in Pandas" }, { "code": null, "e": 27623, "s": 27483, "text": "Indexing can be worked with labels using the pandas.DataFrame.loc method, which allows to index using labels instead of positions.Examples:" }, { "code": "# prints first five rows including 5th index and every columns of dfdf.loc[0:5,:]# prints from 5th rows onwards and entire columnsdf = df.loc[5:,:]", "e": 27771, "s": 27623, "text": null }, { "code": null, "e": 28019, "s": 27771, "text": "The above doesn’t actually look much different from df.iloc[0:5,:]. This is because while row labels can take on any values, our row labels match the positions exactly. But column labels can make things much easier when working with data. Example:" }, { "code": "# Prints the first 5 rows of Time period# value df.loc[:5,\"Time period\"]", "e": 28092, "s": 28019, "text": null }, { "code": null, "e": 28121, "s": 28094, "text": "DataFrame Math with Pandas" }, { "code": null, "e": 28217, "s": 28121, "text": "Computation of data frames can be done by using Statistical Functions of pandas tools.Examples:" }, { "code": "# computes various summary statistics, excluding NaN valuesdf.describe()# for computing correlationsdf.corr()# computes numerical data ranksdf.rank()", "e": 28367, "s": 28217, "text": null }, { "code": null, "e": 28390, "s": 28374, "text": "Pandas Plotting" }, { "code": null, "e": 28568, "s": 28390, "text": "Plots in these examples are made using standard convention for referencing the matplotlib API which provides the basics in pandas to easily create decent looking plots.Examples:" }, { "code": "# import the required module import matplotlib.pyplot as plt# plot a histogram df['Observation Value'].hist(bins=10) # shows presence of a lot of outliers/extreme valuesdf.boxplot(column='Observation Value', by = 'Time period') # plotting points as a scatter plotx = df[\"Observation Value\"]y = df[\"Time period\"]plt.scatter(x, y, label= \"stars\", color= \"m\", marker= \"*\", s=30)# x-axis labelplt.xlabel('Observation Value')# frequency labelplt.ylabel('Time period')# function to show the plotplt.show()", "e": 29082, "s": 28568, "text": null }, { "code": null, "e": 29138, "s": 29086, "text": "Data Analysis and Visualization with Python | Set 2" }, { "code": null, "e": 29149, "s": 29138, "text": "Reference:" }, { "code": null, "e": 29208, "s": 29149, "text": "http://pandas.pydata.org/pandas-docs/stable/tutorials.html" }, { "code": null, "e": 29233, "s": 29208, "text": "https://www.datacamp.com" }, { "code": null, "e": 29531, "s": 29233, "text": "This article is contributed by Afzal_Saan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29656, "s": 29531, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29663, "s": 29656, "text": "Python" }, { "code": null, "e": 29761, "s": 29663, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29779, "s": 29761, "text": "Python Dictionary" }, { "code": null, "e": 29814, "s": 29779, "text": "Read a file line by line in Python" }, { "code": null, "e": 29836, "s": 29814, "text": "Enumerate() in Python" }, { "code": null, "e": 29868, "s": 29836, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29898, "s": 29868, "text": "Iterate over a list in Python" }, { "code": null, "e": 29940, "s": 29898, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29966, "s": 29940, "text": "Python String | replace()" }, { "code": null, "e": 30009, "s": 29966, "text": "Python program to convert a list to string" }, { "code": null, "e": 30046, "s": 30009, "text": "Create a Pandas DataFrame from Lists" } ]
How to merge arrays and preserve the keys in PHP ? - GeeksforGeeks
07 Jul, 2020 Arrays in PHP are created using array() function. Arrays are variable that can hold more than one values at a time. There are three types of arrays: Indexed ArraysAssociative ArraysMultidimensional Arrays Indexed Arrays Associative Arrays Multidimensional Arrays Each and every value in an array has a name or identity attached to it used to access that element called keys. To merge the two arrays array_merge() function works fine but it does not preserve the keys. Instead array_replace() function helps to merge two arrays while preserving their key. Program 1: This example using array_replace() function to merge two arrays and preserve the keys. <?php // Create first associative array$array1 = array( 1 => 'Welcome', 2 => 'To'); // Create second associative array$array2 = array( 3 => 'Geeks', 4 => 'For', 5 => 'Geeks'); // Use array_replace() function to// merge the two array while// preserving the keysprint_r(array_replace($array1, $array2));?> Array ( [1] => Welcome [2] => To [3] => Geeks [4] => For [5] => Geeks ) Program 1: This example using array_replace_recursive() function to merge two arrays and preserve the keys. <?php // Create first associative array$array1 = array( 1 => 'Welcome', 2 => 'To'); // Create second associative array$array2 = array( 3 => 'Geeks', 4 => 'For', 5 => 'Geeks'); // Use array_replace() function to// merge the two array while// preserving the keysprint_r(array_replace_recursive($array1, $array2));?> Array ( [1] => Welcome [2] => To [3] => Geeks [4] => For [5] => Geeks ) PHP-Misc Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? How to receive JSON POST with PHP ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP?
[ { "code": null, "e": 24499, "s": 24471, "text": "\n07 Jul, 2020" }, { "code": null, "e": 24648, "s": 24499, "text": "Arrays in PHP are created using array() function. Arrays are variable that can hold more than one values at a time. There are three types of arrays:" }, { "code": null, "e": 24704, "s": 24648, "text": "Indexed ArraysAssociative ArraysMultidimensional Arrays" }, { "code": null, "e": 24719, "s": 24704, "text": "Indexed Arrays" }, { "code": null, "e": 24738, "s": 24719, "text": "Associative Arrays" }, { "code": null, "e": 24762, "s": 24738, "text": "Multidimensional Arrays" }, { "code": null, "e": 24874, "s": 24762, "text": "Each and every value in an array has a name or identity attached to it used to access that element called keys." }, { "code": null, "e": 25054, "s": 24874, "text": "To merge the two arrays array_merge() function works fine but it does not preserve the keys. Instead array_replace() function helps to merge two arrays while preserving their key." }, { "code": null, "e": 25152, "s": 25054, "text": "Program 1: This example using array_replace() function to merge two arrays and preserve the keys." }, { "code": "<?php // Create first associative array$array1 = array( 1 => 'Welcome', 2 => 'To'); // Create second associative array$array2 = array( 3 => 'Geeks', 4 => 'For', 5 => 'Geeks'); // Use array_replace() function to// merge the two array while// preserving the keysprint_r(array_replace($array1, $array2));?>", "e": 25474, "s": 25152, "text": null }, { "code": null, "e": 25567, "s": 25474, "text": "Array\n(\n [1] => Welcome\n [2] => To\n [3] => Geeks\n [4] => For\n [5] => Geeks\n)\n" }, { "code": null, "e": 25675, "s": 25567, "text": "Program 1: This example using array_replace_recursive() function to merge two arrays and preserve the keys." }, { "code": "<?php // Create first associative array$array1 = array( 1 => 'Welcome', 2 => 'To'); // Create second associative array$array2 = array( 3 => 'Geeks', 4 => 'For', 5 => 'Geeks'); // Use array_replace() function to// merge the two array while// preserving the keysprint_r(array_replace_recursive($array1, $array2));?>", "e": 26007, "s": 25675, "text": null }, { "code": null, "e": 26100, "s": 26007, "text": "Array\n(\n [1] => Welcome\n [2] => To\n [3] => Geeks\n [4] => For\n [5] => Geeks\n)\n" }, { "code": null, "e": 26109, "s": 26100, "text": "PHP-Misc" }, { "code": null, "e": 26116, "s": 26109, "text": "Picked" }, { "code": null, "e": 26120, "s": 26116, "text": "PHP" }, { "code": null, "e": 26133, "s": 26120, "text": "PHP Programs" }, { "code": null, "e": 26150, "s": 26133, "text": "Web Technologies" }, { "code": null, "e": 26177, "s": 26150, "text": "Web technologies Questions" }, { "code": null, "e": 26181, "s": 26177, "text": "PHP" }, { "code": null, "e": 26279, "s": 26181, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26288, "s": 26279, "text": "Comments" }, { "code": null, "e": 26301, "s": 26288, "text": "Old Comments" }, { "code": null, "e": 26351, "s": 26301, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26391, "s": 26351, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 26452, "s": 26391, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 26502, "s": 26452, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 26538, "s": 26502, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 26588, "s": 26538, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26628, "s": 26588, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 26680, "s": 26628, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 26741, "s": 26680, "text": "How to Upload Image into Database and Display it using PHP ?" } ]
Complete Beginner’s Guide to Processing Whatsapp Data with Python | by Bobby Muljono | Towards Data Science
From texting your loved ones, sending memes and professional usage, Whatsapp has been dominating the messenger market worldwide with 1.5 billion active monthly users. When it comes to complex NLP modelling, free text is black gold. NLP for businesses provide enhanced user experience ranging from spell-checks, feedback analysis and even virtual assistants. www.wonderflow.co In certain situations, small businesses may create Whatsapp chat groups to relay information between members as a low-cost alternative to setting up systems to log data. Rule-based chat system on how the information is to be disseminated is agreed at the start of the chat. Consider the following example: 21/09/2019, 14:04 — Salesperson A: Item B/Branch C/Sold/$190021/09/2019, 16:12 — Salesperson X: Item Y/Branch Z/Refund/$1600, defect found in product, not functioning We can immediately recognize patterns pertaining to sales order from different salesperson, separated by common operators such as ‘/’ and ‘,’. With a simple system (but prone to human spelling error) like this, we can analyze sales pattern of different products and different locations with the use of Whatsapp. There are many great resources online to convert Whatsapp data into a pandas dataframe. Most, if not all, makes use of Python’s Regex library as a fairly complicated solution to split the text file into columns of the dataframe. However, my objective here is to target Python users who are beginners in string manipulation. For beginners learning Python, we have better familiarity with basic Python methods that does not come from external libraries. In this article, we will be using a lot of the basic methods in processing Whatsapp data into a pandas dataframe. Here is what we will be covering: 2 libraries (pandas for dataframe and datetime to detect datetime objects)A lot of .split() methodsList comprehensionsError-handling 2 libraries (pandas for dataframe and datetime to detect datetime objects) A lot of .split() methods List comprehensions Error-handling If exporting messages directly from your phone is not your jam, you can try the following method: geeknizer.com Otherwise, the easiest way to extract Whatsapp .txt file can be done by the following method: Open your Whatsapp applicationSelect a chat of your interestTap on the ‘...’ > Select ‘More’ > Select ‘Export chat’ without media and send it to your personal e-mail Open your Whatsapp application Select a chat of your interest Tap on the ‘...’ > Select ‘More’ > Select ‘Export chat’ without media and send it to your personal e-mail Once you’re done, your text file should look something like this: 21/09/2019, 23:03 — Friend: my boss dont like filter21/09/2019, 23:03 — Friend: he likes everything on a page21/09/2019, 23:03 — Me: so basically you need to turn your data into ugly first then come out pivot table21/09/2019, 23:03 — Me: haha21/09/2019, 23:04 — Me: pivot table all in 1 page what21/09/2019, 23:05 — Me: but ya i hate this kinda excel work sia21/09/2019, 23:05 — Me: haha21/09/2019, 23:05 — Friend: as in21/09/2019, 23:05 — Me: hope to transition to data scientist asap The first thing we want to do is to make sure we know the location of your text file. Once we know its destination, we can set our working directory to the file’s location: import osos.chdir('C:/Users/Some_Directory/...') Once that is out of the way, we want to define a function to read your text file into a Python variable with the following method: The above function converts our text file into a list of strings that allows us to make use of .split() methods later on. But for now, there is some cleaning you need to do. Sometimes the data you extract may not be in perfect format due to multi-line texts. Consider the following situation using the same salesperson example from above that is already converted into a list: 21/09/2019, 14:04 — Salesperson A: Item B/Branch C/Sold/$1900'Some random text formed by new line from Salesperson A'21/09/2019, 16:12 — Salesperson X: Item Y/Branch Z/Refund/$1600, defect found in product, not functioning We can observe that ‘Some random text’ does not have the same usual format that every line of Whatsapp text should have. To handle such elements, let’s first look at the pattern of Whatsapp text messages. Ignoring everything else after the date, it is obvious that unwanted elements do not have date objects in them. So we begin removing them by checking if they do contain date before the first ‘,’. We do this by utilizing basic error handling-technique. As you can see, we have removed about 100 elements that may pose a hindrance to feature extraction later on. It is just within most of our casual texting culture to not use multi-line texts unless we are sharing links with caption with our buddies! Now this is where you will be using your basic Python skills to extract features from the list that you will parse into a dataframe later on. First, we need to revisit the string pattern from the Whatsapp data. The first feature we would like to extract is the date. Remember that the date string occurs right before the first ‘,’. So we extract the element using the .split(‘,’) method at index 0. We can write this beautifully using Python’s list comprehension. Do note that I came from an R background and I am very used to using ‘i’ in for loops. Another way you can write the above code without using range() function is the following: date = [text.split(‘,’)[0] for text in chat] In contrast, this is what is required using the Regex method just to check whether the string pattern is date. With that out of the way, we may proceed with the same logic when extracting both the time and name of the sender. Take note of the following pattern: Time string occurs right after the first ‘,’ and right before the first ‘-’Name string occurs right after the first ‘-’ followed by the second ‘:’ at index 0 Time string occurs right after the first ‘,’ and right before the first ‘-’ Name string occurs right after the first ‘-’ followed by the second ‘:’ at index 0 Finally we want to extract the content of the message. This is a little bit tricky because certain lines do not contain any messages. Instead, they are system-generated messages depicted by the following: 21/09/2019, 11:03 — Salesperson A created the group "Dummy Chat"21/09/2019, 11:03 — Salesperson A added Salesperson B21/09/2019, 14:04 — Salesperson A: Item B/Branch C/Sold/$190021/09/2019, 16:12 — Salesperson X: Item Y/Branch Z/Refund/$1600, defect found in product, not functioning Notice that there is no additional ‘:’ after the first one that occurred at the time string. To put into perspective, consider the following .split(‘:’) method: chat.split(":")#['21/09/2019, 14','04 — Salesperson A',' Item B/Branch C/Sold/$1900'] The element at index 2 is of interest to us. However, since system-generated messages do not contain the second ‘:’, extracting information at index 2 will produce an error. Therefore we will proceed with our second error-handling technique. You may choose to remove elements with ‘Missing Text’ later on. Now that we have 4 lists of features, we can finally create a pandas dataframe with a single line of code! And voila! Your data frame is ready for post-analysis! Notice the system-generated message that appear on the name column. You can conditionally remove rows with system generated message with the following code: df = df[df[‘Content’] != ‘Missing Text’] There are many ways you can make use of a processed Whatsapp text data to conduct your analysis. From recreating yourself as a bot, using NLP for sentiment analysis to just plain simple analytics. Making use of Whatsapp data is great practice for any complex NLP projects to come. Basic string manipulation is enough to convert a text file into a pandas dataframe as shown above. If you are a newbie with Python(like me), it is better to get used to the basics than trying out new techniques that may prove a little overwhelming at first. However, Python’s regex library is still an important tool for intermediate to advanced uses of text mining and data validation. Here is a great article explaining the concepts of the Regex library in Python along with its potential uses for data analytics and data science:
[ { "code": null, "e": 279, "s": 47, "text": "From texting your loved ones, sending memes and professional usage, Whatsapp has been dominating the messenger market worldwide with 1.5 billion active monthly users. When it comes to complex NLP modelling, free text is black gold." }, { "code": null, "e": 405, "s": 279, "text": "NLP for businesses provide enhanced user experience ranging from spell-checks, feedback analysis and even virtual assistants." }, { "code": null, "e": 423, "s": 405, "text": "www.wonderflow.co" }, { "code": null, "e": 729, "s": 423, "text": "In certain situations, small businesses may create Whatsapp chat groups to relay information between members as a low-cost alternative to setting up systems to log data. Rule-based chat system on how the information is to be disseminated is agreed at the start of the chat. Consider the following example:" }, { "code": null, "e": 896, "s": 729, "text": "21/09/2019, 14:04 — Salesperson A: Item B/Branch C/Sold/$190021/09/2019, 16:12 — Salesperson X: Item Y/Branch Z/Refund/$1600, defect found in product, not functioning" }, { "code": null, "e": 1208, "s": 896, "text": "We can immediately recognize patterns pertaining to sales order from different salesperson, separated by common operators such as ‘/’ and ‘,’. With a simple system (but prone to human spelling error) like this, we can analyze sales pattern of different products and different locations with the use of Whatsapp." }, { "code": null, "e": 1437, "s": 1208, "text": "There are many great resources online to convert Whatsapp data into a pandas dataframe. Most, if not all, makes use of Python’s Regex library as a fairly complicated solution to split the text file into columns of the dataframe." }, { "code": null, "e": 1774, "s": 1437, "text": "However, my objective here is to target Python users who are beginners in string manipulation. For beginners learning Python, we have better familiarity with basic Python methods that does not come from external libraries. In this article, we will be using a lot of the basic methods in processing Whatsapp data into a pandas dataframe." }, { "code": null, "e": 1808, "s": 1774, "text": "Here is what we will be covering:" }, { "code": null, "e": 1941, "s": 1808, "text": "2 libraries (pandas for dataframe and datetime to detect datetime objects)A lot of .split() methodsList comprehensionsError-handling" }, { "code": null, "e": 2016, "s": 1941, "text": "2 libraries (pandas for dataframe and datetime to detect datetime objects)" }, { "code": null, "e": 2042, "s": 2016, "text": "A lot of .split() methods" }, { "code": null, "e": 2062, "s": 2042, "text": "List comprehensions" }, { "code": null, "e": 2077, "s": 2062, "text": "Error-handling" }, { "code": null, "e": 2175, "s": 2077, "text": "If exporting messages directly from your phone is not your jam, you can try the following method:" }, { "code": null, "e": 2189, "s": 2175, "text": "geeknizer.com" }, { "code": null, "e": 2283, "s": 2189, "text": "Otherwise, the easiest way to extract Whatsapp .txt file can be done by the following method:" }, { "code": null, "e": 2449, "s": 2283, "text": "Open your Whatsapp applicationSelect a chat of your interestTap on the ‘...’ > Select ‘More’ > Select ‘Export chat’ without media and send it to your personal e-mail" }, { "code": null, "e": 2480, "s": 2449, "text": "Open your Whatsapp application" }, { "code": null, "e": 2511, "s": 2480, "text": "Select a chat of your interest" }, { "code": null, "e": 2617, "s": 2511, "text": "Tap on the ‘...’ > Select ‘More’ > Select ‘Export chat’ without media and send it to your personal e-mail" }, { "code": null, "e": 2683, "s": 2617, "text": "Once you’re done, your text file should look something like this:" }, { "code": null, "e": 3169, "s": 2683, "text": "21/09/2019, 23:03 — Friend: my boss dont like filter21/09/2019, 23:03 — Friend: he likes everything on a page21/09/2019, 23:03 — Me: so basically you need to turn your data into ugly first then come out pivot table21/09/2019, 23:03 — Me: haha21/09/2019, 23:04 — Me: pivot table all in 1 page what21/09/2019, 23:05 — Me: but ya i hate this kinda excel work sia21/09/2019, 23:05 — Me: haha21/09/2019, 23:05 — Friend: as in21/09/2019, 23:05 — Me: hope to transition to data scientist asap" }, { "code": null, "e": 3342, "s": 3169, "text": "The first thing we want to do is to make sure we know the location of your text file. Once we know its destination, we can set our working directory to the file’s location:" }, { "code": null, "e": 3391, "s": 3342, "text": "import osos.chdir('C:/Users/Some_Directory/...')" }, { "code": null, "e": 3522, "s": 3391, "text": "Once that is out of the way, we want to define a function to read your text file into a Python variable with the following method:" }, { "code": null, "e": 3696, "s": 3522, "text": "The above function converts our text file into a list of strings that allows us to make use of .split() methods later on. But for now, there is some cleaning you need to do." }, { "code": null, "e": 3899, "s": 3696, "text": "Sometimes the data you extract may not be in perfect format due to multi-line texts. Consider the following situation using the same salesperson example from above that is already converted into a list:" }, { "code": null, "e": 4122, "s": 3899, "text": "21/09/2019, 14:04 — Salesperson A: Item B/Branch C/Sold/$1900'Some random text formed by new line from Salesperson A'21/09/2019, 16:12 — Salesperson X: Item Y/Branch Z/Refund/$1600, defect found in product, not functioning" }, { "code": null, "e": 4327, "s": 4122, "text": "We can observe that ‘Some random text’ does not have the same usual format that every line of Whatsapp text should have. To handle such elements, let’s first look at the pattern of Whatsapp text messages." }, { "code": null, "e": 4579, "s": 4327, "text": "Ignoring everything else after the date, it is obvious that unwanted elements do not have date objects in them. So we begin removing them by checking if they do contain date before the first ‘,’. We do this by utilizing basic error handling-technique." }, { "code": null, "e": 4828, "s": 4579, "text": "As you can see, we have removed about 100 elements that may pose a hindrance to feature extraction later on. It is just within most of our casual texting culture to not use multi-line texts unless we are sharing links with caption with our buddies!" }, { "code": null, "e": 5039, "s": 4828, "text": "Now this is where you will be using your basic Python skills to extract features from the list that you will parse into a dataframe later on. First, we need to revisit the string pattern from the Whatsapp data." }, { "code": null, "e": 5292, "s": 5039, "text": "The first feature we would like to extract is the date. Remember that the date string occurs right before the first ‘,’. So we extract the element using the .split(‘,’) method at index 0. We can write this beautifully using Python’s list comprehension." }, { "code": null, "e": 5469, "s": 5292, "text": "Do note that I came from an R background and I am very used to using ‘i’ in for loops. Another way you can write the above code without using range() function is the following:" }, { "code": null, "e": 5514, "s": 5469, "text": "date = [text.split(‘,’)[0] for text in chat]" }, { "code": null, "e": 5625, "s": 5514, "text": "In contrast, this is what is required using the Regex method just to check whether the string pattern is date." }, { "code": null, "e": 5776, "s": 5625, "text": "With that out of the way, we may proceed with the same logic when extracting both the time and name of the sender. Take note of the following pattern:" }, { "code": null, "e": 5934, "s": 5776, "text": "Time string occurs right after the first ‘,’ and right before the first ‘-’Name string occurs right after the first ‘-’ followed by the second ‘:’ at index 0" }, { "code": null, "e": 6010, "s": 5934, "text": "Time string occurs right after the first ‘,’ and right before the first ‘-’" }, { "code": null, "e": 6093, "s": 6010, "text": "Name string occurs right after the first ‘-’ followed by the second ‘:’ at index 0" }, { "code": null, "e": 6298, "s": 6093, "text": "Finally we want to extract the content of the message. This is a little bit tricky because certain lines do not contain any messages. Instead, they are system-generated messages depicted by the following:" }, { "code": null, "e": 6582, "s": 6298, "text": "21/09/2019, 11:03 — Salesperson A created the group \"Dummy Chat\"21/09/2019, 11:03 — Salesperson A added Salesperson B21/09/2019, 14:04 — Salesperson A: Item B/Branch C/Sold/$190021/09/2019, 16:12 — Salesperson X: Item Y/Branch Z/Refund/$1600, defect found in product, not functioning" }, { "code": null, "e": 6743, "s": 6582, "text": "Notice that there is no additional ‘:’ after the first one that occurred at the time string. To put into perspective, consider the following .split(‘:’) method:" }, { "code": null, "e": 6829, "s": 6743, "text": "chat.split(\":\")#['21/09/2019, 14','04 — Salesperson A',' Item B/Branch C/Sold/$1900']" }, { "code": null, "e": 7071, "s": 6829, "text": "The element at index 2 is of interest to us. However, since system-generated messages do not contain the second ‘:’, extracting information at index 2 will produce an error. Therefore we will proceed with our second error-handling technique." }, { "code": null, "e": 7135, "s": 7071, "text": "You may choose to remove elements with ‘Missing Text’ later on." }, { "code": null, "e": 7242, "s": 7135, "text": "Now that we have 4 lists of features, we can finally create a pandas dataframe with a single line of code!" }, { "code": null, "e": 7454, "s": 7242, "text": "And voila! Your data frame is ready for post-analysis! Notice the system-generated message that appear on the name column. You can conditionally remove rows with system generated message with the following code:" }, { "code": null, "e": 7495, "s": 7454, "text": "df = df[df[‘Content’] != ‘Missing Text’]" }, { "code": null, "e": 7776, "s": 7495, "text": "There are many ways you can make use of a processed Whatsapp text data to conduct your analysis. From recreating yourself as a bot, using NLP for sentiment analysis to just plain simple analytics. Making use of Whatsapp data is great practice for any complex NLP projects to come." }, { "code": null, "e": 8163, "s": 7776, "text": "Basic string manipulation is enough to convert a text file into a pandas dataframe as shown above. If you are a newbie with Python(like me), it is better to get used to the basics than trying out new techniques that may prove a little overwhelming at first. However, Python’s regex library is still an important tool for intermediate to advanced uses of text mining and data validation." } ]
How to create a Zebra Stripes table effect using jQuery ? - GeeksforGeeks
24 Jan, 2021 Given an HTML document with a table and the task is to create a Zebra Stripes table effect on the table using jQuery. Approach : To achieve the Zebra Stripes table effect, use the below code snippet: $(function() { $("table tr:nth-child(odd)").addClass("zebrastripe"); }); In the above function, zebrastripe is the class name used and odd depicts that odd number of rows will have colored stripes. To change the even row stripes just use : $(function() { $("table tr:nth-child(even)").addClass("zebrastripe"); }) In the below demonstration of the above approach the jQuery-3.5.1.js contains the source code. Example: Below is the demonstration of the above approach. HTML <html> <head> <title>jQuery Zebra Stripes Demonstration</title> <script type="text/javascript" src= "https://code.jquery.com/jquery-3.5.1.js"> </script> <script type="text/javascript"> $(function() { $("table tr:nth-child(odd)") .addClass("zebrastripe"); }); </script> <style type="text/css"> body, td { font-size: 10pt; text-align: center; } h1 { color: green; } table { background-color: black; border: 1px black solid; border-collapse: collapse; } th { font-size: 15px; padding: 5px 8px; border: 1px outset silver; background-color: rgb(197, 69, 69); color: white; } tr { border: 1px outset silver; padding: 5px 8px; background-color: white; margin: 1px; } tr.zebrastripe { background-color: green; } td { border: 0.5px outset silver; border-collapse: collapse; padding: 5px 8px; } .center { margin-left: auto; margin-right: auto; } </style></head> <body> <h1> GeeksforGeeks </h1> <table class="center"> <tr> <th>ID</th> <th>Course</th> <th>Price</th> </tr> <tr> <td>1</td> <td>Fork CPP</td> <td>Free</td> </tr> <tr> <td>2</td> <td>DSA</td> <td>2499</td> </tr> <tr> <td>3</td> <td>Fork Java</td> <td>Free</td> </tr> <tr> <td>5</td> <td>Linux</td> <td>599</td> </tr> <tr> <td>6</td> <td>Fork Python</td> <td>Free</td> </tr> </table></body> </html> Output: Output of the above demonstration Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc jQuery-Misc Picked CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to Create Time-Table schedule using HTML ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25461, "s": 25433, "text": "\n24 Jan, 2021" }, { "code": null, "e": 25579, "s": 25461, "text": "Given an HTML document with a table and the task is to create a Zebra Stripes table effect on the table using jQuery." }, { "code": null, "e": 25661, "s": 25579, "text": "Approach : To achieve the Zebra Stripes table effect, use the below code snippet:" }, { "code": null, "e": 25738, "s": 25661, "text": "$(function() {\n $(\"table tr:nth-child(odd)\").addClass(\"zebrastripe\");\n});" }, { "code": null, "e": 25863, "s": 25738, "text": "In the above function, zebrastripe is the class name used and odd depicts that odd number of rows will have colored stripes." }, { "code": null, "e": 25906, "s": 25863, "text": "To change the even row stripes just use : " }, { "code": null, "e": 25983, "s": 25906, "text": "$(function() {\n $(\"table tr:nth-child(even)\").addClass(\"zebrastripe\");\n})" }, { "code": null, "e": 26078, "s": 25983, "text": "In the below demonstration of the above approach the jQuery-3.5.1.js contains the source code." }, { "code": null, "e": 26137, "s": 26078, "text": "Example: Below is the demonstration of the above approach." }, { "code": null, "e": 26142, "s": 26137, "text": "HTML" }, { "code": "<html> <head> <title>jQuery Zebra Stripes Demonstration</title> <script type=\"text/javascript\" src= \"https://code.jquery.com/jquery-3.5.1.js\"> </script> <script type=\"text/javascript\"> $(function() { $(\"table tr:nth-child(odd)\") .addClass(\"zebrastripe\"); }); </script> <style type=\"text/css\"> body, td { font-size: 10pt; text-align: center; } h1 { color: green; } table { background-color: black; border: 1px black solid; border-collapse: collapse; } th { font-size: 15px; padding: 5px 8px; border: 1px outset silver; background-color: rgb(197, 69, 69); color: white; } tr { border: 1px outset silver; padding: 5px 8px; background-color: white; margin: 1px; } tr.zebrastripe { background-color: green; } td { border: 0.5px outset silver; border-collapse: collapse; padding: 5px 8px; } .center { margin-left: auto; margin-right: auto; } </style></head> <body> <h1> GeeksforGeeks </h1> <table class=\"center\"> <tr> <th>ID</th> <th>Course</th> <th>Price</th> </tr> <tr> <td>1</td> <td>Fork CPP</td> <td>Free</td> </tr> <tr> <td>2</td> <td>DSA</td> <td>2499</td> </tr> <tr> <td>3</td> <td>Fork Java</td> <td>Free</td> </tr> <tr> <td>5</td> <td>Linux</td> <td>599</td> </tr> <tr> <td>6</td> <td>Fork Python</td> <td>Free</td> </tr> </table></body> </html>", "e": 28190, "s": 26142, "text": null }, { "code": null, "e": 28198, "s": 28190, "text": "Output:" }, { "code": null, "e": 28232, "s": 28198, "text": "Output of the above demonstration" }, { "code": null, "e": 28369, "s": 28232, "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": 28378, "s": 28369, "text": "CSS-Misc" }, { "code": null, "e": 28388, "s": 28378, "text": "HTML-Misc" }, { "code": null, "e": 28400, "s": 28388, "text": "jQuery-Misc" }, { "code": null, "e": 28407, "s": 28400, "text": "Picked" }, { "code": null, "e": 28411, "s": 28407, "text": "CSS" }, { "code": null, "e": 28416, "s": 28411, "text": "HTML" }, { "code": null, "e": 28423, "s": 28416, "text": "JQuery" }, { "code": null, "e": 28440, "s": 28423, "text": "Web Technologies" }, { "code": null, "e": 28445, "s": 28440, "text": "HTML" }, { "code": null, "e": 28543, "s": 28445, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28580, "s": 28543, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28609, "s": 28580, "text": "Form validation using jQuery" }, { "code": null, "e": 28648, "s": 28609, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 28690, "s": 28648, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28737, "s": 28690, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 28797, "s": 28737, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28858, "s": 28797, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28911, "s": 28858, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 28961, "s": 28911, "text": "How to Insert Form Data into Database using PHP ?" } ]
C program to input an array from a sequence of space-separated integers - GeeksforGeeks
15 Jul, 2021 Given a string S consisting of space-separated integers, the task is to write a C program to take the integers as input from the string S and store them in an array arr[]. Examples: Input: S = “1 2 3 4”Output: {1, 2, 3, 4} Input: S = “32 12”Output: {32, 12} Approach: The idea is to solve the given problem is to use getchar() function to check if a ‘\n’ (newline) occurs is found while taking input and then stop the input. Follow the step below to solve the given problem: Initialize a variable, say count, which is used to store the index of the array element. Initialize an array arr[] of size 106 to store the elements into the array. Iterate using a do-while loop until newLine occurs and perform the following steps:Store the current value at index count as scanf(“%d “, &arr[count]); and increment the value of count.If the next character is not endline, then continue. Otherwise, break out of the loop. Store the current value at index count as scanf(“%d “, &arr[count]); and increment the value of count. If the next character is not endline, then continue. Otherwise, break out of the loop. After completing the above steps, print the elements stored in the array. Below is the implementation of the above approach: C // C program for the above approach#include <stdio.h> // Driver Codeint main(){ // Stores the index where the // element is to be inserted int count = 0; // Initialize an array int a[1000000]; // Perform a do-while loop do { // Take input at position count // and increment count scanf("%d", &a[count++]); // If '\n' (newline) has occurred // or the whole array is filled, // then exit the loop // Otherwise, continue } while (getchar() != '\n' && count < 100); // Resize the array size to count a[count]; // Print the array elements for (int i = 0; i < count; i++) { printf("%d, ", a[i]); } return 0;} Output: akshaysingh98088 arorakashish0911 c-input-output Arrays C Programs Strings Technical Scripter Arrays Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Reversal algorithm for array rotation Building Heap from Array Move all negative numbers to beginning and positive to end with constant extra space Strings in C Arrow operator -> in C/C++ with Examples UDP Server-Client implementation in C C Program to read contents of Whole File Header files in C/C++ and its uses
[ { "code": null, "e": 24796, "s": 24768, "text": "\n15 Jul, 2021" }, { "code": null, "e": 24968, "s": 24796, "text": "Given a string S consisting of space-separated integers, the task is to write a C program to take the integers as input from the string S and store them in an array arr[]." }, { "code": null, "e": 24978, "s": 24968, "text": "Examples:" }, { "code": null, "e": 25019, "s": 24978, "text": "Input: S = “1 2 3 4”Output: {1, 2, 3, 4}" }, { "code": null, "e": 25054, "s": 25019, "text": "Input: S = “32 12”Output: {32, 12}" }, { "code": null, "e": 25271, "s": 25054, "text": "Approach: The idea is to solve the given problem is to use getchar() function to check if a ‘\\n’ (newline) occurs is found while taking input and then stop the input. Follow the step below to solve the given problem:" }, { "code": null, "e": 25360, "s": 25271, "text": "Initialize a variable, say count, which is used to store the index of the array element." }, { "code": null, "e": 25436, "s": 25360, "text": "Initialize an array arr[] of size 106 to store the elements into the array." }, { "code": null, "e": 25708, "s": 25436, "text": "Iterate using a do-while loop until newLine occurs and perform the following steps:Store the current value at index count as scanf(“%d “, &arr[count]); and increment the value of count.If the next character is not endline, then continue. Otherwise, break out of the loop." }, { "code": null, "e": 25811, "s": 25708, "text": "Store the current value at index count as scanf(“%d “, &arr[count]); and increment the value of count." }, { "code": null, "e": 25898, "s": 25811, "text": "If the next character is not endline, then continue. Otherwise, break out of the loop." }, { "code": null, "e": 25972, "s": 25898, "text": "After completing the above steps, print the elements stored in the array." }, { "code": null, "e": 26023, "s": 25972, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26025, "s": 26023, "text": "C" }, { "code": "// C program for the above approach#include <stdio.h> // Driver Codeint main(){ // Stores the index where the // element is to be inserted int count = 0; // Initialize an array int a[1000000]; // Perform a do-while loop do { // Take input at position count // and increment count scanf(\"%d\", &a[count++]); // If '\\n' (newline) has occurred // or the whole array is filled, // then exit the loop // Otherwise, continue } while (getchar() != '\\n' && count < 100); // Resize the array size to count a[count]; // Print the array elements for (int i = 0; i < count; i++) { printf(\"%d, \", a[i]); } return 0;}", "e": 26734, "s": 26025, "text": null }, { "code": null, "e": 26742, "s": 26734, "text": "Output:" }, { "code": null, "e": 26759, "s": 26742, "text": "akshaysingh98088" }, { "code": null, "e": 26776, "s": 26759, "text": "arorakashish0911" }, { "code": null, "e": 26791, "s": 26776, "text": "c-input-output" }, { "code": null, "e": 26798, "s": 26791, "text": "Arrays" }, { "code": null, "e": 26809, "s": 26798, "text": "C Programs" }, { "code": null, "e": 26817, "s": 26809, "text": "Strings" }, { "code": null, "e": 26836, "s": 26817, "text": "Technical Scripter" }, { "code": null, "e": 26843, "s": 26836, "text": "Arrays" }, { "code": null, "e": 26851, "s": 26843, "text": "Strings" }, { "code": null, "e": 26949, "s": 26851, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26974, "s": 26949, "text": "Window Sliding Technique" }, { "code": null, "e": 26994, "s": 26974, "text": "Trapping Rain Water" }, { "code": null, "e": 27032, "s": 26994, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 27057, "s": 27032, "text": "Building Heap from Array" }, { "code": null, "e": 27142, "s": 27057, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 27155, "s": 27142, "text": "Strings in C" }, { "code": null, "e": 27196, "s": 27155, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27234, "s": 27196, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27275, "s": 27234, "text": "C Program to read contents of Whole File" } ]
Python Assert Statement — Everything You Need To Know Explained in 5 Minutes | by Dario Radečić | Towards Data Science
Being an interpreted and dynamically-typed language, Python has a bad reputation for unexpected and hard-to-track bugs. The assert statement could save you a nerve or two. It’s a go-to way of catching things that shouldn’t happen early on, most likely at the beginning of a function. It’s a simple boolean expression that checks if a condition returns true. If so, nothing happens. If not, the script raises an AssertionError with an optional message. Keep in mind — assertion is not a replacement for exception handling. You should use try except blocks for any error that’s bound to happen at some point. Use assertion for ones that shouldn’t happen. Don’t feel like reading? Check out my video on the topic: As you would imagine, the assert keyword is built into Python. It must be followed by a condition, and you can optionally put a message that gets printed if the condition evaluates to false. Here’s the syntax: assert <condition>, <optional error message> So for example, Megan can’t enter the club if she’s underage: assert age > 18, 'Go home, Megan.' Let’s leave Megan alone for now and focus on an even simpler example. We have a variable x which is set to 1. Let’s assert it and see what happens: x = 1assert x == 1 Here’s the output: Literally nothing happens. That’s because the condition evaluated to true, so no error was raised. Let’s change the code slightly: x = 1assert x == 2 The output is different this time: You’ve got an AssertionError because the condition evaluated to false — x is 1, so it can’t be 2. The console output provided no explanation, which probably isn’t what you want. You can specify the error message that gets printed if AssertionError is raised: x = 1assert x == 2, 'X should be 1' Here’s the output: Easy, right? It should be. In reality, you’re far more likely to write assert statements at the beginning of a function. Let’s see how to do that next. Let’s declare a simple Python function. It will take in a list as an argument, sum it, and then return the sum as a float. There are two problems you want to catch early on: Is the list passed to the function? You can use type hints in Python to indicate which data type should be passed, but no one’s stopping you to pass a dictionary instead of a list. Hints are just that — hints.Is the list empty? You can’t sum an empty list, obviously. Well, calling sum([]) returns 0, but that’s not what you want. Is the list passed to the function? You can use type hints in Python to indicate which data type should be passed, but no one’s stopping you to pass a dictionary instead of a list. Hints are just that — hints. Is the list empty? You can’t sum an empty list, obviously. Well, calling sum([]) returns 0, but that’s not what you want. That’s why you’ll have two assertion statements, followed by a piece of code for summing up list elements. Python interpreter won’t get to that code if both conditions don’t evaluate to true: def sum_list(lst: list) -> float: assert type(lst) == list, 'Param `lst` must be of type list!' assert len(lst), 'The input list is empty!' total = 0 for item in lst: total += item return total Let’s now try to call sum_list() and pass in a dictionary: lst_sum = sum_list(lst={'a': 1, 'b': 4})print(lst_sum) Here’s what happens: Just what you wanted — a list wasn’t provided to the function, so an appropriate assertion error was printed to the console. What if you pass an empty list? lst_sum = sum_list(lst=[])print(lst_sum) You still get the AssertionError, but this time with a different message. And finally, let’s verify the function works correctly by providing a list of numbers: lst_sum = sum_list([1.11, 2.21, 3.14])print(lst_sum) And there you have it, works as advertised. What’s particularly neat about assert statements is that you can ignore them when running the scripts, without modifying the code. Here’s how you’d run a Python script normally: python3 script.py If you have asserts statements and want to ignore them, simply add the -O to the command: python3 -O script.py Here’s an example of our assertion.py file with the following code inside (you’ve declared the sum_list() function earlier): lst_sum = sum_list(lst={'a': 1, 'b': 4})print(lst_sum) As you can see, the TypeError was raised because the dictionary was passed instead of a list. I’ve told it before, but I’ll repeat once again — assertion isn’t a replacement for try except blocks. You should always use try except for errors that will inevitably happen. Still, assert statements have at least two things going for them. assert is more compact and readable than if. It’s easier to write assert <condition>, <message> than if <condition>: <message>. At least it will save you a line of code. Also, by writing assert you know you’re checking for cases that shouldn’t happen. if is just a generic check. assert statements can be ignored at runtime. You’ve already seen how to do this, so I won’t repeat myself. To summarize, assert is faster to write and easier to distinguish from your regular condition checks. Use them well, but never as the only approach to exception handling. What do you guys think of assert statements? Are they a part of your Python projects, or do you get around with if’s and try except?. Please let me know in the comment section below. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Sign up for my newsletter Subscribe on YouTube Connect on LinkedIn
[ { "code": null, "e": 331, "s": 47, "text": "Being an interpreted and dynamically-typed language, Python has a bad reputation for unexpected and hard-to-track bugs. The assert statement could save you a nerve or two. It’s a go-to way of catching things that shouldn’t happen early on, most likely at the beginning of a function." }, { "code": null, "e": 499, "s": 331, "text": "It’s a simple boolean expression that checks if a condition returns true. If so, nothing happens. If not, the script raises an AssertionError with an optional message." }, { "code": null, "e": 700, "s": 499, "text": "Keep in mind — assertion is not a replacement for exception handling. You should use try except blocks for any error that’s bound to happen at some point. Use assertion for ones that shouldn’t happen." }, { "code": null, "e": 758, "s": 700, "text": "Don’t feel like reading? Check out my video on the topic:" }, { "code": null, "e": 949, "s": 758, "text": "As you would imagine, the assert keyword is built into Python. It must be followed by a condition, and you can optionally put a message that gets printed if the condition evaluates to false." }, { "code": null, "e": 968, "s": 949, "text": "Here’s the syntax:" }, { "code": null, "e": 1013, "s": 968, "text": "assert <condition>, <optional error message>" }, { "code": null, "e": 1075, "s": 1013, "text": "So for example, Megan can’t enter the club if she’s underage:" }, { "code": null, "e": 1110, "s": 1075, "text": "assert age > 18, 'Go home, Megan.'" }, { "code": null, "e": 1258, "s": 1110, "text": "Let’s leave Megan alone for now and focus on an even simpler example. We have a variable x which is set to 1. Let’s assert it and see what happens:" }, { "code": null, "e": 1277, "s": 1258, "text": "x = 1assert x == 1" }, { "code": null, "e": 1296, "s": 1277, "text": "Here’s the output:" }, { "code": null, "e": 1427, "s": 1296, "text": "Literally nothing happens. That’s because the condition evaluated to true, so no error was raised. Let’s change the code slightly:" }, { "code": null, "e": 1446, "s": 1427, "text": "x = 1assert x == 2" }, { "code": null, "e": 1481, "s": 1446, "text": "The output is different this time:" }, { "code": null, "e": 1740, "s": 1481, "text": "You’ve got an AssertionError because the condition evaluated to false — x is 1, so it can’t be 2. The console output provided no explanation, which probably isn’t what you want. You can specify the error message that gets printed if AssertionError is raised:" }, { "code": null, "e": 1776, "s": 1740, "text": "x = 1assert x == 2, 'X should be 1'" }, { "code": null, "e": 1795, "s": 1776, "text": "Here’s the output:" }, { "code": null, "e": 1947, "s": 1795, "text": "Easy, right? It should be. In reality, you’re far more likely to write assert statements at the beginning of a function. Let’s see how to do that next." }, { "code": null, "e": 2121, "s": 1947, "text": "Let’s declare a simple Python function. It will take in a list as an argument, sum it, and then return the sum as a float. There are two problems you want to catch early on:" }, { "code": null, "e": 2452, "s": 2121, "text": "Is the list passed to the function? You can use type hints in Python to indicate which data type should be passed, but no one’s stopping you to pass a dictionary instead of a list. Hints are just that — hints.Is the list empty? You can’t sum an empty list, obviously. Well, calling sum([]) returns 0, but that’s not what you want." }, { "code": null, "e": 2662, "s": 2452, "text": "Is the list passed to the function? You can use type hints in Python to indicate which data type should be passed, but no one’s stopping you to pass a dictionary instead of a list. Hints are just that — hints." }, { "code": null, "e": 2784, "s": 2662, "text": "Is the list empty? You can’t sum an empty list, obviously. Well, calling sum([]) returns 0, but that’s not what you want." }, { "code": null, "e": 2976, "s": 2784, "text": "That’s why you’ll have two assertion statements, followed by a piece of code for summing up list elements. Python interpreter won’t get to that code if both conditions don’t evaluate to true:" }, { "code": null, "e": 3197, "s": 2976, "text": "def sum_list(lst: list) -> float: assert type(lst) == list, 'Param `lst` must be of type list!' assert len(lst), 'The input list is empty!' total = 0 for item in lst: total += item return total" }, { "code": null, "e": 3256, "s": 3197, "text": "Let’s now try to call sum_list() and pass in a dictionary:" }, { "code": null, "e": 3311, "s": 3256, "text": "lst_sum = sum_list(lst={'a': 1, 'b': 4})print(lst_sum)" }, { "code": null, "e": 3332, "s": 3311, "text": "Here’s what happens:" }, { "code": null, "e": 3457, "s": 3332, "text": "Just what you wanted — a list wasn’t provided to the function, so an appropriate assertion error was printed to the console." }, { "code": null, "e": 3489, "s": 3457, "text": "What if you pass an empty list?" }, { "code": null, "e": 3530, "s": 3489, "text": "lst_sum = sum_list(lst=[])print(lst_sum)" }, { "code": null, "e": 3604, "s": 3530, "text": "You still get the AssertionError, but this time with a different message." }, { "code": null, "e": 3691, "s": 3604, "text": "And finally, let’s verify the function works correctly by providing a list of numbers:" }, { "code": null, "e": 3744, "s": 3691, "text": "lst_sum = sum_list([1.11, 2.21, 3.14])print(lst_sum)" }, { "code": null, "e": 3788, "s": 3744, "text": "And there you have it, works as advertised." }, { "code": null, "e": 3919, "s": 3788, "text": "What’s particularly neat about assert statements is that you can ignore them when running the scripts, without modifying the code." }, { "code": null, "e": 3966, "s": 3919, "text": "Here’s how you’d run a Python script normally:" }, { "code": null, "e": 3984, "s": 3966, "text": "python3 script.py" }, { "code": null, "e": 4074, "s": 3984, "text": "If you have asserts statements and want to ignore them, simply add the -O to the command:" }, { "code": null, "e": 4095, "s": 4074, "text": "python3 -O script.py" }, { "code": null, "e": 4220, "s": 4095, "text": "Here’s an example of our assertion.py file with the following code inside (you’ve declared the sum_list() function earlier):" }, { "code": null, "e": 4275, "s": 4220, "text": "lst_sum = sum_list(lst={'a': 1, 'b': 4})print(lst_sum)" }, { "code": null, "e": 4369, "s": 4275, "text": "As you can see, the TypeError was raised because the dictionary was passed instead of a list." }, { "code": null, "e": 4545, "s": 4369, "text": "I’ve told it before, but I’ll repeat once again — assertion isn’t a replacement for try except blocks. You should always use try except for errors that will inevitably happen." }, { "code": null, "e": 4611, "s": 4545, "text": "Still, assert statements have at least two things going for them." }, { "code": null, "e": 4891, "s": 4611, "text": "assert is more compact and readable than if. It’s easier to write assert <condition>, <message> than if <condition>: <message>. At least it will save you a line of code. Also, by writing assert you know you’re checking for cases that shouldn’t happen. if is just a generic check." }, { "code": null, "e": 4998, "s": 4891, "text": "assert statements can be ignored at runtime. You’ve already seen how to do this, so I won’t repeat myself." }, { "code": null, "e": 5169, "s": 4998, "text": "To summarize, assert is faster to write and easier to distinguish from your regular condition checks. Use them well, but never as the only approach to exception handling." }, { "code": null, "e": 5352, "s": 5169, "text": "What do you guys think of assert statements? Are they a part of your Python projects, or do you get around with if’s and try except?. Please let me know in the comment section below." }, { "code": null, "e": 5535, "s": 5352, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 5546, "s": 5535, "text": "medium.com" }, { "code": null, "e": 5572, "s": 5546, "text": "Sign up for my newsletter" }, { "code": null, "e": 5593, "s": 5572, "text": "Subscribe on YouTube" } ]
Find all pairs that sum to a target value in JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first argument and a target sum number as the second argument. The function should return an array of all those pair of numbers from the array that add up to the target sum specified by the second argument. We will use a map object to check for the pairs and push the desired pairs to a new array. The code for this will be − const arr = [7, 0, -4, 5, 2, 3]; const allTwoSum = (arr, target) => { const map = {}; const results = []; for (let i = 0; i < arr.length; i++) { if (map[arr[i]]) { results.push([target − arr[i], arr[i]]); continue; }; map[target − arr[i]] = true; }; return results; }; console.log(allTwoSum(arr, 5)); And the output in the console will be − [ [ 0, 5 ], [ 2, 3 ] ]
[ { "code": null, "e": 1213, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of numbers as the first argument and a target sum number as the second argument." }, { "code": null, "e": 1357, "s": 1213, "text": "The function should return an array of all those pair of numbers from the array that add up to the target sum specified by the second argument." }, { "code": null, "e": 1448, "s": 1357, "text": "We will use a map object to check for the pairs and push the desired pairs to a new array." }, { "code": null, "e": 1476, "s": 1448, "text": "The code for this will be −" }, { "code": null, "e": 1828, "s": 1476, "text": "const arr = [7, 0, -4, 5, 2, 3];\nconst allTwoSum = (arr, target) => {\n const map = {};\n const results = [];\n for (let i = 0; i < arr.length; i++) {\n if (map[arr[i]]) {\n results.push([target − arr[i], arr[i]]);\n continue;\n };\n map[target − arr[i]] = true;\n };\n return results;\n};\nconsole.log(allTwoSum(arr, 5));" }, { "code": null, "e": 1868, "s": 1828, "text": "And the output in the console will be −" }, { "code": null, "e": 1891, "s": 1868, "text": "[ [ 0, 5 ], [ 2, 3 ] ]" } ]
What is a copy constructor in C#?
Copy Constructor creates an object by copying variables from another object. Let us see an example − using System; namespace Demo { class Student { private string name; private int rank; public Student(Student s) { name = s.name; rank = s.rank; } public Student(string name, int rank) { this.name = name; this.rank = rank; } public string Display { get { return " Student " + name +" got Rank "+ rank.ToString(); } } } class StudentInfo { static void Main() { Student s1 = new Student("Jack", 2); // copy constructor Student s2 = new Student(s1); // display Console.WriteLine(s2.Display); Console.ReadLine(); } } } Above we saw, firstly we declared a copy constructor − public Student(Student s) Then a new object is created for the Student class − Student s1 = new Student("Jack", 2); Now, the s1 object is copied to a new object s2 − Student s2 = new Student(s1); This is what we call copy constructor.
[ { "code": null, "e": 1139, "s": 1062, "text": "Copy Constructor creates an object by copying variables from another object." }, { "code": null, "e": 1163, "s": 1139, "text": "Let us see an example −" }, { "code": null, "e": 1875, "s": 1163, "text": "using System;\nnamespace Demo {\n class Student {\n private string name;\n private int rank;\n\n public Student(Student s) {\n name = s.name;\n rank = s.rank;\n }\n\n public Student(string name, int rank) {\n this.name = name;\n this.rank = rank;\n }\n\n public string Display {\n get {\n return \" Student \" + name +\" got Rank \"+ rank.ToString();\n }\n }\n }\n\n class StudentInfo {\n static void Main() {\n Student s1 = new Student(\"Jack\", 2);\n\n // copy constructor\n Student s2 = new Student(s1);\n\n // display\n Console.WriteLine(s2.Display);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 1930, "s": 1875, "text": "Above we saw, firstly we declared a copy constructor −" }, { "code": null, "e": 1956, "s": 1930, "text": "public Student(Student s)" }, { "code": null, "e": 2009, "s": 1956, "text": "Then a new object is created for the Student class −" }, { "code": null, "e": 2046, "s": 2009, "text": "Student s1 = new Student(\"Jack\", 2);" }, { "code": null, "e": 2096, "s": 2046, "text": "Now, the s1 object is copied to a new object s2 −" }, { "code": null, "e": 2126, "s": 2096, "text": "Student s2 = new Student(s1);" }, { "code": null, "e": 2165, "s": 2126, "text": "This is what we call copy constructor." } ]
MySQL Tryit Editor v1.0
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 64, "s": 0, "text": "SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate" }, { "code": null, "e": 76, "s": 64, "text": "FROM Orders" }, { "code": null, "e": 97, "s": 76, "text": "INNER JOIN Customers" }, { "code": null, "e": 140, "s": 97, "text": "ON Orders.CustomerID=Customers.CustomerID;" }, { "code": null, "e": 142, "s": 140, "text": "​" }, { "code": null, "e": 214, "s": 151, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 274, "s": 214, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 342, "s": 274, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 380, "s": 342, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 465, "s": 380, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 639, "s": 465, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 690, "s": 639, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 758, "s": 690, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 929, "s": 758, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 1029, "s": 929, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 1079, "s": 1029, "text": "WebSQL is supported in Chrome, Safari, and Opera." } ]
Move all special char to the end of the String - GeeksforGeeks
07 May, 2021 In this article, we will learn how to move all special char to the end of the String.Examples: Input : !@$%^&*AJAY Output :AJAY!@$%^&*Input :Geeksf!@orgeek@s A#$ c%o^mputer s****cience p#o@rtal fo@r ge%eks Output :Geeksforgeeks A computer science portal for geeks!@@#$%^****#@@% Prerequisite : Regular Expressions in JavaThe idea is to traverse input string and maintain two strings, one string that contains normal characters (a, A, 1, ‘ ‘, etc) and other string that maintains special characters (@, $, etc). Finally, concatenate the two strings and return.Here is the implementation of above approach C++ Java Python3 C# Javascript // C++ program move all special char to the end of the string #include <bits/stdc++.h>using namespace std; // Function return a string with all special// chars to the endstring moveAllSC(string str){ // Take length of string int len = str.length(); // traverse string string res1 = "", res2 = ""; for (int i = 0; i < len; i++) { char c = str.at(i); // check char at index i is a special char if (isalnum(c) || c == ' ') res1 += c; else res2 += c; } return res1 + res2;} // Driver codeint main(){ string str1("Geeksf!@orgeek@s A#$ c%o^mputer"); string str2(" s****cience p#o@rtal fo@r ge%eks"); string str = str1 + str2; cout << moveAllSC(str) << endl; return 0;} // This code is contributed by// sanjeev2552 // Java program move all special char to the end of the stringclass GFG1 { // Function return a string with all special // chars to the end static String moveAllSC(String str) { // Take length of string int len = str.length(); // regular expression for check char is special // or not. String regx = "[a-zA-Z0-9\\s+]"; // traverse string String res1 = "", res2 = ""; for (int i = 0; i < len; i++) { char c = str.charAt(i); // check char at index i is a special char if (String.valueOf(c).matches(regx)) res1 = res1 + c; else res2 = res2 + c; } return res1 + res2; } public static void main(String args[]) { String str = "Geeksf!@orgeek@s A#$ c%o^mputer" + " s****cience p#o@rtal fo@r ge%eks"; System.out.println(moveAllSC(str)); }} # Python3 program move all special char# to the end of the string # Function return a string with all# special chars to the enddef moveAllSC(string): # Take length of string length = len(string) # Traverse string res1, res2 = "", "" for i in range(0, length): c = string[i] # check char at index i is a special char if c.isalnum() or c == " ": res1 = res1 + c else: res2 = res2 + c return res1 + res2 # Driver Codeif __name__ == "__main__": string = "Geeksf!@orgeek@s A#$ c%o^mputer" \ +" s****cience p#o@rtal fo@r ge%eks" print(moveAllSC(string)) # This code is contributed by Rituraj Jain // C# program move all special char// to the end of the stringusing System;using System.Text.RegularExpressions; class GFG{ // Function return a string with all // special chars to the end static String moveAllSC(String str) { // Take length of string int len = str.Length; // regular expression to check // char is special or not. var regx = new Regex("[a-zA-Z0-9\\s+]"); // traverse string String res1 = "", res2 = ""; for (int i = 0; i < len; i++) { char c = str[i]; // check char at index i is a special char if (regx.IsMatch(c.ToString())) res1 = res1 + c; else res2 = res2 + c; } return res1 + res2; } public static void Main(String []args) { String str = "Geeksf!@orgeek@s A#$ c%o^mputer" + " s****cience p#o@rtal fo@r ge%eks"; Console.WriteLine(moveAllSC(str)); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript program move all special char // to the end of the string // Function return a string with all // special chars to the end function moveAllSC(str) { // Take length of string var len = str.length; // regular expression to check // char is special or not. var regx = new RegExp("[a-zA-Z0-9\\s+]"); // traverse string var res1 = "", res2 = ""; for (var i = 0; i < len; i++) { var c = str[i].toString(); // check char at index i is a special char if (regx.test(c)) res1 = res1 + c; else res2 = res2 + c; } return res1 + res2; } var str = "Geeksf!@orgeek@s A#$ c%o^mputer" + " s****cience p#o@rtal fo@r ge%eks"; document.write(moveAllSC(str)); </script> Geeksforgeeks A computer science portal for geeks!@@#$%^****#@@% rituraj_jain sanjeev2552 princiraj1992 rdtank java-regular-expression Java-Strings Technical Scripter 2018 Java Programs Strings Technical Scripter Java-Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Iterate HashMap in Java? Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Java Program to Write into a File Modulo or Remainder Operator in Java Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 24537, "s": 24509, "text": "\n07 May, 2021" }, { "code": null, "e": 24634, "s": 24537, "text": "In this article, we will learn how to move all special char to the end of the String.Examples: " }, { "code": null, "e": 24818, "s": 24634, "text": "Input : !@$%^&*AJAY Output :AJAY!@$%^&*Input :Geeksf!@orgeek@s A#$ c%o^mputer s****cience p#o@rtal fo@r ge%eks Output :Geeksforgeeks A computer science portal for geeks!@@#$%^****#@@%" }, { "code": null, "e": 25147, "s": 24820, "text": "Prerequisite : Regular Expressions in JavaThe idea is to traverse input string and maintain two strings, one string that contains normal characters (a, A, 1, ‘ ‘, etc) and other string that maintains special characters (@, $, etc). Finally, concatenate the two strings and return.Here is the implementation of above approach " }, { "code": null, "e": 25151, "s": 25147, "text": "C++" }, { "code": null, "e": 25156, "s": 25151, "text": "Java" }, { "code": null, "e": 25164, "s": 25156, "text": "Python3" }, { "code": null, "e": 25167, "s": 25164, "text": "C#" }, { "code": null, "e": 25178, "s": 25167, "text": "Javascript" }, { "code": "// C++ program move all special char to the end of the string #include <bits/stdc++.h>using namespace std; // Function return a string with all special// chars to the endstring moveAllSC(string str){ // Take length of string int len = str.length(); // traverse string string res1 = \"\", res2 = \"\"; for (int i = 0; i < len; i++) { char c = str.at(i); // check char at index i is a special char if (isalnum(c) || c == ' ') res1 += c; else res2 += c; } return res1 + res2;} // Driver codeint main(){ string str1(\"Geeksf!@orgeek@s A#$ c%o^mputer\"); string str2(\" s****cience p#o@rtal fo@r ge%eks\"); string str = str1 + str2; cout << moveAllSC(str) << endl; return 0;} // This code is contributed by// sanjeev2552", "e": 25978, "s": 25178, "text": null }, { "code": "// Java program move all special char to the end of the stringclass GFG1 { // Function return a string with all special // chars to the end static String moveAllSC(String str) { // Take length of string int len = str.length(); // regular expression for check char is special // or not. String regx = \"[a-zA-Z0-9\\\\s+]\"; // traverse string String res1 = \"\", res2 = \"\"; for (int i = 0; i < len; i++) { char c = str.charAt(i); // check char at index i is a special char if (String.valueOf(c).matches(regx)) res1 = res1 + c; else res2 = res2 + c; } return res1 + res2; } public static void main(String args[]) { String str = \"Geeksf!@orgeek@s A#$ c%o^mputer\" + \" s****cience p#o@rtal fo@r ge%eks\"; System.out.println(moveAllSC(str)); }}", "e": 26924, "s": 25978, "text": null }, { "code": "# Python3 program move all special char# to the end of the string # Function return a string with all# special chars to the enddef moveAllSC(string): # Take length of string length = len(string) # Traverse string res1, res2 = \"\", \"\" for i in range(0, length): c = string[i] # check char at index i is a special char if c.isalnum() or c == \" \": res1 = res1 + c else: res2 = res2 + c return res1 + res2 # Driver Codeif __name__ == \"__main__\": string = \"Geeksf!@orgeek@s A#$ c%o^mputer\" \\ +\" s****cience p#o@rtal fo@r ge%eks\" print(moveAllSC(string)) # This code is contributed by Rituraj Jain", "e": 27643, "s": 26924, "text": null }, { "code": "// C# program move all special char// to the end of the stringusing System;using System.Text.RegularExpressions; class GFG{ // Function return a string with all // special chars to the end static String moveAllSC(String str) { // Take length of string int len = str.Length; // regular expression to check // char is special or not. var regx = new Regex(\"[a-zA-Z0-9\\\\s+]\"); // traverse string String res1 = \"\", res2 = \"\"; for (int i = 0; i < len; i++) { char c = str[i]; // check char at index i is a special char if (regx.IsMatch(c.ToString())) res1 = res1 + c; else res2 = res2 + c; } return res1 + res2; } public static void Main(String []args) { String str = \"Geeksf!@orgeek@s A#$ c%o^mputer\" + \" s****cience p#o@rtal fo@r ge%eks\"; Console.WriteLine(moveAllSC(str)); }} // This code is contributed by PrinciRaj1992", "e": 28675, "s": 27643, "text": null }, { "code": "<script> // JavaScript program move all special char // to the end of the string // Function return a string with all // special chars to the end function moveAllSC(str) { // Take length of string var len = str.length; // regular expression to check // char is special or not. var regx = new RegExp(\"[a-zA-Z0-9\\\\s+]\"); // traverse string var res1 = \"\", res2 = \"\"; for (var i = 0; i < len; i++) { var c = str[i].toString(); // check char at index i is a special char if (regx.test(c)) res1 = res1 + c; else res2 = res2 + c; } return res1 + res2; } var str = \"Geeksf!@orgeek@s A#$ c%o^mputer\" + \" s****cience p#o@rtal fo@r ge%eks\"; document.write(moveAllSC(str)); </script>", "e": 29515, "s": 28675, "text": null }, { "code": null, "e": 29580, "s": 29515, "text": "Geeksforgeeks A computer science portal for geeks!@@#$%^****#@@%" }, { "code": null, "e": 29595, "s": 29582, "text": "rituraj_jain" }, { "code": null, "e": 29607, "s": 29595, "text": "sanjeev2552" }, { "code": null, "e": 29621, "s": 29607, "text": "princiraj1992" }, { "code": null, "e": 29628, "s": 29621, "text": "rdtank" }, { "code": null, "e": 29652, "s": 29628, "text": "java-regular-expression" }, { "code": null, "e": 29665, "s": 29652, "text": "Java-Strings" }, { "code": null, "e": 29689, "s": 29665, "text": "Technical Scripter 2018" }, { "code": null, "e": 29703, "s": 29689, "text": "Java Programs" }, { "code": null, "e": 29711, "s": 29703, "text": "Strings" }, { "code": null, "e": 29730, "s": 29711, "text": "Technical Scripter" }, { "code": null, "e": 29743, "s": 29730, "text": "Java-Strings" }, { "code": null, "e": 29751, "s": 29743, "text": "Strings" }, { "code": null, "e": 29849, "s": 29751, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29858, "s": 29849, "text": "Comments" }, { "code": null, "e": 29871, "s": 29858, "text": "Old Comments" }, { "code": null, "e": 29903, "s": 29871, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 29951, "s": 29903, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 30002, "s": 29951, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 30036, "s": 30002, "text": "Java Program to Write into a File" }, { "code": null, "e": 30073, "s": 30036, "text": "Modulo or Remainder Operator in Java" }, { "code": null, "e": 30098, "s": 30073, "text": "Reverse a string in Java" }, { "code": null, "e": 30144, "s": 30098, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 30178, "s": 30144, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 30238, "s": 30178, "text": "Write a program to print all permutations of a given string" } ]
Check if a number can be expressed as sum of two Perfect powers - GeeksforGeeks
02 Dec, 2021 Given a positive number N, the task is to check whether the given number N can be expressed in the form of ax + by where x and y > 1 and a and b > 0. If N can be expressed in the given form then print true otherwise print false. Examples: Input: N = 5Output: trueExplanation:5 can be expressed as 22+12 Input: N = 15Output: false Approach: The idea is to use the concept of perfect powers to determine whether the sum exists or not. Below are the steps: Create an array(say perfectPower[]) to store the numbers which are a perfect power or not.Now the array perfectPower[] store all the elements which are perfect power, therefore we generate all possible pair sum of all the elements in this array.Keep the mark of the sum calculated in the above step in an array isSum[] as it can be expressed in the form of ax + by .After the above steps if isSum[N] is true then print true otherwise print false. Create an array(say perfectPower[]) to store the numbers which are a perfect power or not. Now the array perfectPower[] store all the elements which are perfect power, therefore we generate all possible pair sum of all the elements in this array. Keep the mark of the sum calculated in the above step in an array isSum[] as it can be expressed in the form of ax + by . After the above steps if isSum[N] is true then print true otherwise print false. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that returns true if n// can be written as a^m+b^nbool isSumOfPower(int n){ // Taking isSum boolean array // for check the sum exist or not bool isSum[n + 1]; // To store perfect squares vector<int> perfectPowers; perfectPowers.push_back(1); for (int i = 0; i < (n + 1); i++) { // Initially all sums as false isSum[i] = false; } for (long long int i = 2; i < (n + 1); i++) { if (isSum[i] == true) { // If sum exist then push // that sum into perfect // square vector perfectPowers.push_back(i); continue; } for (long long int j = i * i; j > 0 && j < (n + 1); j *= i) { isSum[j] = true; } } // Mark all perfect powers as false for (int i = 0; i < perfectPowers.size(); i++) { isSum[perfectPowers[i]] = false; } // Traverse each perfectPowers for (int i = 0; i < perfectPowers.size(); i++) { for (int j = i; j < perfectPowers.size(); j++) { // Calculating Sum with // perfect powers array int sum = perfectPowers[i] + perfectPowers[j]; if (sum < (n + 1)) isSum[sum] = true; } } return isSum[n];} // Driver Codeint main(){ // Given Number n int n = 9; // Function Call if (isSumOfPower(n)) { cout << "true\n"; } else { cout << "false\n"; }} // Java program for the above approachimport java.util.*; class GFG{ // Function that returns true if n// can be written as a^m+b^nstatic boolean isSumOfPower(int n){ // Taking isSum boolean array // for check the sum exist or not boolean []isSum = new boolean[n + 1]; // To store perfect squares Vector<Integer> perfectPowers = new Vector<Integer>(); perfectPowers.add(1); for(int i = 0; i < (n + 1); i++) { // Initially all sums as false isSum[i] = false; } for(int i = 2; i < (n + 1); i++) { if (isSum[i] == true) { // If sum exist then push // that sum into perfect // square vector perfectPowers.add(i); continue; } for(int j = i * i; j > 0 && j < (n + 1); j *= i) { isSum[j] = true; } } // Mark all perfect powers as false for(int i = 0; i < perfectPowers.size(); i++) { isSum[perfectPowers.get(i)] = false; } // Traverse each perfectPowers for(int i = 0; i < perfectPowers.size(); i++) { for(int j = i; j < perfectPowers.size(); j++) { // Calculating Sum with // perfect powers array int sum = perfectPowers.get(i) + perfectPowers.get(j); if (sum < (n + 1)) isSum[sum] = true; } } return isSum[n];} // Driver Codepublic static void main(String[] args){ // Given number n int n = 9; // Function call if (isSumOfPower(n)) { System.out.print("true\n"); } else { System.out.print("false\n"); }}} // This code is contributed by amal kumar choubey # Python3 program for the above approach # Function that returns true if n# can be written as a^m+b^ndef isSumOfPower(n): # Taking isSum boolean array # for check the sum exist or not isSum = [0] * (n + 1) # To store perfect squares perfectPowers = [] perfectPowers.append(1) for i in range(n + 1): # Initially all sums as false isSum[i] = False for i in range(2, n + 1): if (isSum[i] == True): # If sum exist then push # that sum into perfect # square vector perfectPowers.append(i) continue j = i * i while(j > 0 and j < (n + 1)): isSum[j] = True j *= i # Mark all perfect powers as false for i in range(len(perfectPowers)): isSum[perfectPowers[i]] = False # Traverse each perfectPowers for i in range(len(perfectPowers)): for j in range(len(perfectPowers)): # Calculating Sum with # perfect powers array sum = (perfectPowers[i] + perfectPowers[j]) if (sum < (n + 1)): isSum[sum] = True return isSum[n] # Driver Code # Given Number nn = 9 # Function callif (isSumOfPower(n)): print("true")else: print("false") # This code is contributed by sanjoy_62 // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function that returns true if n// can be written as a^m+b^nstatic bool isSumOfPower(int n){ // Taking isSum bool array // for check the sum exist or not bool []isSum = new bool[n + 1]; // To store perfect squares List<int> perfectPowers = new List<int>(); perfectPowers.Add(1); for(int i = 0; i < (n + 1); i++) { // Initially all sums as false isSum[i] = false; } for(int i = 2; i < (n + 1); i++) { if (isSum[i] == true) { // If sum exist then push // that sum into perfect // square vector perfectPowers.Add(i); continue; } for(int j = i * i; j > 0 && j < (n + 1); j *= i) { isSum[j] = true; } } // Mark all perfect powers as false for(int i = 0; i < perfectPowers.Count; i++) { isSum[perfectPowers[i]] = false; } // Traverse each perfectPowers for(int i = 0; i < perfectPowers.Count; i++) { for(int j = i; j < perfectPowers.Count; j++) { // Calculating Sum with // perfect powers array int sum = perfectPowers[i] + perfectPowers[j]; if (sum < (n + 1)) isSum[sum] = true; } } return isSum[n];} // Driver Codepublic static void Main(String[] args){ // Given number n int n = 9; // Function call if (isSumOfPower(n)) { Console.Write("true\n"); } else { Console.Write("false\n"); }}} // This code is contributed by amal kumar choubey <script> // JavaScript program to implement// the above approach // Function that returns true if n// can be written as a^m+b^nfunction isSumOfPower(n){ // Taking isSum boolean array // for check the sum exist or not let isSum = Array(n+1).fill(0); // To store perfect squares let perfectPowers = []; perfectPowers.push(1); for(let i = 0; i < (n + 1); i++) { // Initially all sums as false isSum[i] = false; } for(let i = 2; i < (n + 1); i++) { if (isSum[i] == true) { // If sum exist then push // that sum into perfect // square vector perfectPowers.push(i); continue; } for(let j = i * i; j > 0 && j < (n + 1); j *= i) { isSum[j] = true; } } // Mark all perfect powers as false for(let i = 0; i < perfectPowers.length; i++) { isSum[perfectPowers[i]] = false; } // Traverse each perfectPowers for(let i = 0; i < perfectPowers.length; i++) { for(let j = i; j < perfectPowers.length; j++) { // Calculating Sum with // perfect powers array let sum = perfectPowers[i] + perfectPowers[j]; if (sum < (n + 1)) isSum[sum] = true; } } return isSum[n];} // Driver Code // Given number n let n = 9; // Function call if (isSumOfPower(n)) { document.write("true\n"); } else { document.write("false\n"); } </script> true Time Complexity: O(N)Auxiliary Space: O(N) Amal Kumar Choubey sanjoy_62 avijitmondal1998 surinderdawra388 arorakashish0911 Maths maths-power Numbers Greedy Mathematical Greedy Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Program for First Fit algorithm in Memory Management Bin Packing Problem (Minimize number of used Bins) Max Flow Problem Introduction Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 26537, "s": 26509, "text": "\n02 Dec, 2021" }, { "code": null, "e": 26766, "s": 26537, "text": "Given a positive number N, the task is to check whether the given number N can be expressed in the form of ax + by where x and y > 1 and a and b > 0. If N can be expressed in the given form then print true otherwise print false." }, { "code": null, "e": 26776, "s": 26766, "text": "Examples:" }, { "code": null, "e": 26842, "s": 26776, "text": "Input: N = 5Output: trueExplanation:5 can be expressed as 22+12 " }, { "code": null, "e": 26869, "s": 26842, "text": "Input: N = 15Output: false" }, { "code": null, "e": 26993, "s": 26869, "text": "Approach: The idea is to use the concept of perfect powers to determine whether the sum exists or not. Below are the steps:" }, { "code": null, "e": 27440, "s": 26993, "text": "Create an array(say perfectPower[]) to store the numbers which are a perfect power or not.Now the array perfectPower[] store all the elements which are perfect power, therefore we generate all possible pair sum of all the elements in this array.Keep the mark of the sum calculated in the above step in an array isSum[] as it can be expressed in the form of ax + by .After the above steps if isSum[N] is true then print true otherwise print false." }, { "code": null, "e": 27531, "s": 27440, "text": "Create an array(say perfectPower[]) to store the numbers which are a perfect power or not." }, { "code": null, "e": 27687, "s": 27531, "text": "Now the array perfectPower[] store all the elements which are perfect power, therefore we generate all possible pair sum of all the elements in this array." }, { "code": null, "e": 27809, "s": 27687, "text": "Keep the mark of the sum calculated in the above step in an array isSum[] as it can be expressed in the form of ax + by ." }, { "code": null, "e": 27890, "s": 27809, "text": "After the above steps if isSum[N] is true then print true otherwise print false." }, { "code": null, "e": 27941, "s": 27890, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27945, "s": 27941, "text": "C++" }, { "code": null, "e": 27950, "s": 27945, "text": "Java" }, { "code": null, "e": 27958, "s": 27950, "text": "Python3" }, { "code": null, "e": 27961, "s": 27958, "text": "C#" }, { "code": null, "e": 27972, "s": 27961, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that returns true if n// can be written as a^m+b^nbool isSumOfPower(int n){ // Taking isSum boolean array // for check the sum exist or not bool isSum[n + 1]; // To store perfect squares vector<int> perfectPowers; perfectPowers.push_back(1); for (int i = 0; i < (n + 1); i++) { // Initially all sums as false isSum[i] = false; } for (long long int i = 2; i < (n + 1); i++) { if (isSum[i] == true) { // If sum exist then push // that sum into perfect // square vector perfectPowers.push_back(i); continue; } for (long long int j = i * i; j > 0 && j < (n + 1); j *= i) { isSum[j] = true; } } // Mark all perfect powers as false for (int i = 0; i < perfectPowers.size(); i++) { isSum[perfectPowers[i]] = false; } // Traverse each perfectPowers for (int i = 0; i < perfectPowers.size(); i++) { for (int j = i; j < perfectPowers.size(); j++) { // Calculating Sum with // perfect powers array int sum = perfectPowers[i] + perfectPowers[j]; if (sum < (n + 1)) isSum[sum] = true; } } return isSum[n];} // Driver Codeint main(){ // Given Number n int n = 9; // Function Call if (isSumOfPower(n)) { cout << \"true\\n\"; } else { cout << \"false\\n\"; }}", "e": 29573, "s": 27972, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function that returns true if n// can be written as a^m+b^nstatic boolean isSumOfPower(int n){ // Taking isSum boolean array // for check the sum exist or not boolean []isSum = new boolean[n + 1]; // To store perfect squares Vector<Integer> perfectPowers = new Vector<Integer>(); perfectPowers.add(1); for(int i = 0; i < (n + 1); i++) { // Initially all sums as false isSum[i] = false; } for(int i = 2; i < (n + 1); i++) { if (isSum[i] == true) { // If sum exist then push // that sum into perfect // square vector perfectPowers.add(i); continue; } for(int j = i * i; j > 0 && j < (n + 1); j *= i) { isSum[j] = true; } } // Mark all perfect powers as false for(int i = 0; i < perfectPowers.size(); i++) { isSum[perfectPowers.get(i)] = false; } // Traverse each perfectPowers for(int i = 0; i < perfectPowers.size(); i++) { for(int j = i; j < perfectPowers.size(); j++) { // Calculating Sum with // perfect powers array int sum = perfectPowers.get(i) + perfectPowers.get(j); if (sum < (n + 1)) isSum[sum] = true; } } return isSum[n];} // Driver Codepublic static void main(String[] args){ // Given number n int n = 9; // Function call if (isSumOfPower(n)) { System.out.print(\"true\\n\"); } else { System.out.print(\"false\\n\"); }}} // This code is contributed by amal kumar choubey", "e": 31414, "s": 29573, "text": null }, { "code": "# Python3 program for the above approach # Function that returns true if n# can be written as a^m+b^ndef isSumOfPower(n): # Taking isSum boolean array # for check the sum exist or not isSum = [0] * (n + 1) # To store perfect squares perfectPowers = [] perfectPowers.append(1) for i in range(n + 1): # Initially all sums as false isSum[i] = False for i in range(2, n + 1): if (isSum[i] == True): # If sum exist then push # that sum into perfect # square vector perfectPowers.append(i) continue j = i * i while(j > 0 and j < (n + 1)): isSum[j] = True j *= i # Mark all perfect powers as false for i in range(len(perfectPowers)): isSum[perfectPowers[i]] = False # Traverse each perfectPowers for i in range(len(perfectPowers)): for j in range(len(perfectPowers)): # Calculating Sum with # perfect powers array sum = (perfectPowers[i] + perfectPowers[j]) if (sum < (n + 1)): isSum[sum] = True return isSum[n] # Driver Code # Given Number nn = 9 # Function callif (isSumOfPower(n)): print(\"true\")else: print(\"false\") # This code is contributed by sanjoy_62", "e": 32763, "s": 31414, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function that returns true if n// can be written as a^m+b^nstatic bool isSumOfPower(int n){ // Taking isSum bool array // for check the sum exist or not bool []isSum = new bool[n + 1]; // To store perfect squares List<int> perfectPowers = new List<int>(); perfectPowers.Add(1); for(int i = 0; i < (n + 1); i++) { // Initially all sums as false isSum[i] = false; } for(int i = 2; i < (n + 1); i++) { if (isSum[i] == true) { // If sum exist then push // that sum into perfect // square vector perfectPowers.Add(i); continue; } for(int j = i * i; j > 0 && j < (n + 1); j *= i) { isSum[j] = true; } } // Mark all perfect powers as false for(int i = 0; i < perfectPowers.Count; i++) { isSum[perfectPowers[i]] = false; } // Traverse each perfectPowers for(int i = 0; i < perfectPowers.Count; i++) { for(int j = i; j < perfectPowers.Count; j++) { // Calculating Sum with // perfect powers array int sum = perfectPowers[i] + perfectPowers[j]; if (sum < (n + 1)) isSum[sum] = true; } } return isSum[n];} // Driver Codepublic static void Main(String[] args){ // Given number n int n = 9; // Function call if (isSumOfPower(n)) { Console.Write(\"true\\n\"); } else { Console.Write(\"false\\n\"); }}} // This code is contributed by amal kumar choubey", "e": 34584, "s": 32763, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // Function that returns true if n// can be written as a^m+b^nfunction isSumOfPower(n){ // Taking isSum boolean array // for check the sum exist or not let isSum = Array(n+1).fill(0); // To store perfect squares let perfectPowers = []; perfectPowers.push(1); for(let i = 0; i < (n + 1); i++) { // Initially all sums as false isSum[i] = false; } for(let i = 2; i < (n + 1); i++) { if (isSum[i] == true) { // If sum exist then push // that sum into perfect // square vector perfectPowers.push(i); continue; } for(let j = i * i; j > 0 && j < (n + 1); j *= i) { isSum[j] = true; } } // Mark all perfect powers as false for(let i = 0; i < perfectPowers.length; i++) { isSum[perfectPowers[i]] = false; } // Traverse each perfectPowers for(let i = 0; i < perfectPowers.length; i++) { for(let j = i; j < perfectPowers.length; j++) { // Calculating Sum with // perfect powers array let sum = perfectPowers[i] + perfectPowers[j]; if (sum < (n + 1)) isSum[sum] = true; } } return isSum[n];} // Driver Code // Given number n let n = 9; // Function call if (isSumOfPower(n)) { document.write(\"true\\n\"); } else { document.write(\"false\\n\"); } </script>", "e": 36302, "s": 34584, "text": null }, { "code": null, "e": 36307, "s": 36302, "text": "true" }, { "code": null, "e": 36350, "s": 36307, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 36369, "s": 36350, "text": "Amal Kumar Choubey" }, { "code": null, "e": 36379, "s": 36369, "text": "sanjoy_62" }, { "code": null, "e": 36396, "s": 36379, "text": "avijitmondal1998" }, { "code": null, "e": 36413, "s": 36396, "text": "surinderdawra388" }, { "code": null, "e": 36430, "s": 36413, "text": "arorakashish0911" }, { "code": null, "e": 36436, "s": 36430, "text": "Maths" }, { "code": null, "e": 36448, "s": 36436, "text": "maths-power" }, { "code": null, "e": 36456, "s": 36448, "text": "Numbers" }, { "code": null, "e": 36463, "s": 36456, "text": "Greedy" }, { "code": null, "e": 36476, "s": 36463, "text": "Mathematical" }, { "code": null, "e": 36483, "s": 36476, "text": "Greedy" }, { "code": null, "e": 36496, "s": 36483, "text": "Mathematical" }, { "code": null, "e": 36504, "s": 36496, "text": "Numbers" }, { "code": null, "e": 36602, "s": 36504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36637, "s": 36602, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 36689, "s": 36637, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 36742, "s": 36689, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 36793, "s": 36742, "text": "Bin Packing Problem (Minimize number of used Bins)" }, { "code": null, "e": 36823, "s": 36793, "text": "Max Flow Problem Introduction" }, { "code": null, "e": 36853, "s": 36823, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36868, "s": 36853, "text": "C++ Data Types" }, { "code": null, "e": 36911, "s": 36868, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 36935, "s": 36911, "text": "Merge two sorted arrays" } ]
Image Segmentation using K Means Clustering - GeeksforGeeks
21 Jul, 2021 Image Segmentation: In computer vision, image segmentation is the process of partitioning an image into multiple segments. The goal of segmenting an image is to change the representation of an image into something that is more meaningful and easier to analyze. It is usually used for locating objects and creating boundaries. It is not a great idea to process an entire image because many parts in an image may not contain any useful information. Therefore, by segmenting the image, we can make use of only the important segments for processing. An image is basically a set of given pixels. In image segmentation, pixels which have similar attributes are grouped together. Image segmentation creates a pixel-wise mask for objects in an image which gives us a more comprehensive and granular understanding of the object. Uses: Used in self-driving cars. Autonomous driving is not possible without object detection which involves segmentation.Used in the healthcare industry. Helpful in segmenting cancer cells and tumours using which their severity can be gauged. Used in self-driving cars. Autonomous driving is not possible without object detection which involves segmentation. Used in the healthcare industry. Helpful in segmenting cancer cells and tumours using which their severity can be gauged. There are many more uses of image segmentation. In this article, we will perform segmentation on an image of the monarch butterfly using a clustering method called K Means Clustering. K Means Clustering Algorithm: K Means is a clustering algorithm. Clustering algorithms are unsupervised algorithms which means that there is no labelled data available. It is used to identify different classes or clusters in the given data based on how similar the data is. Data points in the same group are more similar to other data points in that same group than those in other groups. K-means clustering is one of the most commonly used clustering algorithms. Here, k represents the number of clusters. Let’s see how does K-means clustering work – Choose the number of clusters you want to find which is k.Randomly assign the data points to any of the k clusters.Then calculate the center of the clusters.Calculate the distance of the data points from the centers of each of the clusters.Depending on the distance of each data point from the cluster, reassign the data points to the nearest clusters.Again calculate the new cluster center.Repeat steps 4,5 and 6 till data points don’t change the clusters, or till we reach the assigned number of iterations. Choose the number of clusters you want to find which is k. Randomly assign the data points to any of the k clusters. Then calculate the center of the clusters. Calculate the distance of the data points from the centers of each of the clusters. Depending on the distance of each data point from the cluster, reassign the data points to the nearest clusters. Again calculate the new cluster center. Repeat steps 4,5 and 6 till data points don’t change the clusters, or till we reach the assigned number of iterations. Requirements: Make sure you have Python, Numpy, Matplotlib and OpenCV installed. Code: Read in the image and convert it to an RGB image. python3 import numpy as npimport matplotlib.pyplot as pltimport cv2 %matplotlib inline # Read in the imageimage = cv2.imread('images/monarch.jpg') # Change color to RGB (from BGR)image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(image) Now we have to prepare the data for K means. The image is a 3-dimensional shape but to apply k-means clustering on it we need to reshape it to a 2-dimensional array. Code: python3 # Reshaping the image into a 2D array of pixels and 3 color values (RGB)pixel_vals = image.reshape((-1,3)) # Convert to float typepixel_vals = np.float32(pixel_vals) Now we will implement the K means algorithm for segmenting an image. Code: Taking k = 3, which means that the algorithm will identify 3 clusters in the image. python3 #the below line of code defines the criteria for the algorithm to stop running,#which will happen is 100 iterations are run or the epsilon (which is the required accuracy)#becomes 85%criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.85) # then perform k-means clustering wit h number of clusters defined as 3#also random centres are initially choosed for k-means clusteringk = 3retval, labels, centers = cv2.kmeans(pixel_vals, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) # convert data into 8-bit valuescenters = np.uint8(centers)segmented_data = centers[labels.flatten()] # reshape data into the original image dimensionssegmented_image = segmented_data.reshape((image.shape)) plt.imshow(segmented_image) Output: Now if we change the value of k to 6, we get the following Output: As you can see with an increase in the value of k, the image becomes clearer and distinct because the K-means algorithm can classify more classes/cluster of colors. K-means clustering works well when we have a small dataset. It can segment objects in images and also give better results. But when it is applied on large datasets (more number of images), it looks at all the samples in one iteration which leads to a lot of time being taken up. simmytarika5 kapoorsagar226 OpenCV Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Activation functions in Neural Networks Decision Tree Introduction with example Introduction to Recurrent Neural Network Support Vector Machine Algorithm 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": 25655, "s": 25627, "text": "\n21 Jul, 2021" }, { "code": null, "e": 25983, "s": 25655, "text": " Image Segmentation: In computer vision, image segmentation is the process of partitioning an image into multiple segments. The goal of segmenting an image is to change the representation of an image into something that is more meaningful and easier to analyze. It is usually used for locating objects and creating boundaries. " }, { "code": null, "e": 26204, "s": 25983, "text": "It is not a great idea to process an entire image because many parts in an image may not contain any useful information. Therefore, by segmenting the image, we can make use of only the important segments for processing. " }, { "code": null, "e": 26478, "s": 26204, "text": "An image is basically a set of given pixels. In image segmentation, pixels which have similar attributes are grouped together. Image segmentation creates a pixel-wise mask for objects in an image which gives us a more comprehensive and granular understanding of the object." }, { "code": null, "e": 26485, "s": 26478, "text": "Uses: " }, { "code": null, "e": 26722, "s": 26485, "text": "Used in self-driving cars. Autonomous driving is not possible without object detection which involves segmentation.Used in the healthcare industry. Helpful in segmenting cancer cells and tumours using which their severity can be gauged." }, { "code": null, "e": 26838, "s": 26722, "text": "Used in self-driving cars. Autonomous driving is not possible without object detection which involves segmentation." }, { "code": null, "e": 26960, "s": 26838, "text": "Used in the healthcare industry. Helpful in segmenting cancer cells and tumours using which their severity can be gauged." }, { "code": null, "e": 27008, "s": 26960, "text": "There are many more uses of image segmentation." }, { "code": null, "e": 27144, "s": 27008, "text": "In this article, we will perform segmentation on an image of the monarch butterfly using a clustering method called K Means Clustering." }, { "code": null, "e": 27174, "s": 27144, "text": "K Means Clustering Algorithm:" }, { "code": null, "e": 27534, "s": 27174, "text": "K Means is a clustering algorithm. Clustering algorithms are unsupervised algorithms which means that there is no labelled data available. It is used to identify different classes or clusters in the given data based on how similar the data is. Data points in the same group are more similar to other data points in that same group than those in other groups. " }, { "code": null, "e": 27652, "s": 27534, "text": "K-means clustering is one of the most commonly used clustering algorithms. Here, k represents the number of clusters." }, { "code": null, "e": 27697, "s": 27652, "text": "Let’s see how does K-means clustering work –" }, { "code": null, "e": 28207, "s": 27697, "text": "Choose the number of clusters you want to find which is k.Randomly assign the data points to any of the k clusters.Then calculate the center of the clusters.Calculate the distance of the data points from the centers of each of the clusters.Depending on the distance of each data point from the cluster, reassign the data points to the nearest clusters.Again calculate the new cluster center.Repeat steps 4,5 and 6 till data points don’t change the clusters, or till we reach the assigned number of iterations." }, { "code": null, "e": 28266, "s": 28207, "text": "Choose the number of clusters you want to find which is k." }, { "code": null, "e": 28324, "s": 28266, "text": "Randomly assign the data points to any of the k clusters." }, { "code": null, "e": 28367, "s": 28324, "text": "Then calculate the center of the clusters." }, { "code": null, "e": 28451, "s": 28367, "text": "Calculate the distance of the data points from the centers of each of the clusters." }, { "code": null, "e": 28564, "s": 28451, "text": "Depending on the distance of each data point from the cluster, reassign the data points to the nearest clusters." }, { "code": null, "e": 28604, "s": 28564, "text": "Again calculate the new cluster center." }, { "code": null, "e": 28723, "s": 28604, "text": "Repeat steps 4,5 and 6 till data points don’t change the clusters, or till we reach the assigned number of iterations." }, { "code": null, "e": 28737, "s": 28723, "text": "Requirements:" }, { "code": null, "e": 28804, "s": 28737, "text": "Make sure you have Python, Numpy, Matplotlib and OpenCV installed." }, { "code": null, "e": 28860, "s": 28804, "text": "Code: Read in the image and convert it to an RGB image." }, { "code": null, "e": 28868, "s": 28860, "text": "python3" }, { "code": "import numpy as npimport matplotlib.pyplot as pltimport cv2 %matplotlib inline # Read in the imageimage = cv2.imread('images/monarch.jpg') # Change color to RGB (from BGR)image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(image)", "e": 29104, "s": 28868, "text": null }, { "code": null, "e": 29270, "s": 29104, "text": "Now we have to prepare the data for K means. The image is a 3-dimensional shape but to apply k-means clustering on it we need to reshape it to a 2-dimensional array." }, { "code": null, "e": 29277, "s": 29270, "text": "Code: " }, { "code": null, "e": 29285, "s": 29277, "text": "python3" }, { "code": "# Reshaping the image into a 2D array of pixels and 3 color values (RGB)pixel_vals = image.reshape((-1,3)) # Convert to float typepixel_vals = np.float32(pixel_vals)", "e": 29451, "s": 29285, "text": null }, { "code": null, "e": 29521, "s": 29451, "text": "Now we will implement the K means algorithm for segmenting an image. " }, { "code": null, "e": 29612, "s": 29521, "text": "Code: Taking k = 3, which means that the algorithm will identify 3 clusters in the image." }, { "code": null, "e": 29620, "s": 29612, "text": "python3" }, { "code": "#the below line of code defines the criteria for the algorithm to stop running,#which will happen is 100 iterations are run or the epsilon (which is the required accuracy)#becomes 85%criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.85) # then perform k-means clustering wit h number of clusters defined as 3#also random centres are initially choosed for k-means clusteringk = 3retval, labels, centers = cv2.kmeans(pixel_vals, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) # convert data into 8-bit valuescenters = np.uint8(centers)segmented_data = centers[labels.flatten()] # reshape data into the original image dimensionssegmented_image = segmented_data.reshape((image.shape)) plt.imshow(segmented_image)", "e": 30353, "s": 29620, "text": null }, { "code": null, "e": 30362, "s": 30353, "text": "Output: " }, { "code": null, "e": 30429, "s": 30362, "text": "Now if we change the value of k to 6, we get the following Output:" }, { "code": null, "e": 30874, "s": 30429, "text": "As you can see with an increase in the value of k, the image becomes clearer and distinct because the K-means algorithm can classify more classes/cluster of colors. K-means clustering works well when we have a small dataset. It can segment objects in images and also give better results. But when it is applied on large datasets (more number of images), it looks at all the samples in one iteration which leads to a lot of time being taken up. " }, { "code": null, "e": 30887, "s": 30874, "text": "simmytarika5" }, { "code": null, "e": 30902, "s": 30887, "text": "kapoorsagar226" }, { "code": null, "e": 30909, "s": 30902, "text": "OpenCV" }, { "code": null, "e": 30926, "s": 30909, "text": "Machine Learning" }, { "code": null, "e": 30933, "s": 30926, "text": "Python" }, { "code": null, "e": 30950, "s": 30933, "text": "Machine Learning" }, { "code": null, "e": 31048, "s": 30950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31062, "s": 31048, "text": "Decision Tree" }, { "code": null, "e": 31102, "s": 31062, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 31142, "s": 31102, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 31183, "s": 31142, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 31216, "s": 31183, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 31244, "s": 31216, "text": "Read JSON file using Python" }, { "code": null, "e": 31294, "s": 31244, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 31316, "s": 31294, "text": "Python map() function" } ]
Generating subarrays using recursion - GeeksforGeeks
19 Apr, 2022 Given an array, generate all the possible subarrays of the given array using recursion. Examples: Input : [1, 2, 3] Output : [1], [1, 2], [2], [1, 2, 3], [2, 3], [3] Input : [1, 2] Output : [1], [1, 2], [2] We have discussed iterative program to generate all subarrays. In this post, recursive is discussed. Approach: We use two pointers start and end to maintain the starting and ending point of the array and follow the steps given below: Stop if we have reached the end of the array Increment the end index if start has become greater than end Print the subarray from index start to end and increment the starting index Below is the implementation of the above approach. C++ C Java Python3 C# PHP Javascript // C++ code to print all possible subarrays for given array// using recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print all possible subarrays for// given arrayvoid printSubArrays(vector<int> arr, int start, int end){ // Stop if we have reached the end of the array if (end == arr.size()) return; // Increment the end point and start from 0 else if (start > end) printSubArrays(arr, 0, end + 1); // Print the subarray and increment the starting point else { cout << "["; for (int i = start; i < end; i++) cout << arr[i] << ", "; cout << arr[end] << "]" << endl; printSubArrays(arr, start + 1, end); } return;} int main(){ vector<int> arr = { 1, 2, 3 }; printSubArrays(arr, 0, 0); return 0;} // This code is contributed by Sania Kumari Gupta // C code to print all possible subarrays for given array// using recursion#include <stdio.h> // Recursive function to print all possible subarrays for// given arrayvoid printSubArrays(int arr[], int start, int end, int size){ // Stop if we have reached the end of the array if (end == size) return; // Increment the end point and start from 0 else if (start > end) printSubArrays(arr, 0, end + 1, size); // Print the subarray and increment the starting point else { printf("["); for (int i = start; i < end; i++) printf("%d, ", arr[i]); // cout << arr[i] << ", "; printf("%d]\n", arr[end]); // cout << arr[end] << "]" << endl; printSubArrays(arr, start + 1, end, size); } return;} int main(){ int arr[] = { 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printSubArrays(arr, 0, 0, n); return 0;} // This code is contributed by Sania Kumari Gupta // Java code to print all possible subarrays for given array// using recursion class solution { // Recursive function to print all possible subarrays // for given array static void printSubArrays(int[] arr, int start, int end) { // Stop if we have reached the end of the array if (end == arr.length) return; // Increment the end point and start from 0 else if (start > end) printSubArrays(arr, 0, end + 1); // Print the subarray and increment the starting // point else { System.out.print("["); for (int i = start; i < end; i++) System.out.print(arr[i] + ", "); System.out.println(arr[end] + "]"); printSubArrays(arr, start + 1, end); } return; } public static void main(String args[]) { int[] arr = { 1, 2, 3 }; printSubArrays(arr, 0, 0); }} // This code is contributed by Sania Kumari Gupta # Python3 code to print all possible subarrays# for given array using recursion # Recursive function to print all possible subarrays# for given arraydef printSubArrays(arr, start, end): # Stop if we have reached the end of the array if end == len(arr): return # Increment the end point and start from 0 elif start > end: return printSubArrays(arr, 0, end + 1) # Print the subarray and increment the starting # point else: print(arr[start:end + 1]) return printSubArrays(arr, start + 1, end) # Driver codearr = [1, 2, 3]printSubArrays(arr, 0, 0) // C# code to print all possible subarrays// for given array using recursionusing System; class GFG{ // Recursive function to print all // possible subarrays for given array static void printSubArrays(int []arr, int start, int end) { // Stop if we have reached // the end of the array if (end == arr.Length) return; // Increment the end point // and start from 0 else if (start > end) printSubArrays(arr, 0, end + 1); // Print the subarray and // increment the starting point else { Console.Write("["); for (int i = start; i < end; i++) { Console.Write(arr[i]+", "); } Console.WriteLine(arr[end]+"]"); printSubArrays(arr, start + 1, end); } return; } // Driver code public static void Main(String []args) { int []arr = {1, 2, 3}; printSubArrays(arr, 0, 0); }} // This code is contributed by Rajput-Ji <?php// PHP code to print all possible// subarrays for given array using recursion // Recursive function to print all// possible subarrays for given arrayfunction printSubArrays($arr, $start, $end){ // Stop if we have reached // the end of the array if ($end == count($arr)) return; // Increment the end point // and start from 0 else if ($start > $end) return printSubArrays($arr, 0, $end + 1); // Print the subarray and increment // the starting point else { echo "["; for($i = $start; $i < $end + 1; $i++) { echo $arr[$i]; if($i != $end) echo ", "; } echo "]\n"; return printSubArrays($arr, $start + 1, $end); }} // Driver code$arr = array(1, 2, 3);printSubArrays($arr, 0, 0); // This code is contributed by mits?> <script> // Javascript code to print all possible// subarrays for given array using recursion // Recursive function to print all// possible subarrays for given arrayfunction printSubArrays(arr, start, end){ // Stop if we have reached the end // of the array if (end == arr.length) return; // Increment the end point and start // from 0 else if (start > end) printSubArrays(arr, 0, end + 1); // Print the subarray and increment // the starting point else { document.write("["); for(var i = start; i < end; i++) { document.write( arr[i] + ", "); } document.write(arr[end] + "]<br>"); printSubArrays(arr, start + 1, end); } return;} // Driver codevar arr = [ 1, 2, 3 ];printSubArrays(arr, 0, 0); // This code is contributed by rutvik_56 </script> [1] [1, 2] [2] [1, 2, 3] [2, 3] [3] Time Complexity: Mithun Kumar rituraj_jain SURENDRA_GANGWAR Rajput-Ji rutvik_56 sankarsingh jaskeerat10000 krisania804 Picked subarray Technical Scripter 2018 Arrays Python Recursion Technical Scripter Arrays Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java 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": 26453, "s": 26425, "text": "\n19 Apr, 2022" }, { "code": null, "e": 26541, "s": 26453, "text": "Given an array, generate all the possible subarrays of the given array using recursion." }, { "code": null, "e": 26552, "s": 26541, "text": "Examples: " }, { "code": null, "e": 26662, "s": 26552, "text": "Input : [1, 2, 3]\nOutput : [1], [1, 2], [2], [1, 2, 3], [2, 3], [3]\n\nInput : [1, 2]\nOutput : [1], [1, 2], [2]" }, { "code": null, "e": 26763, "s": 26662, "text": "We have discussed iterative program to generate all subarrays. In this post, recursive is discussed." }, { "code": null, "e": 26897, "s": 26763, "text": "Approach: We use two pointers start and end to maintain the starting and ending point of the array and follow the steps given below: " }, { "code": null, "e": 26942, "s": 26897, "text": "Stop if we have reached the end of the array" }, { "code": null, "e": 27003, "s": 26942, "text": "Increment the end index if start has become greater than end" }, { "code": null, "e": 27079, "s": 27003, "text": "Print the subarray from index start to end and increment the starting index" }, { "code": null, "e": 27132, "s": 27079, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 27136, "s": 27132, "text": "C++" }, { "code": null, "e": 27138, "s": 27136, "text": "C" }, { "code": null, "e": 27143, "s": 27138, "text": "Java" }, { "code": null, "e": 27151, "s": 27143, "text": "Python3" }, { "code": null, "e": 27154, "s": 27151, "text": "C#" }, { "code": null, "e": 27158, "s": 27154, "text": "PHP" }, { "code": null, "e": 27169, "s": 27158, "text": "Javascript" }, { "code": "// C++ code to print all possible subarrays for given array// using recursion #include <bits/stdc++.h>using namespace std; // Recursive function to print all possible subarrays for// given arrayvoid printSubArrays(vector<int> arr, int start, int end){ // Stop if we have reached the end of the array if (end == arr.size()) return; // Increment the end point and start from 0 else if (start > end) printSubArrays(arr, 0, end + 1); // Print the subarray and increment the starting point else { cout << \"[\"; for (int i = start; i < end; i++) cout << arr[i] << \", \"; cout << arr[end] << \"]\" << endl; printSubArrays(arr, start + 1, end); } return;} int main(){ vector<int> arr = { 1, 2, 3 }; printSubArrays(arr, 0, 0); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 28030, "s": 27169, "text": null }, { "code": "// C code to print all possible subarrays for given array// using recursion#include <stdio.h> // Recursive function to print all possible subarrays for// given arrayvoid printSubArrays(int arr[], int start, int end, int size){ // Stop if we have reached the end of the array if (end == size) return; // Increment the end point and start from 0 else if (start > end) printSubArrays(arr, 0, end + 1, size); // Print the subarray and increment the starting point else { printf(\"[\"); for (int i = start; i < end; i++) printf(\"%d, \", arr[i]); // cout << arr[i] << \", \"; printf(\"%d]\\n\", arr[end]); // cout << arr[end] << \"]\" << endl; printSubArrays(arr, start + 1, end, size); } return;} int main(){ int arr[] = { 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printSubArrays(arr, 0, 0, n); return 0;} // This code is contributed by Sania Kumari Gupta", "e": 29004, "s": 28030, "text": null }, { "code": "// Java code to print all possible subarrays for given array// using recursion class solution { // Recursive function to print all possible subarrays // for given array static void printSubArrays(int[] arr, int start, int end) { // Stop if we have reached the end of the array if (end == arr.length) return; // Increment the end point and start from 0 else if (start > end) printSubArrays(arr, 0, end + 1); // Print the subarray and increment the starting // point else { System.out.print(\"[\"); for (int i = start; i < end; i++) System.out.print(arr[i] + \", \"); System.out.println(arr[end] + \"]\"); printSubArrays(arr, start + 1, end); } return; } public static void main(String args[]) { int[] arr = { 1, 2, 3 }; printSubArrays(arr, 0, 0); }} // This code is contributed by Sania Kumari Gupta", "e": 29981, "s": 29004, "text": null }, { "code": "# Python3 code to print all possible subarrays# for given array using recursion # Recursive function to print all possible subarrays# for given arraydef printSubArrays(arr, start, end): # Stop if we have reached the end of the array if end == len(arr): return # Increment the end point and start from 0 elif start > end: return printSubArrays(arr, 0, end + 1) # Print the subarray and increment the starting # point else: print(arr[start:end + 1]) return printSubArrays(arr, start + 1, end) # Driver codearr = [1, 2, 3]printSubArrays(arr, 0, 0)", "e": 30605, "s": 29981, "text": null }, { "code": "// C# code to print all possible subarrays// for given array using recursionusing System; class GFG{ // Recursive function to print all // possible subarrays for given array static void printSubArrays(int []arr, int start, int end) { // Stop if we have reached // the end of the array if (end == arr.Length) return; // Increment the end point // and start from 0 else if (start > end) printSubArrays(arr, 0, end + 1); // Print the subarray and // increment the starting point else { Console.Write(\"[\"); for (int i = start; i < end; i++) { Console.Write(arr[i]+\", \"); } Console.WriteLine(arr[end]+\"]\"); printSubArrays(arr, start + 1, end); } return; } // Driver code public static void Main(String []args) { int []arr = {1, 2, 3}; printSubArrays(arr, 0, 0); }} // This code is contributed by Rajput-Ji", "e": 31663, "s": 30605, "text": null }, { "code": "<?php// PHP code to print all possible// subarrays for given array using recursion // Recursive function to print all// possible subarrays for given arrayfunction printSubArrays($arr, $start, $end){ // Stop if we have reached // the end of the array if ($end == count($arr)) return; // Increment the end point // and start from 0 else if ($start > $end) return printSubArrays($arr, 0, $end + 1); // Print the subarray and increment // the starting point else { echo \"[\"; for($i = $start; $i < $end + 1; $i++) { echo $arr[$i]; if($i != $end) echo \", \"; } echo \"]\\n\"; return printSubArrays($arr, $start + 1, $end); }} // Driver code$arr = array(1, 2, 3);printSubArrays($arr, 0, 0); // This code is contributed by mits?>", "e": 32549, "s": 31663, "text": null }, { "code": "<script> // Javascript code to print all possible// subarrays for given array using recursion // Recursive function to print all// possible subarrays for given arrayfunction printSubArrays(arr, start, end){ // Stop if we have reached the end // of the array if (end == arr.length) return; // Increment the end point and start // from 0 else if (start > end) printSubArrays(arr, 0, end + 1); // Print the subarray and increment // the starting point else { document.write(\"[\"); for(var i = start; i < end; i++) { document.write( arr[i] + \", \"); } document.write(arr[end] + \"]<br>\"); printSubArrays(arr, start + 1, end); } return;} // Driver codevar arr = [ 1, 2, 3 ];printSubArrays(arr, 0, 0); // This code is contributed by rutvik_56 </script>", "e": 33432, "s": 32549, "text": null }, { "code": null, "e": 33468, "s": 33432, "text": "[1]\n[1, 2]\n[2]\n[1, 2, 3]\n[2, 3]\n[3]" }, { "code": null, "e": 33488, "s": 33470, "text": "Time Complexity: " }, { "code": null, "e": 33501, "s": 33488, "text": "Mithun Kumar" }, { "code": null, "e": 33514, "s": 33501, "text": "rituraj_jain" }, { "code": null, "e": 33531, "s": 33514, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33541, "s": 33531, "text": "Rajput-Ji" }, { "code": null, "e": 33551, "s": 33541, "text": "rutvik_56" }, { "code": null, "e": 33563, "s": 33551, "text": "sankarsingh" }, { "code": null, "e": 33578, "s": 33563, "text": "jaskeerat10000" }, { "code": null, "e": 33590, "s": 33578, "text": "krisania804" }, { "code": null, "e": 33597, "s": 33590, "text": "Picked" }, { "code": null, "e": 33606, "s": 33597, "text": "subarray" }, { "code": null, "e": 33630, "s": 33606, "text": "Technical Scripter 2018" }, { "code": null, "e": 33637, "s": 33630, "text": "Arrays" }, { "code": null, "e": 33644, "s": 33637, "text": "Python" }, { "code": null, "e": 33654, "s": 33644, "text": "Recursion" }, { "code": null, "e": 33673, "s": 33654, "text": "Technical Scripter" }, { "code": null, "e": 33680, "s": 33673, "text": "Arrays" }, { "code": null, "e": 33690, "s": 33680, "text": "Recursion" }, { "code": null, "e": 33788, "s": 33690, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33856, "s": 33788, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33900, "s": 33856, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33948, "s": 33900, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33971, "s": 33948, "text": "Introduction to Arrays" }, { "code": null, "e": 34003, "s": 33971, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34031, "s": 34003, "text": "Read JSON file using Python" }, { "code": null, "e": 34081, "s": 34031, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 34103, "s": 34081, "text": "Python map() function" } ]
ByteBuffer getFloat() method in Java with Examples - GeeksforGeeks
17 Jun, 2019 The getFloat() method of java.nio.ByteBuffer class is used to read the next four bytes at this buffer’s current position, composing them into a float value according to the current byte order, and then increments the position by four. Syntax: public abstract float getFloat() Return Value: This method returns the float value at the buffer’s current position. Exception: This method throws BufferUnderflowException if there are fewer than four bytes remaining in this buffer. Below are the examples to illustrate the getFloat() method: Examples 1: // Java program to demonstrate// getFloat() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the double value in the bytebuffer bb.asFloatBuffer() .put(12.3f) .put(28.44f); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getFloat() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the Float at this buffer's current position // using getFloat() method float value = bb.getFloat(); // print the float value System.out.println("\n\nByte Value: " + value); // Reads the float at this buffer's next position // using getFloat() method float value1 = bb.getFloat(); // print the float value System.out.print("\nNext Byte Value: " + value1); } catch (BufferUnderflowException e) { System.out.println("\nException Thrown : " + e); } }} Original ByteBuffer: 12.3 28.44 Byte Value: 12.3 Next Byte Value: 28.44 Examples 2: // Java program to demonstrate// getFloat() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the double value in the bytebuffer bb.asFloatBuffer() .put(12.3f) .put(28.44f); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getFloat() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the Float at this buffer's current position // using getFloat() method float value = bb.getFloat(); // print the float value System.out.println("\n\nByte Value: " + value); // Reads the float at this buffer's next position // using getFloat() method float value1 = bb.getFloat(); // print the float value System.out.println("\nNext Byte Value: " + value1); // Reads the float at this buffer's next position // using getFloat() method float value2 = bb.getFloat(); } catch (BufferUnderflowException e) { System.out.println("\nthere are fewer " + "than eight bytes remaining" + " in this buffer"); System.out.println("Exception Thrown : " + e); } }} Original ByteBuffer: 12.3 28.44 Byte Value: 12.3 Next Byte Value: 28.44 there are fewer than eight bytes remaining in this buffer Exception Thrown : java.nio.BufferUnderflowException Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getFloat– The getFloat(int index) method of java.nio.ByteBuffer is used to read four bytes at the given index, composing them into a float value according to the current byte order. Syntax: public abstract float getFloat(int index) Parameters: This method takes index as parameter which is the index from which the Byte will be read. Return Value: This method returns the float value at the given index. Exception: This method throws IndexOutOfBoundsException if index is negative or not smaller than the buffer’s limit. Below are the examples to illustrate the getFloat(int index) method: Examples 1: // Java program to demonstrate// getFloat() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the double value in the bytebuffer bb.asFloatBuffer() .put(12.3f) .put(28.44f); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getFloat() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the Float at this buffer's current position // using getFloat() method float value = bb.getFloat(0); // print the float value System.out.println("\n\nByte Value: " + value); // Reads the float at this buffer's next position // using getFloat() method float value1 = bb.getFloat(4); // print the float value System.out.println("\nNext Byte Value: " + value1); } catch (IndexOutOfBoundsException e) { System.out.println("\nindex is negative or smaller" + " than the buffer's limit, " + "minus seven"); System.out.println("Exception Thrown : " + e); } }} Original ByteBuffer: 12.3 28.44 Byte Value: 12.3 Next Byte Value: 28.44 Examples 2: // Java program to demonstrate// getFloat() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the double value in the bytebuffer bb.asFloatBuffer() .put(12.3f) .put(28.44f); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getFloat() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the Float at this buffer's current position // using getFloat() method float value = bb.getFloat(0); // print the float value System.out.println("\n\nByte Value: " + value); // Reads the float at this buffer's next position // using getFloat() method float value1 = bb.getFloat(6); // print the float value System.out.println("\nNext Byte Value: " + value1); } catch (IndexOutOfBoundsException e) { System.out.println("\nindex is negative or" + " smaller than the buffer's " + "limit, minus seven"); System.out.println("Exception Thrown : " + e); } }} Original ByteBuffer: 12.3 28.44 Byte Value: 12.3 index is negative or smaller than the buffer's limit, minus seven Exception Thrown : java.lang.IndexOutOfBoundsException Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getFloat-int- Java-ByteBuffer Java-Functions Java-NIO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 25827, "s": 25799, "text": "\n17 Jun, 2019" }, { "code": null, "e": 26062, "s": 25827, "text": "The getFloat() method of java.nio.ByteBuffer class is used to read the next four bytes at this buffer’s current position, composing them into a float value according to the current byte order, and then increments the position by four." }, { "code": null, "e": 26070, "s": 26062, "text": "Syntax:" }, { "code": null, "e": 26103, "s": 26070, "text": "public abstract float getFloat()" }, { "code": null, "e": 26187, "s": 26103, "text": "Return Value: This method returns the float value at the buffer’s current position." }, { "code": null, "e": 26303, "s": 26187, "text": "Exception: This method throws BufferUnderflowException if there are fewer than four bytes remaining in this buffer." }, { "code": null, "e": 26363, "s": 26303, "text": "Below are the examples to illustrate the getFloat() method:" }, { "code": null, "e": 26375, "s": 26363, "text": "Examples 1:" }, { "code": "// Java program to demonstrate// getFloat() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the double value in the bytebuffer bb.asFloatBuffer() .put(12.3f) .put(28.44f); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \"); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getFloat() + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the Float at this buffer's current position // using getFloat() method float value = bb.getFloat(); // print the float value System.out.println(\"\\n\\nByte Value: \" + value); // Reads the float at this buffer's next position // using getFloat() method float value1 = bb.getFloat(); // print the float value System.out.print(\"\\nNext Byte Value: \" + value1); } catch (BufferUnderflowException e) { System.out.println(\"\\nException Thrown : \" + e); } }}", "e": 27890, "s": 26375, "text": null }, { "code": null, "e": 27967, "s": 27890, "text": "Original ByteBuffer: \n12.3 28.44 \n\nByte Value: 12.3\n\nNext Byte Value: 28.44\n" }, { "code": null, "e": 27979, "s": 27967, "text": "Examples 2:" }, { "code": "// Java program to demonstrate// getFloat() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the double value in the bytebuffer bb.asFloatBuffer() .put(12.3f) .put(28.44f); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \"); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getFloat() + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the Float at this buffer's current position // using getFloat() method float value = bb.getFloat(); // print the float value System.out.println(\"\\n\\nByte Value: \" + value); // Reads the float at this buffer's next position // using getFloat() method float value1 = bb.getFloat(); // print the float value System.out.println(\"\\nNext Byte Value: \" + value1); // Reads the float at this buffer's next position // using getFloat() method float value2 = bb.getFloat(); } catch (BufferUnderflowException e) { System.out.println(\"\\nthere are fewer \" + \"than eight bytes remaining\" + \" in this buffer\"); System.out.println(\"Exception Thrown : \" + e); } }}", "e": 29799, "s": 27979, "text": null }, { "code": null, "e": 29988, "s": 29799, "text": "Original ByteBuffer: \n12.3 28.44 \n\nByte Value: 12.3\n\nNext Byte Value: 28.44\n\nthere are fewer than eight bytes remaining in this buffer\nException Thrown : java.nio.BufferUnderflowException\n" }, { "code": null, "e": 30076, "s": 29988, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getFloat–" }, { "code": null, "e": 30248, "s": 30076, "text": "The getFloat(int index) method of java.nio.ByteBuffer is used to read four bytes at the given index, composing them into a float value according to the current byte order." }, { "code": null, "e": 30256, "s": 30248, "text": "Syntax:" }, { "code": null, "e": 30298, "s": 30256, "text": "public abstract float getFloat(int index)" }, { "code": null, "e": 30400, "s": 30298, "text": "Parameters: This method takes index as parameter which is the index from which the Byte will be read." }, { "code": null, "e": 30470, "s": 30400, "text": "Return Value: This method returns the float value at the given index." }, { "code": null, "e": 30587, "s": 30470, "text": "Exception: This method throws IndexOutOfBoundsException if index is negative or not smaller than the buffer’s limit." }, { "code": null, "e": 30656, "s": 30587, "text": "Below are the examples to illustrate the getFloat(int index) method:" }, { "code": null, "e": 30668, "s": 30656, "text": "Examples 1:" }, { "code": "// Java program to demonstrate// getFloat() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the double value in the bytebuffer bb.asFloatBuffer() .put(12.3f) .put(28.44f); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \"); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getFloat() + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the Float at this buffer's current position // using getFloat() method float value = bb.getFloat(0); // print the float value System.out.println(\"\\n\\nByte Value: \" + value); // Reads the float at this buffer's next position // using getFloat() method float value1 = bb.getFloat(4); // print the float value System.out.println(\"\\nNext Byte Value: \" + value1); } catch (IndexOutOfBoundsException e) { System.out.println(\"\\nindex is negative or smaller\" + \" than the buffer's limit, \" + \"minus seven\"); System.out.println(\"Exception Thrown : \" + e); } }}", "e": 32358, "s": 30668, "text": null }, { "code": null, "e": 32435, "s": 32358, "text": "Original ByteBuffer: \n12.3 28.44 \n\nByte Value: 12.3\n\nNext Byte Value: 28.44\n" }, { "code": null, "e": 32447, "s": 32435, "text": "Examples 2:" }, { "code": "// Java program to demonstrate// getFloat() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the double value in the bytebuffer bb.asFloatBuffer() .put(12.3f) .put(28.44f); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \"); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getFloat() + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the Float at this buffer's current position // using getFloat() method float value = bb.getFloat(0); // print the float value System.out.println(\"\\n\\nByte Value: \" + value); // Reads the float at this buffer's next position // using getFloat() method float value1 = bb.getFloat(6); // print the float value System.out.println(\"\\nNext Byte Value: \" + value1); } catch (IndexOutOfBoundsException e) { System.out.println(\"\\nindex is negative or\" + \" smaller than the buffer's \" + \"limit, minus seven\"); System.out.println(\"Exception Thrown : \" + e); } }}", "e": 34137, "s": 32447, "text": null }, { "code": null, "e": 34312, "s": 34137, "text": "Original ByteBuffer: \n12.3 28.44 \n\nByte Value: 12.3\n\nindex is negative or smaller than the buffer's limit, minus seven\nException Thrown : java.lang.IndexOutOfBoundsException\n" }, { "code": null, "e": 34404, "s": 34312, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getFloat-int-" }, { "code": null, "e": 34420, "s": 34404, "text": "Java-ByteBuffer" }, { "code": null, "e": 34435, "s": 34420, "text": "Java-Functions" }, { "code": null, "e": 34452, "s": 34435, "text": "Java-NIO package" }, { "code": null, "e": 34457, "s": 34452, "text": "Java" }, { "code": null, "e": 34462, "s": 34457, "text": "Java" }, { "code": null, "e": 34560, "s": 34462, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34590, "s": 34560, "text": "HashMap in Java with Examples" }, { "code": null, "e": 34605, "s": 34590, "text": "Stream In Java" }, { "code": null, "e": 34624, "s": 34605, "text": "Interfaces in Java" }, { "code": null, "e": 34655, "s": 34624, "text": "How to iterate any Map in Java" }, { "code": null, "e": 34673, "s": 34655, "text": "ArrayList in Java" }, { "code": null, "e": 34705, "s": 34673, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 34725, "s": 34705, "text": "Stack Class in Java" }, { "code": null, "e": 34749, "s": 34725, "text": "Singleton Class in Java" }, { "code": null, "e": 34781, "s": 34749, "text": "Multidimensional Arrays in Java" } ]
Explain the importance of Doctype in HTML ? - GeeksforGeeks
20 Aug, 2021 Doctype in HTML: HTML Doctype is most often written at the very first element of the entire HTML document. It remains wrapped inside angle brackets but it is not a tag. It is a statement or declaration. Doctype stands for Document Type. It is a statement to declare the type of the document. With the help of this statement, the developer let the browser know that the following document is an HTML document. Meaning of Doctype: A doctype or document type declaration (DTD) is an instruction that tells the web browser about the markup language in which the current page is written. The Doctype is not an element or tag, it lets the browser know about the version of or standard of HTML or any other markup language that is being used in the document. Syntax: In HTML5 the syntax to declare doctype is very simple but in older versions like HTML4.0.1 or XHTML 1.1, it was a little bit more complex. In HTML 5 and above versions: <!DOCTYPE html> In HTML 4.0.1 Strict: In HTML 4.01 Strict document type definition (DTD) all those elements and attributes are included that do not appear in frameset documents or that have not been deprecated. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> In HTML 4.0.1 Transitional: In HTML 4.01 Transitional document type definition (DTD) allows some older PUBLIC attributes that have been deprecated. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> In HTML 4.01 Frameset: In HTML 4.01 Frameset document type definition (DTD),Frames can be used. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> In XHTML 1.1: In XHTML 1.1 Strict document type definition (DTD), deprecated tags are not supported and the code must be written according to the XML Specification. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> In XHTML 1.0: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Note: The XHTML 1.1 and XHTML 1.0 also have their respective strict, transitional and frameset type declarations. Useful Tips: In HTML5, if the developer skips adding the doctype declaration, the system will automatically add it during runtime. The doctype declaration is not upper and lower case sensitive. <!-- All of them are correct conventions--> <!DOCTYPE html> <!DocType html> <!Doctype html> <!doctype html> Significance of Doctype declaration: Doctype enforces the browser to make the best effort to follow the exact specifications being made in the HTML document while rendering. It prevents the browser from switching to quirks mode ( The non-standard behavior of the layout in Navigator 4 and Internet Explorer 5) Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Basics HTML-Questions Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n20 Aug, 2021" }, { "code": null, "e": 26549, "s": 26139, "text": "Doctype in HTML: HTML Doctype is most often written at the very first element of the entire HTML document. It remains wrapped inside angle brackets but it is not a tag. It is a statement or declaration. Doctype stands for Document Type. It is a statement to declare the type of the document. With the help of this statement, the developer let the browser know that the following document is an HTML document." }, { "code": null, "e": 26892, "s": 26549, "text": "Meaning of Doctype: A doctype or document type declaration (DTD) is an instruction that tells the web browser about the markup language in which the current page is written. The Doctype is not an element or tag, it lets the browser know about the version of or standard of HTML or any other markup language that is being used in the document." }, { "code": null, "e": 27039, "s": 26892, "text": "Syntax: In HTML5 the syntax to declare doctype is very simple but in older versions like HTML4.0.1 or XHTML 1.1, it was a little bit more complex." }, { "code": null, "e": 27069, "s": 27039, "text": "In HTML 5 and above versions:" }, { "code": null, "e": 27085, "s": 27069, "text": "<!DOCTYPE html>" }, { "code": null, "e": 27280, "s": 27085, "text": "In HTML 4.0.1 Strict: In HTML 4.01 Strict document type definition (DTD) all those elements and attributes are included that do not appear in frameset documents or that have not been deprecated." }, { "code": null, "e": 27386, "s": 27280, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \n \"http://www.w3.org/TR/html4/strict.dtd\">" }, { "code": null, "e": 27534, "s": 27386, "text": "In HTML 4.0.1 Transitional: In HTML 4.01 Transitional document type definition (DTD) allows some older PUBLIC attributes that have been deprecated." }, { "code": null, "e": 27659, "s": 27534, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \n \"http://www.w3.org/TR/html4/loose.dtd\">" }, { "code": null, "e": 27755, "s": 27659, "text": "In HTML 4.01 Frameset: In HTML 4.01 Frameset document type definition (DTD),Frames can be used." }, { "code": null, "e": 27877, "s": 27755, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \n \"http://www.w3.org/TR/html4/frameset.dtd\">" }, { "code": null, "e": 28042, "s": 27877, "text": "In XHTML 1.1: In XHTML 1.1 Strict document type definition (DTD), deprecated tags are not supported and the code must be written according to the XML Specification." }, { "code": null, "e": 28160, "s": 28042, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \n \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" }, { "code": null, "e": 28174, "s": 28160, "text": "In XHTML 1.0:" }, { "code": null, "e": 28298, "s": 28174, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">" }, { "code": null, "e": 28412, "s": 28298, "text": "Note: The XHTML 1.1 and XHTML 1.0 also have their respective strict, transitional and frameset type declarations." }, { "code": null, "e": 28425, "s": 28412, "text": "Useful Tips:" }, { "code": null, "e": 28543, "s": 28425, "text": "In HTML5, if the developer skips adding the doctype declaration, the system will automatically add it during runtime." }, { "code": null, "e": 28606, "s": 28543, "text": "The doctype declaration is not upper and lower case sensitive." }, { "code": null, "e": 28715, "s": 28606, "text": "<!-- All of them are correct conventions-->\n\n<!DOCTYPE html>\n<!DocType html>\n<!Doctype html>\n<!doctype html>" }, { "code": null, "e": 28752, "s": 28715, "text": "Significance of Doctype declaration:" }, { "code": null, "e": 28889, "s": 28752, "text": "Doctype enforces the browser to make the best effort to follow the exact specifications being made in the HTML document while rendering." }, { "code": null, "e": 29025, "s": 28889, "text": "It prevents the browser from switching to quirks mode ( The non-standard behavior of the layout in Navigator 4 and Internet Explorer 5)" }, { "code": null, "e": 29162, "s": 29025, "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": 29174, "s": 29162, "text": "HTML-Basics" }, { "code": null, "e": 29189, "s": 29174, "text": "HTML-Questions" }, { "code": null, "e": 29196, "s": 29189, "text": "Picked" }, { "code": null, "e": 29201, "s": 29196, "text": "HTML" }, { "code": null, "e": 29218, "s": 29201, "text": "Web Technologies" }, { "code": null, "e": 29223, "s": 29218, "text": "HTML" }, { "code": null, "e": 29321, "s": 29223, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29345, "s": 29321, "text": "REST API (Introduction)" }, { "code": null, "e": 29386, "s": 29345, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 29423, "s": 29386, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29452, "s": 29423, "text": "Form validation using jQuery" }, { "code": null, "e": 29472, "s": 29452, "text": "Angular File Upload" }, { "code": null, "e": 29512, "s": 29472, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29545, "s": 29512, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29590, "s": 29545, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29633, "s": 29590, "text": "How to fetch data from an API in ReactJS ?" } ]
How to print range of basic data types without any library function and constant in C? - GeeksforGeeks
25 Aug, 2021 How to write C code to print range of basic data types like int, char, short int, unsigned int, unsigned char etc? It is assumed that signed numbers are stored in 2’s complement form. We strongly recommend to minimize the browser and try this yourself first. Following are the steps to be followed for unsigned data types. 1) Find number of bytes for a given data type using sizeof operator. 2) Find number of bits by multiplying result of sizeof with 8. 3) The minimum value for an unsigned type is always 0 irrespective of data type. 4) The maximum value of an unsigned type is (1 << n) – 1 where n is number of bits needed in data type. For example for char which typically requires 8 bits, the maximum value is 255. Following are the steps to be followed for signed data type. 1) Find number of bytes for a given data type using sizeof operator. 2) Find number of bits by multiplying result of sizeof with 8. 3) The minimum value for a signed type is -(1 << (n-1)). For example for char which typically requires 8 bits, the minimum value is -128. 4) The maximum value of a data type is (1 << (n-1)) – 1 where n is number of bits needed in data type. For example for char which typically requires 8 bits, the maximum value is 127.Following is C code to demonstrate above idea. C C++ // C program to print range of basic data types#include <stdio.h> // Prints min and max value for a signed typevoid printUnsignedRange(size_t bytes){ int bits = 8*bytes; // Note that the value of 'to' is "(1 << bits) - 1" // Writing it in following way doesn't cause overflow unsigned int to = ((1 << (bits-1)) - 1) + (1 << (bits-1)) ; printf(" range is from %u to %u \n", 0, to);} // Prints min and max value for an unsigned typevoid printSignedRange(size_t bytes){ int bits = 8*bytes; int from = -(1 << (bits-1)); int to = (1 << (bits-1)) - 1; printf(" range is from %d to %d\n", from, to);} int main(){ printf("signed char: "); printSignedRange(sizeof(char)); printf("unsigned char: "); printUnsignedRange(sizeof(unsigned char)); printf("signed int: "); printSignedRange(sizeof(int)); printf("unsigned int: "); printUnsignedRange(sizeof(unsigned int)); printf("signed short int: "); printSignedRange(sizeof(short int)); printf("unsigned short int: "); printUnsignedRange(sizeof(unsigned short int)); return 0;} #include <iostream> /*1ULL is used to tell compiler use 1 which is having data type unsigned long long*/using namespace std; /*if we use 1 only it will be explained as 1 of data type int which will further */ /*give us a wrong output by giving a warning: left shift count >= width of type [-Wshift-count-overflow]*/int main() { cout<<"signed char: the range is from "<<(1 << ((sizeof(char)*8)))<<" to "<< ~(1 << ((sizeof(char)*8)-1)); cout<<"\nunsigned char: the range is from "<<0<<" to "<< ~((1 << ((sizeof(char)*8)-1))+(1 << (sizeof(char)*8))); cout<<"\nsigned int: the range is from "<<(1ULL << ((unsigned long long)(sizeof(int)*8)))<<" to "<< ~(1ULL << ((unsigned long long)(sizeof(int)*8)-1ULL)); cout<<"\nunsigned int: the range is from "<<0<<" to "<< ~((1ULL << ((unsigned long long)(sizeof(int)*8)-1ULL))+(1ULL << (unsigned long long)(sizeof(int)*8))); cout<<"\nsigned float: the range is from "<<(1ULL << ((unsigned long long)(sizeof(float)*8)))<<" to "<< ~(1ULL << ((unsigned long long)(sizeof(float)*8)-1ULL)); cout<<"\nunsigned float: the range is from "<<0<<" to "<< ~((1ULL << ((unsigned long long)(sizeof(float)*8)-1ULL))+(1ULL << (unsigned long long)(sizeof(float)*8))); return 0;} Output: signed char: range is from -128 to 127 unsigned char: range is from 0 to 255 signed int: range is from -2147483648 to 2147483647 unsigned int: range is from 0 to 4294967295 signed short int: range is from -32768 to 32767 unsigned short int: range is from 0 to 65535 Note that the above functions cannot be used for float. Also, the above program may not work for data types bigger that int, like ‘long long int’. We can make it work for bigger types by changing data type of ‘to’ and ‘from’ to long long int.This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above discjockysubhra C-Data Types C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Ways to copy a vector in C++ Smart Pointers in C++ and How to Use Them Understanding "extern" keyword in C Multiple Inheritance in C++ How to split a string in C/C++, Python and Java?
[ { "code": null, "e": 25477, "s": 25449, "text": "\n25 Aug, 2021" }, { "code": null, "e": 25736, "s": 25477, "text": "How to write C code to print range of basic data types like int, char, short int, unsigned int, unsigned char etc? It is assumed that signed numbers are stored in 2’s complement form. We strongly recommend to minimize the browser and try this yourself first." }, { "code": null, "e": 26197, "s": 25736, "text": "Following are the steps to be followed for unsigned data types. 1) Find number of bytes for a given data type using sizeof operator. 2) Find number of bits by multiplying result of sizeof with 8. 3) The minimum value for an unsigned type is always 0 irrespective of data type. 4) The maximum value of an unsigned type is (1 << n) – 1 where n is number of bits needed in data type. For example for char which typically requires 8 bits, the maximum value is 255." }, { "code": null, "e": 26759, "s": 26197, "text": "Following are the steps to be followed for signed data type. 1) Find number of bytes for a given data type using sizeof operator. 2) Find number of bits by multiplying result of sizeof with 8. 3) The minimum value for a signed type is -(1 << (n-1)). For example for char which typically requires 8 bits, the minimum value is -128. 4) The maximum value of a data type is (1 << (n-1)) – 1 where n is number of bits needed in data type. For example for char which typically requires 8 bits, the maximum value is 127.Following is C code to demonstrate above idea. " }, { "code": null, "e": 26761, "s": 26759, "text": "C" }, { "code": null, "e": 26765, "s": 26761, "text": "C++" }, { "code": "// C program to print range of basic data types#include <stdio.h> // Prints min and max value for a signed typevoid printUnsignedRange(size_t bytes){ int bits = 8*bytes; // Note that the value of 'to' is \"(1 << bits) - 1\" // Writing it in following way doesn't cause overflow unsigned int to = ((1 << (bits-1)) - 1) + (1 << (bits-1)) ; printf(\" range is from %u to %u \\n\", 0, to);} // Prints min and max value for an unsigned typevoid printSignedRange(size_t bytes){ int bits = 8*bytes; int from = -(1 << (bits-1)); int to = (1 << (bits-1)) - 1; printf(\" range is from %d to %d\\n\", from, to);} int main(){ printf(\"signed char: \"); printSignedRange(sizeof(char)); printf(\"unsigned char: \"); printUnsignedRange(sizeof(unsigned char)); printf(\"signed int: \"); printSignedRange(sizeof(int)); printf(\"unsigned int: \"); printUnsignedRange(sizeof(unsigned int)); printf(\"signed short int: \"); printSignedRange(sizeof(short int)); printf(\"unsigned short int: \"); printUnsignedRange(sizeof(unsigned short int)); return 0;}", "e": 27850, "s": 26765, "text": null }, { "code": "#include <iostream> /*1ULL is used to tell compiler use 1 which is having data type unsigned long long*/using namespace std; /*if we use 1 only it will be explained as 1 of data type int which will further */ /*give us a wrong output by giving a warning: left shift count >= width of type [-Wshift-count-overflow]*/int main() { cout<<\"signed char: the range is from \"<<(1 << ((sizeof(char)*8)))<<\" to \"<< ~(1 << ((sizeof(char)*8)-1)); cout<<\"\\nunsigned char: the range is from \"<<0<<\" to \"<< ~((1 << ((sizeof(char)*8)-1))+(1 << (sizeof(char)*8))); cout<<\"\\nsigned int: the range is from \"<<(1ULL << ((unsigned long long)(sizeof(int)*8)))<<\" to \"<< ~(1ULL << ((unsigned long long)(sizeof(int)*8)-1ULL)); cout<<\"\\nunsigned int: the range is from \"<<0<<\" to \"<< ~((1ULL << ((unsigned long long)(sizeof(int)*8)-1ULL))+(1ULL << (unsigned long long)(sizeof(int)*8))); cout<<\"\\nsigned float: the range is from \"<<(1ULL << ((unsigned long long)(sizeof(float)*8)))<<\" to \"<< ~(1ULL << ((unsigned long long)(sizeof(float)*8)-1ULL)); cout<<\"\\nunsigned float: the range is from \"<<0<<\" to \"<< ~((1ULL << ((unsigned long long)(sizeof(float)*8)-1ULL))+(1ULL << (unsigned long long)(sizeof(float)*8))); return 0;}", "e": 29141, "s": 27850, "text": null }, { "code": null, "e": 29150, "s": 29141, "text": "Output: " }, { "code": null, "e": 29422, "s": 29150, "text": "signed char: range is from -128 to 127\nunsigned char: range is from 0 to 255\nsigned int: range is from -2147483648 to 2147483647\nunsigned int: range is from 0 to 4294967295\nsigned short int: range is from -32768 to 32767\nunsigned short int: range is from 0 to 65535" }, { "code": null, "e": 29833, "s": 29422, "text": "Note that the above functions cannot be used for float. Also, the above program may not work for data types bigger that int, like ‘long long int’. We can make it work for bigger types by changing data type of ‘to’ and ‘from’ to long long int.This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 29849, "s": 29833, "text": "discjockysubhra" }, { "code": null, "e": 29862, "s": 29849, "text": "C-Data Types" }, { "code": null, "e": 29873, "s": 29862, "text": "C Language" }, { "code": null, "e": 29971, "s": 29873, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30009, "s": 29971, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 30035, "s": 30009, "text": "Exception Handling in C++" }, { "code": null, "e": 30055, "s": 30035, "text": "Multithreading in C" }, { "code": null, "e": 30077, "s": 30055, "text": "'this' pointer in C++" }, { "code": null, "e": 30118, "s": 30077, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 30147, "s": 30118, "text": "Ways to copy a vector in C++" }, { "code": null, "e": 30189, "s": 30147, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 30225, "s": 30189, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 30253, "s": 30225, "text": "Multiple Inheritance in C++" } ]
Print n x n spiral matrix using O(1) extra space - GeeksforGeeks
15 May, 2022 Given a number n, print a n x n spiral matrix (of numbers from 1 to n x n) in clockwise direction using O(1) space. Example : Input: n = 5 Output: 25 24 23 22 21 10 9 8 7 20 11 2 1 6 19 12 3 4 5 18 13 14 15 16 17 We strongly recommend you to minimize your browser and try this yourself first.The solution becomes simple if extra space is allowed. We allocate memory for n x n matrix and for every element starting from n*n to 1, we start filling out matrix in spiral order. To maintain the spiral order four loops are used, each for top, right, bottom and left corner of the matrix. But how to solve it in O(1) space? An n x n matrix has ceil(n/2) square cycles. A cycle is formed by ith row, (n-i+1)th column, (n-i+1)th row and ith column where i varies from 1 to ceil(n/2). 25 24 23 22 21 10 9 8 7 20 11 2 1 6 19 12 3 4 5 18 13 14 15 16 17 The first cycle is formed by elements of its first row, last column, last row and first column (marked by red). The first cycle consists of elements from n*n to (n-2)*(n-2) + 1. i.e. from 25 to 10.The second cycle is formed by elements of second row, second-last column, second-last row and second column(marked by blue). The second cycle consists of elements from (n-2)*(n-2) to (n-4)*(n-4) + 1. i.e. from 9 to 2.The third cycle is formed by elements of third row, third-last column, third-last row and third column(marked by black). The third cycle consists of elements from (n-4)*(n-4) to 1. i.e. only 1. The first cycle is formed by elements of its first row, last column, last row and first column (marked by red). The first cycle consists of elements from n*n to (n-2)*(n-2) + 1. i.e. from 25 to 10. The second cycle is formed by elements of second row, second-last column, second-last row and second column(marked by blue). The second cycle consists of elements from (n-2)*(n-2) to (n-4)*(n-4) + 1. i.e. from 9 to 2. The third cycle is formed by elements of third row, third-last column, third-last row and third column(marked by black). The third cycle consists of elements from (n-4)*(n-4) to 1. i.e. only 1. The idea is for each square cycle, we associate a marker to it. For outer cycle, the marker will have value 0, for second cycle, it will have value 1 and for third cycle it has value 2. In general for a n x n matrix, i’th cycle will have marker value of i – 1.If we divide the matrix into two parts, upper right triangle(marked by orange) and lower left triangle(marked by green), then using the marker x, we can easily calculate the value that will be present at the index(i, j) in any n x n spiral matrix using the below formula – 25 24 23 22 21 10 9 8 7 20 11 2 1 6 19 12 3 4 5 18 13 14 15 16 17 For upper right half, mat[i][j] = (n-2*x)*(n-2*x)-(i-x)-(j-x) For lower left half, mat[i][j] = (n-2*x-2)*(n-2*x-2) + (i-x) + (j-x) Below is the implementation of the idea. C++ C Java Python3 C# PHP Javascript // C++ program to print a n x n spiral matrix// in clockwise direction using O(1) space#include <bits/stdc++.h>using namespace std; // Prints spiral matrix of size n x n containing// numbers from 1 to n x nvoid printSpiral(int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // x stores the layer in which (i, j)th // element lies int x; // Finds minimum of four inputs x = min(min(i, j), min(n-1-i, n-1-j)); // For upper right half if (i <= j) printf("%d\t ", (n-2*x)*(n-2*x) - (i-x) - (j-x)); // for lower left half else printf("%d\t ", (n-2*x-2)*(n-2*x-2) + (i-x) + (j-x)); } printf("\n"); }} // Driver codeint main(){ int n = 5; // print a n x n spiral matrix in O(1) space printSpiral(n); return 0;} // C program to print a n x n spiral matrix// in clockwise direction using O(1) space#include <stdio.h> // Prints spiral matrix of size n x n containing// numbers from 1 to n x nint min(int a,int b){ int min = a; if(min > b) min = b; return min;}void printSpiral(int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // x stores the layer in which (i, j)th // element lies int x; // Finds minimum of four inputs x = min(min(i, j), min(n-1-i, n-1-j)); // For upper right half if (i <= j) printf("%d\t ", (n-2*x)*(n-2*x) - (i-x) - (j-x)); // for lower left half else printf("%d\t ", (n-2*x-2)*(n-2*x-2) + (i-x) + (j-x)); } printf("\n"); }} // Driver codeint main(){ int n = 5; // print a n x n spiral matrix in O(1) space printSpiral(n); return 0;} // This code is contributed by kothavvsaakash. // Java program to print a n x n spiral matrix// in clockwise direction using O(1) space import java.io.*;import java.util.*; class GFG { // Prints spiral matrix of size n x n // containing numbers from 1 to n x n static void printSpiral(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // x stores the layer in which (i, j)th // element lies int x; // Finds minimum of four inputs x = Math.min(Math.min(i, j), Math.min(n - 1 - i, n - 1 - j)); // For upper right half if (i <= j) System.out.print((n - 2 * x) * (n - 2 * x) - (i - x) - (j - x) + "\t"); // for lower left half else System.out.print((n - 2 * x - 2) * (n - 2 * x - 2) + (i - x) + (j - x) + "\t"); } System.out.println(); } } // Driver code public static void main(String args[]) { int n = 5; // print a n x n spiral matrix in O(1) space printSpiral(n); }} /*This code is contributed by Nikita Tiwari.*/ # Python3 program to print a n x n spiral matrix# in clockwise direction using O(1) space # Prints spiral matrix of size n x n# containing numbers from 1 to n x ndef printSpiral(n) : for i in range(0, n) : for j in range(0, n) : # Finds minimum of four inputs x = min(min(i, j), min(n - 1 - i, n - 1 - j)) # For upper right half if (i <= j) : print((n - 2 * x) * (n - 2 * x) - (i - x)- (j - x), end = "\t") # For lower left half else : print(((n - 2 * x - 2) * (n - 2 * x - 2) + (i - x) + (j - x)), end = "\t") print() # Driver coden = 5 # print a n x n spiral matrix# in O(1) spaceprintSpiral(n) # This code is contributed by Nikita Tiwari. // C# program to print a n x n// spiral matrix in clockwise// direction using O(1) spaceusing System; class GFG { // Prints spiral matrix of // size n x n containing // numbers from 1 to n x n static void printSpiral(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // x stores the layer in which // (i, j)th element lies int x; // Finds minimum of four inputs x = Math.Min(Math.Min(i, j), Math.Min(n - 1 - i, n - 1 - j)); // For upper right half if (i <= j) Console.Write((n - 2 * x) * (n - 2 * x) - (i - x) - (j - x) + "\t"); // for lower left half else Console.Write((n - 2 * x - 2) * (n - 2 * x - 2) + (i - x) + (j - x) + "\t"); } Console.WriteLine(); } } // Driver code public static void Main() { int n = 5; // print a n x n spiral // matrix in O(1) space printSpiral(n); }} // This code is contributed by KRV <?php// PHP program to print a n x n// spiral matrix in clockwise// direction using O(1) space // Prints spiral matrix of size// n x n containing numbers// from 1 to n x nfunction printSpiral($n){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { // x stores the layer in // which (i, j)th element lies $x; // Finds minimum of four inputs $x = min(min($i, $j), min($n - 1 - $i, $n - 1 - $j)); // For upper right half if ($i <= $j) echo "\t ", ($n - 2 * $x) * ($n - 2 * $x) - ($i - $x) - ($j - $x); // for lower left half else echo "\t ", ($n - 2 * $x - 2) * ($n - 2 * $x - 2) + ($i - $x) + ($j - $x); } echo "\n"; }} // Driver code$n = 5; // print a n x n spiral// matrix in O(1) spaceprintSpiral($n); // This code is contributed by ajit?> <script> // Javascript program to print a// n x n spiral matrix in clockwise// direction using O(1) space // Prints spiral matrix of size// n x n containing numbers from// 1 to n x nfunction printSpiral(n){ for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { // x stores the layer in which (i, j)th // element lies let x; // Finds minimum of four inputs x = Math.min(Math.min(i, j), Math.min(n - 1 - i, n - 1 - j)); // For upper right half if (i <= j) document.write(`${(n - 2 * x) * (n - 2 * x) - (i - x) - (j - x)} `); // For lower left half else document.write(`${(n - 2 * x - 2) * (n - 2 * x - 2) + (i - x) + (j - x)} `); } document.write("<br>"); }} // Driver codelet n = 5; // Print a n x n spiral matrix in O(1) spaceprintSpiral(n); // This code is contributed by subham348 </script> Output : 25 24 23 22 21 10 9 8 7 20 11 2 1 6 19 12 3 4 5 18 13 14 15 16 17 Exercise For a given number n, print a n x n spiral matrix in counter clockwise direction using O(1) space.This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above KRV jit_t subham348 kothavvsaakash pattern-printing spiral Matrix pattern-printing Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Efficiently compute sums of diagonals of a matrix Flood fill Algorithm - how to implement fill() in paint? Check for possible path in 2D matrix Zigzag (or diagonal) traversal of Matrix Mathematics | L U Decomposition of a System of Linear Equations Python program to add two Matrices Unique paths in a Grid with Obstacles A Boolean Matrix Question Shortest distance between two cells in a matrix or grid Breadth First Traversal ( BFS ) on a 2D array
[ { "code": null, "e": 26165, "s": 26137, "text": "\n15 May, 2022" }, { "code": null, "e": 26282, "s": 26165, "text": "Given a number n, print a n x n spiral matrix (of numbers from 1 to n x n) in clockwise direction using O(1) space. " }, { "code": null, "e": 26293, "s": 26282, "text": "Example : " }, { "code": null, "e": 26389, "s": 26293, "text": "Input: n = 5\nOutput:\n25 24 23 22 21\n10 9 8 7 20\n11 2 1 6 19\n12 3 4 5 18\n13 14 15 16 17" }, { "code": null, "e": 26759, "s": 26389, "text": "We strongly recommend you to minimize your browser and try this yourself first.The solution becomes simple if extra space is allowed. We allocate memory for n x n matrix and for every element starting from n*n to 1, we start filling out matrix in spiral order. To maintain the spiral order four loops are used, each for top, right, bottom and left corner of the matrix." }, { "code": null, "e": 26954, "s": 26759, "text": "But how to solve it in O(1) space? An n x n matrix has ceil(n/2) square cycles. A cycle is formed by ith row, (n-i+1)th column, (n-i+1)th row and ith column where i varies from 1 to ceil(n/2). " }, { "code": null, "e": 27030, "s": 26954, "text": "25 24 23 22 21 \n10 9 8 7 20\n11 2 1 6 19\n12 3 4 5 18\n13 14 15 16 17" }, { "code": null, "e": 27638, "s": 27030, "text": "The first cycle is formed by elements of its first row, last column, last row and first column (marked by red). The first cycle consists of elements from n*n to (n-2)*(n-2) + 1. i.e. from 25 to 10.The second cycle is formed by elements of second row, second-last column, second-last row and second column(marked by blue). The second cycle consists of elements from (n-2)*(n-2) to (n-4)*(n-4) + 1. i.e. from 9 to 2.The third cycle is formed by elements of third row, third-last column, third-last row and third column(marked by black). The third cycle consists of elements from (n-4)*(n-4) to 1. i.e. only 1." }, { "code": null, "e": 27836, "s": 27638, "text": "The first cycle is formed by elements of its first row, last column, last row and first column (marked by red). The first cycle consists of elements from n*n to (n-2)*(n-2) + 1. i.e. from 25 to 10." }, { "code": null, "e": 28054, "s": 27836, "text": "The second cycle is formed by elements of second row, second-last column, second-last row and second column(marked by blue). The second cycle consists of elements from (n-2)*(n-2) to (n-4)*(n-4) + 1. i.e. from 9 to 2." }, { "code": null, "e": 28248, "s": 28054, "text": "The third cycle is formed by elements of third row, third-last column, third-last row and third column(marked by black). The third cycle consists of elements from (n-4)*(n-4) to 1. i.e. only 1." }, { "code": null, "e": 28782, "s": 28248, "text": "The idea is for each square cycle, we associate a marker to it. For outer cycle, the marker will have value 0, for second cycle, it will have value 1 and for third cycle it has value 2. In general for a n x n matrix, i’th cycle will have marker value of i – 1.If we divide the matrix into two parts, upper right triangle(marked by orange) and lower left triangle(marked by green), then using the marker x, we can easily calculate the value that will be present at the index(i, j) in any n x n spiral matrix using the below formula – " }, { "code": null, "e": 28867, "s": 28782, "text": "25 24 23 22 21 \n10 9 8 7 20 \n11 2 1 6 19 \n12 3 4 5 18 \n13 14 15 16 17 " }, { "code": null, "e": 28999, "s": 28867, "text": "For upper right half,\nmat[i][j] = (n-2*x)*(n-2*x)-(i-x)-(j-x)\n\nFor lower left half,\nmat[i][j] = (n-2*x-2)*(n-2*x-2) + (i-x) + (j-x)" }, { "code": null, "e": 29041, "s": 28999, "text": "Below is the implementation of the idea. " }, { "code": null, "e": 29045, "s": 29041, "text": "C++" }, { "code": null, "e": 29047, "s": 29045, "text": "C" }, { "code": null, "e": 29052, "s": 29047, "text": "Java" }, { "code": null, "e": 29060, "s": 29052, "text": "Python3" }, { "code": null, "e": 29063, "s": 29060, "text": "C#" }, { "code": null, "e": 29067, "s": 29063, "text": "PHP" }, { "code": null, "e": 29078, "s": 29067, "text": "Javascript" }, { "code": "// C++ program to print a n x n spiral matrix// in clockwise direction using O(1) space#include <bits/stdc++.h>using namespace std; // Prints spiral matrix of size n x n containing// numbers from 1 to n x nvoid printSpiral(int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // x stores the layer in which (i, j)th // element lies int x; // Finds minimum of four inputs x = min(min(i, j), min(n-1-i, n-1-j)); // For upper right half if (i <= j) printf(\"%d\\t \", (n-2*x)*(n-2*x) - (i-x) - (j-x)); // for lower left half else printf(\"%d\\t \", (n-2*x-2)*(n-2*x-2) + (i-x) + (j-x)); } printf(\"\\n\"); }} // Driver codeint main(){ int n = 5; // print a n x n spiral matrix in O(1) space printSpiral(n); return 0;}", "e": 30020, "s": 29078, "text": null }, { "code": "// C program to print a n x n spiral matrix// in clockwise direction using O(1) space#include <stdio.h> // Prints spiral matrix of size n x n containing// numbers from 1 to n x nint min(int a,int b){ int min = a; if(min > b) min = b; return min;}void printSpiral(int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // x stores the layer in which (i, j)th // element lies int x; // Finds minimum of four inputs x = min(min(i, j), min(n-1-i, n-1-j)); // For upper right half if (i <= j) printf(\"%d\\t \", (n-2*x)*(n-2*x) - (i-x) - (j-x)); // for lower left half else printf(\"%d\\t \", (n-2*x-2)*(n-2*x-2) + (i-x) + (j-x)); } printf(\"\\n\"); }} // Driver codeint main(){ int n = 5; // print a n x n spiral matrix in O(1) space printSpiral(n); return 0;} // This code is contributed by kothavvsaakash.", "e": 31059, "s": 30020, "text": null }, { "code": "// Java program to print a n x n spiral matrix// in clockwise direction using O(1) space import java.io.*;import java.util.*; class GFG { // Prints spiral matrix of size n x n // containing numbers from 1 to n x n static void printSpiral(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // x stores the layer in which (i, j)th // element lies int x; // Finds minimum of four inputs x = Math.min(Math.min(i, j), Math.min(n - 1 - i, n - 1 - j)); // For upper right half if (i <= j) System.out.print((n - 2 * x) * (n - 2 * x) - (i - x) - (j - x) + \"\\t\"); // for lower left half else System.out.print((n - 2 * x - 2) * (n - 2 * x - 2) + (i - x) + (j - x) + \"\\t\"); } System.out.println(); } } // Driver code public static void main(String args[]) { int n = 5; // print a n x n spiral matrix in O(1) space printSpiral(n); }} /*This code is contributed by Nikita Tiwari.*/", "e": 32327, "s": 31059, "text": null }, { "code": "# Python3 program to print a n x n spiral matrix# in clockwise direction using O(1) space # Prints spiral matrix of size n x n# containing numbers from 1 to n x ndef printSpiral(n) : for i in range(0, n) : for j in range(0, n) : # Finds minimum of four inputs x = min(min(i, j), min(n - 1 - i, n - 1 - j)) # For upper right half if (i <= j) : print((n - 2 * x) * (n - 2 * x) - (i - x)- (j - x), end = \"\\t\") # For lower left half else : print(((n - 2 * x - 2) * (n - 2 * x - 2) + (i - x) + (j - x)), end = \"\\t\") print() # Driver coden = 5 # print a n x n spiral matrix# in O(1) spaceprintSpiral(n) # This code is contributed by Nikita Tiwari.", "e": 33187, "s": 32327, "text": null }, { "code": "// C# program to print a n x n// spiral matrix in clockwise// direction using O(1) spaceusing System; class GFG { // Prints spiral matrix of // size n x n containing // numbers from 1 to n x n static void printSpiral(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // x stores the layer in which // (i, j)th element lies int x; // Finds minimum of four inputs x = Math.Min(Math.Min(i, j), Math.Min(n - 1 - i, n - 1 - j)); // For upper right half if (i <= j) Console.Write((n - 2 * x) * (n - 2 * x) - (i - x) - (j - x) + \"\\t\"); // for lower left half else Console.Write((n - 2 * x - 2) * (n - 2 * x - 2) + (i - x) + (j - x) + \"\\t\"); } Console.WriteLine(); } } // Driver code public static void Main() { int n = 5; // print a n x n spiral // matrix in O(1) space printSpiral(n); }} // This code is contributed by KRV", "e": 34493, "s": 33187, "text": null }, { "code": "<?php// PHP program to print a n x n// spiral matrix in clockwise// direction using O(1) space // Prints spiral matrix of size// n x n containing numbers// from 1 to n x nfunction printSpiral($n){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { // x stores the layer in // which (i, j)th element lies $x; // Finds minimum of four inputs $x = min(min($i, $j), min($n - 1 - $i, $n - 1 - $j)); // For upper right half if ($i <= $j) echo \"\\t \", ($n - 2 * $x) * ($n - 2 * $x) - ($i - $x) - ($j - $x); // for lower left half else echo \"\\t \", ($n - 2 * $x - 2) * ($n - 2 * $x - 2) + ($i - $x) + ($j - $x); } echo \"\\n\"; }} // Driver code$n = 5; // print a n x n spiral// matrix in O(1) spaceprintSpiral($n); // This code is contributed by ajit?>", "e": 35557, "s": 34493, "text": null }, { "code": "<script> // Javascript program to print a// n x n spiral matrix in clockwise// direction using O(1) space // Prints spiral matrix of size// n x n containing numbers from// 1 to n x nfunction printSpiral(n){ for(let i = 0; i < n; i++) { for(let j = 0; j < n; j++) { // x stores the layer in which (i, j)th // element lies let x; // Finds minimum of four inputs x = Math.min(Math.min(i, j), Math.min(n - 1 - i, n - 1 - j)); // For upper right half if (i <= j) document.write(`${(n - 2 * x) * (n - 2 * x) - (i - x) - (j - x)} `); // For lower left half else document.write(`${(n - 2 * x - 2) * (n - 2 * x - 2) + (i - x) + (j - x)} `); } document.write(\"<br>\"); }} // Driver codelet n = 5; // Print a n x n spiral matrix in O(1) spaceprintSpiral(n); // This code is contributed by subham348 </script>", "e": 36683, "s": 35557, "text": null }, { "code": null, "e": 36694, "s": 36683, "text": "Output : " }, { "code": null, "e": 36860, "s": 36694, "text": "25 24 23 22 21 \n10 9 8 7 20 \n11 2 1 6 19 \n12 3 4 5 18 \n13 14 15 16 17" }, { "code": null, "e": 37136, "s": 36860, "text": "Exercise For a given number n, print a n x n spiral matrix in counter clockwise direction using O(1) space.This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 37140, "s": 37136, "text": "KRV" }, { "code": null, "e": 37146, "s": 37140, "text": "jit_t" }, { "code": null, "e": 37156, "s": 37146, "text": "subham348" }, { "code": null, "e": 37171, "s": 37156, "text": "kothavvsaakash" }, { "code": null, "e": 37188, "s": 37171, "text": "pattern-printing" }, { "code": null, "e": 37195, "s": 37188, "text": "spiral" }, { "code": null, "e": 37202, "s": 37195, "text": "Matrix" }, { "code": null, "e": 37219, "s": 37202, "text": "pattern-printing" }, { "code": null, "e": 37226, "s": 37219, "text": "Matrix" }, { "code": null, "e": 37324, "s": 37226, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37374, "s": 37324, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 37431, "s": 37374, "text": "Flood fill Algorithm - how to implement fill() in paint?" }, { "code": null, "e": 37468, "s": 37431, "text": "Check for possible path in 2D matrix" }, { "code": null, "e": 37509, "s": 37468, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 37573, "s": 37509, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 37608, "s": 37573, "text": "Python program to add two Matrices" }, { "code": null, "e": 37646, "s": 37608, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 37672, "s": 37646, "text": "A Boolean Matrix Question" }, { "code": null, "e": 37728, "s": 37672, "text": "Shortest distance between two cells in a matrix or grid" } ]
GATE | GATE CS 2019 | Question 49 - GeeksforGeeks
02 Dec, 2019 Consider the following statements: I. The smallest element in a max-heap is always at a leaf node. II. The second largest element in a max-heap is always a child of the root node. III. A max-heap can be constructed from a binary search tree in Θ(n) time. IV. A binary search tree can be constructed from a max-heap in Θ(n) time. Which of the above statements is/are TRUE?(A) II, III and IV(B) I, II and III(C) I, III and IV(D) I, II and IVAnswer: (B)Explanation: Statement (I) is correct. In a max heap, the smallest element is always present at a leaf node. So we need to check for all leaf nodes for the minimum value. Worst case complexity will be O(n) 12 / \ / \ 8 7 / \ / \ / \ / \ 2 3 4 5 Statement (II) is also correct, otherwise it will not satisfy max-heap property. Statement (III) is also correct, as build-heap always takes Θ(n) time, (Refer: Convert BST to Max Heap). Statement (IV) is false, because construction of binary search tree from max-heap will take O(nlogn) time. So, option (B) is correct. Quiz of this Question nitesh5375 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25735, "s": 25707, "text": "\n02 Dec, 2019" }, { "code": null, "e": 25770, "s": 25735, "text": "Consider the following statements:" }, { "code": null, "e": 25834, "s": 25770, "text": "I. The smallest element in a max-heap is always at a leaf node." }, { "code": null, "e": 25915, "s": 25834, "text": "II. The second largest element in a max-heap is always a child of the root node." }, { "code": null, "e": 25990, "s": 25915, "text": "III. A max-heap can be constructed from a binary search tree in Θ(n) time." }, { "code": null, "e": 26064, "s": 25990, "text": "IV. A binary search tree can be constructed from a max-heap in Θ(n) time." }, { "code": null, "e": 26391, "s": 26064, "text": "Which of the above statements is/are TRUE?(A) II, III and IV(B) I, II and III(C) I, III and IV(D) I, II and IVAnswer: (B)Explanation: Statement (I) is correct. In a max heap, the smallest element is always present at a leaf node. So we need to check for all leaf nodes for the minimum value. Worst case complexity will be O(n)" }, { "code": null, "e": 26507, "s": 26391, "text": " 12\n / \\\n / \\\n 8 7\n / \\ / \\\n / \\ / \\\n2 3 4 5 " }, { "code": null, "e": 26588, "s": 26507, "text": "Statement (II) is also correct, otherwise it will not satisfy max-heap property." }, { "code": null, "e": 26693, "s": 26588, "text": "Statement (III) is also correct, as build-heap always takes Θ(n) time, (Refer: Convert BST to Max Heap)." }, { "code": null, "e": 26800, "s": 26693, "text": "Statement (IV) is false, because construction of binary search tree from max-heap will take O(nlogn) time." }, { "code": null, "e": 26827, "s": 26800, "text": "So, option (B) is correct." }, { "code": null, "e": 26849, "s": 26827, "text": "Quiz of this Question" }, { "code": null, "e": 26860, "s": 26849, "text": "nitesh5375" }, { "code": null, "e": 26865, "s": 26860, "text": "GATE" }, { "code": null, "e": 26963, "s": 26865, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26997, "s": 26963, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27031, "s": 26997, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27065, "s": 27031, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27098, "s": 27065, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27134, "s": 27098, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27170, "s": 27134, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27204, "s": 27170, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27238, "s": 27204, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27272, "s": 27238, "text": "GATE | GATE-CS-2009 | Question 38" } ]
All possible numbers of N digits and base B without leading zeros - GeeksforGeeks
25 May, 2021 Given a number of digits ‘N’ and base ‘B’, the task is to count all the ‘N’ digit numbers without leading zeros that are in base ‘B’. Examples: Input: N = 2, B = 2 Output: 2 All possible numbers without leading zeros are 10 and 11. Input: N = 5, B = 8 Output: 28672 Approach: If the base is ‘B’ then every digit of the number can take any value within the range [0, B-1]. So, B‘N’ digit numbers are possible with base ‘B’ (including the numbers with leading zeros). And, if we fix the first digit as ‘0’ then the rest of the ‘N-1’ digits can form a total of Bnumbers. So, the total number of ‘N’ digit numbers with base ‘B’ possible without leading zeros are B– B. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // function to count// all permutationsvoid countPermutations(int N, int B){ // count of // all permutations int x = pow(B, N); // count of permutations // with leading zeros int y = pow(B, N - 1); // Return the permutations // without leading zeros cout << x - y << "\n";} // Driver codeint main(){ int N = 6; int B = 4; countPermutations(N, B); return 0;} // Java implementation of the approach class GFG{// function to count// all permutationsstatic void countPermutations(int N, int B){ // count of // all permutations int x = (int)Math.pow(B, N); // count of permutations // with leading zeros int y = (int)Math.pow(B, N - 1); // Return the permutations // without leading zeros System.out.println(x - y);} // Driver codepublic static void main(String[] args){ int N = 6; int B = 4; countPermutations(N, B);}} // This code is contributed by mits # Python3 implementation of the approach # function to count all permutationsdef countPermutations(N, B): # count of all permutations x = B ** N # count of permutations # with leading zeros y = B ** (N - 1) # Return the permutations # without leading zeros print(x - y) # Driver codeif __name__ == "__main__": N, B = 6, 4 countPermutations(N, B) # This code is contributed by Rituraj Jain // C# implementation of the approach using System;class GFG{// function to count// all permutationsstatic void countPermutations(int N, int B){ // count of // all permutations int x = (int)Math.Pow(B, N); // count of permutations // with leading zeros int y = (int)Math.Pow(B, N - 1); // Return the permutations // without leading zeros Console.WriteLine(x - y);} // Driver codepublic static void Main(){ int N = 6; int B = 4; countPermutations(N, B);}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP implementation of the approach // function to count all permutationsfunction countPermutations($N, $B){ // count of all permutations $x = pow($B, $N); // count of permutations // with leading zeros $y = pow($B, $N - 1); // Return the permutations // without leading zeros echo ($x - $y), "\n";} // Driver code$N = 6;$B = 4; countPermutations($N, $B); // This code is contributed// by Sach_Code`?> <script> // Javascript implementation of the approach // function to count// all permutationsfunction countPermutations(N, B){ // count of // all permutations var x = Math.pow(B, N); // count of permutations // with leading zeros var y = Math.pow(B, N - 1); // Return the permutations // without leading zeros document.write( x - y );} // Driver codevar N = 6;var B = 4;countPermutations(N, B); </script> 3072 Sach_Code Akanksha_Rai Mithun Kumar rituraj_jain rutvik_56 maths-power number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes Print all possible combinations of r elements in a given array of size n The Knight's tour problem | Backtracking-1 Operators in C / C++ Program for factorial of a number Find minimum number of coins that make a given value
[ { "code": null, "e": 26129, "s": 26101, "text": "\n25 May, 2021" }, { "code": null, "e": 26263, "s": 26129, "text": "Given a number of digits ‘N’ and base ‘B’, the task is to count all the ‘N’ digit numbers without leading zeros that are in base ‘B’." }, { "code": null, "e": 26275, "s": 26263, "text": "Examples: " }, { "code": null, "e": 26399, "s": 26275, "text": "Input: N = 2, B = 2\nOutput: 2\nAll possible numbers without \nleading zeros are 10 and 11.\n\nInput: N = 5, B = 8\nOutput: 28672" }, { "code": null, "e": 26411, "s": 26399, "text": "Approach: " }, { "code": null, "e": 26507, "s": 26411, "text": "If the base is ‘B’ then every digit of the number can take any value within the range [0, B-1]." }, { "code": null, "e": 26601, "s": 26507, "text": "So, B‘N’ digit numbers are possible with base ‘B’ (including the numbers with leading zeros)." }, { "code": null, "e": 26703, "s": 26601, "text": "And, if we fix the first digit as ‘0’ then the rest of the ‘N-1’ digits can form a total of Bnumbers." }, { "code": null, "e": 26800, "s": 26703, "text": "So, the total number of ‘N’ digit numbers with base ‘B’ possible without leading zeros are B– B." }, { "code": null, "e": 26852, "s": 26800, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26856, "s": 26852, "text": "C++" }, { "code": null, "e": 26861, "s": 26856, "text": "Java" }, { "code": null, "e": 26869, "s": 26861, "text": "Python3" }, { "code": null, "e": 26872, "s": 26869, "text": "C#" }, { "code": null, "e": 26876, "s": 26872, "text": "PHP" }, { "code": null, "e": 26887, "s": 26876, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // function to count// all permutationsvoid countPermutations(int N, int B){ // count of // all permutations int x = pow(B, N); // count of permutations // with leading zeros int y = pow(B, N - 1); // Return the permutations // without leading zeros cout << x - y << \"\\n\";} // Driver codeint main(){ int N = 6; int B = 4; countPermutations(N, B); return 0;}", "e": 27371, "s": 26887, "text": null }, { "code": "// Java implementation of the approach class GFG{// function to count// all permutationsstatic void countPermutations(int N, int B){ // count of // all permutations int x = (int)Math.pow(B, N); // count of permutations // with leading zeros int y = (int)Math.pow(B, N - 1); // Return the permutations // without leading zeros System.out.println(x - y);} // Driver codepublic static void main(String[] args){ int N = 6; int B = 4; countPermutations(N, B);}} // This code is contributed by mits", "e": 27903, "s": 27371, "text": null }, { "code": "# Python3 implementation of the approach # function to count all permutationsdef countPermutations(N, B): # count of all permutations x = B ** N # count of permutations # with leading zeros y = B ** (N - 1) # Return the permutations # without leading zeros print(x - y) # Driver codeif __name__ == \"__main__\": N, B = 6, 4 countPermutations(N, B) # This code is contributed by Rituraj Jain", "e": 28326, "s": 27903, "text": null }, { "code": "// C# implementation of the approach using System;class GFG{// function to count// all permutationsstatic void countPermutations(int N, int B){ // count of // all permutations int x = (int)Math.Pow(B, N); // count of permutations // with leading zeros int y = (int)Math.Pow(B, N - 1); // Return the permutations // without leading zeros Console.WriteLine(x - y);} // Driver codepublic static void Main(){ int N = 6; int B = 4; countPermutations(N, B);}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 28876, "s": 28326, "text": null }, { "code": "<?php// PHP implementation of the approach // function to count all permutationsfunction countPermutations($N, $B){ // count of all permutations $x = pow($B, $N); // count of permutations // with leading zeros $y = pow($B, $N - 1); // Return the permutations // without leading zeros echo ($x - $y), \"\\n\";} // Driver code$N = 6;$B = 4; countPermutations($N, $B); // This code is contributed// by Sach_Code`?>", "e": 29311, "s": 28876, "text": null }, { "code": "<script> // Javascript implementation of the approach // function to count// all permutationsfunction countPermutations(N, B){ // count of // all permutations var x = Math.pow(B, N); // count of permutations // with leading zeros var y = Math.pow(B, N - 1); // Return the permutations // without leading zeros document.write( x - y );} // Driver codevar N = 6;var B = 4;countPermutations(N, B); </script>", "e": 29745, "s": 29311, "text": null }, { "code": null, "e": 29750, "s": 29745, "text": "3072" }, { "code": null, "e": 29762, "s": 29752, "text": "Sach_Code" }, { "code": null, "e": 29775, "s": 29762, "text": "Akanksha_Rai" }, { "code": null, "e": 29788, "s": 29775, "text": "Mithun Kumar" }, { "code": null, "e": 29801, "s": 29788, "text": "rituraj_jain" }, { "code": null, "e": 29811, "s": 29801, "text": "rutvik_56" }, { "code": null, "e": 29823, "s": 29811, "text": "maths-power" }, { "code": null, "e": 29837, "s": 29823, "text": "number-digits" }, { "code": null, "e": 29850, "s": 29837, "text": "Mathematical" }, { "code": null, "e": 29863, "s": 29850, "text": "Mathematical" }, { "code": null, "e": 29961, "s": 29863, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29985, "s": 29961, "text": "Merge two sorted arrays" }, { "code": null, "e": 30028, "s": 29985, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30042, "s": 30028, "text": "Prime Numbers" }, { "code": null, "e": 30084, "s": 30042, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 30106, "s": 30084, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 30179, "s": 30106, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 30222, "s": 30179, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 30243, "s": 30222, "text": "Operators in C / C++" }, { "code": null, "e": 30277, "s": 30243, "text": "Program for factorial of a number" } ]
Python | Handling no element found in index() - GeeksforGeeks
27 Sep, 2019 Sometimes, while working with Python lists, we are confronted with a problem in which we need to check whether an element is present in a list and also where exactly, which index it occurs. The convenient solution of it is to use index(). But problem with this can come that sometimes, the desired element might not be present in the list. Let’s discuss a method in which this exception can be handled. Method : Using ValueError + try + except In this method, knowing that the value might not exists, we catch the error in try-except block. The ValueError is raised in the absence and can be used to catch this particular exception. # Python3 code to demonstrate working of# Handling no element found in index()# Using try + except + ValueError # initializing listtest_list = [6, 4, 8, 9, 10] # printing listprint("The original list : " + str(test_list)) # Handling no element found in index()# Using try + except + ValueErrortry : test_list.index(11) res = "Element found"except ValueError : res = "Element not in list !" # Printing resultprint("The value after catching error : " + str(res)) The original list : [6, 4, 8, 9, 10] The value after catching error : Element not in list! Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n27 Sep, 2019" }, { "code": null, "e": 25940, "s": 25537, "text": "Sometimes, while working with Python lists, we are confronted with a problem in which we need to check whether an element is present in a list and also where exactly, which index it occurs. The convenient solution of it is to use index(). But problem with this can come that sometimes, the desired element might not be present in the list. Let’s discuss a method in which this exception can be handled." }, { "code": null, "e": 25981, "s": 25940, "text": "Method : Using ValueError + try + except" }, { "code": null, "e": 26170, "s": 25981, "text": "In this method, knowing that the value might not exists, we catch the error in try-except block. The ValueError is raised in the absence and can be used to catch this particular exception." }, { "code": "# Python3 code to demonstrate working of# Handling no element found in index()# Using try + except + ValueError # initializing listtest_list = [6, 4, 8, 9, 10] # printing listprint(\"The original list : \" + str(test_list)) # Handling no element found in index()# Using try + except + ValueErrortry : test_list.index(11) res = \"Element found\"except ValueError : res = \"Element not in list !\" # Printing resultprint(\"The value after catching error : \" + str(res))", "e": 26644, "s": 26170, "text": null }, { "code": null, "e": 26738, "s": 26644, "text": " \nThe original list : [6, 4, 8, 9, 10]\nThe value after catching error : Element not in list!\n" }, { "code": null, "e": 26759, "s": 26738, "text": "Python list-programs" }, { "code": null, "e": 26766, "s": 26759, "text": "Python" }, { "code": null, "e": 26782, "s": 26766, "text": "Python Programs" }, { "code": null, "e": 26880, "s": 26782, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26912, "s": 26880, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26954, "s": 26912, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26996, "s": 26954, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27052, "s": 26996, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27079, "s": 27052, "text": "Python Classes and Objects" }, { "code": null, "e": 27101, "s": 27079, "text": "Defaultdict in Python" }, { "code": null, "e": 27140, "s": 27101, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27186, "s": 27140, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27224, "s": 27186, "text": "Python | Convert a list to dictionary" } ]
What is dynamic binding in Java?
In dynamic binding, the method call is bonded to the method body at runtime. This is also known as late binding. This is done using instance methods. class Super { public void sample() { System.out.println("This is the method of super class"); } } Public class extends Super { Public static void sample() { System.out.println("This is the method of sub class"); } Public static void main(String args[]) { new Sub().sample() } } This is the method of sub class
[ { "code": null, "e": 1337, "s": 1187, "text": "In dynamic binding, the method call is bonded to the method body at runtime. This is also known as late binding. This is done using instance methods." }, { "code": null, "e": 1653, "s": 1337, "text": "class Super {\n public void sample() {\n System.out.println(\"This is the method of super class\");\n }\n}\n\nPublic class extends Super {\n Public static void sample() {\n System.out.println(\"This is the method of sub class\");\n }\n\n Public static void main(String args[]) {\n new Sub().sample()\n }\n}" }, { "code": null, "e": 1685, "s": 1653, "text": "This is the method of sub class" } ]
PHP 7 - Installation on Windows with Apache
To install Apache with PHP 5 on Windows follow the given steps. If your PHP and Apache versions are different then please take care accordingly. Download Apache server from www.apache.org/dist/httpd/binaries/win32. You want the current stable release version with the no_src.msi extension. Double-click the installer file to install; C:\Program Files is a common location. The installer will also ask you whether you want to run Apache as a service or from the command line or DOS prompt. We recommend you do not install as a service, as this may cause problems with startup. Download Apache server from www.apache.org/dist/httpd/binaries/win32. You want the current stable release version with the no_src.msi extension. Double-click the installer file to install; C:\Program Files is a common location. The installer will also ask you whether you want to run Apache as a service or from the command line or DOS prompt. We recommend you do not install as a service, as this may cause problems with startup. Extract the PHP binary archive using your unzip utility; C:\php7 is a common location. Extract the PHP binary archive using your unzip utility; C:\php7 is a common location. Rename php.ini-development to php.ini. Open this file in a text editor (for example, Notepad). Edit this file to get the configuration directives; At this point, we highly recommend that the new users set error reporting to E_ALL on their development machines. Rename php.ini-development to php.ini. Open this file in a text editor (for example, Notepad). Edit this file to get the configuration directives; At this point, we highly recommend that the new users set error reporting to E_ALL on their development machines. Tell your Apache server where you want to serve files from and what extension(s) you want to identify the PHP files (.php is the standard, but you can use .html, .phtml, or whatever you want). Go to your HTTP configuration files (C:\Program Files\Apache Group\Apache\conf or whatever your path is), and open httpd.conf with a text editor. Search for the word DocumentRoot (which should appear twice) and change both the paths to the directory you want to serve files out of. (The default is C:\Program Files\Apache Group\Apache\htdocs.). Add at least one PHP extension directive as shown in the first line of the following code − Tell your Apache server where you want to serve files from and what extension(s) you want to identify the PHP files (.php is the standard, but you can use .html, .phtml, or whatever you want). Go to your HTTP configuration files (C:\Program Files\Apache Group\Apache\conf or whatever your path is), and open httpd.conf with a text editor. Search for the word DocumentRoot (which should appear twice) and change both the paths to the directory you want to serve files out of. (The default is C:\Program Files\Apache Group\Apache\htdocs.). Add at least one PHP extension directive as shown in the first line of the following code − AddHandler application/x-httpd-php .php AddType application/x-httpd-php .php .html LoadModule php7_module "C:/php7/php7apache2_4.dll" PHPiniDir "c:/php7" Open a text editor. Type: <?php phpinfo(); ?>. Save this file in your Web server's document root as info.php. Start any Web browser and browse the file. You must always use an HTTP request (http://www.testdomain.com/info.php or http://localhost/info.php or http://127.0.0.1/info.php) rather than a filename (/home/httpd/info.php) for the file to be parsed correctly You will see a long table of information about your new PHP installation message Congratulations!
[ { "code": null, "e": 2356, "s": 2211, "text": "To install Apache with PHP 5 on Windows follow the given steps. If your PHP and Apache versions are different then please take care accordingly." }, { "code": null, "e": 2787, "s": 2356, "text": "Download Apache server from www.apache.org/dist/httpd/binaries/win32. You want the current stable release version with the no_src.msi extension. Double-click the installer file to install; C:\\Program Files is a common location. The installer will also ask you whether you want to run Apache as a service or from the command line or DOS prompt. We recommend you do not install as a service, as this may cause problems with startup." }, { "code": null, "e": 3218, "s": 2787, "text": "Download Apache server from www.apache.org/dist/httpd/binaries/win32. You want the current stable release version with the no_src.msi extension. Double-click the installer file to install; C:\\Program Files is a common location. The installer will also ask you whether you want to run Apache as a service or from the command line or DOS prompt. We recommend you do not install as a service, as this may cause problems with startup." }, { "code": null, "e": 3305, "s": 3218, "text": "Extract the PHP binary archive using your unzip utility; C:\\php7 is a common location." }, { "code": null, "e": 3392, "s": 3305, "text": "Extract the PHP binary archive using your unzip utility; C:\\php7 is a common location." }, { "code": null, "e": 3653, "s": 3392, "text": "Rename php.ini-development to php.ini. Open this file in a text editor (for example, Notepad). Edit this file to get the configuration directives; At this point, we highly recommend that the new users set error reporting to E_ALL on their development machines." }, { "code": null, "e": 3914, "s": 3653, "text": "Rename php.ini-development to php.ini. Open this file in a text editor (for example, Notepad). Edit this file to get the configuration directives; At this point, we highly recommend that the new users set error reporting to E_ALL on their development machines." }, { "code": null, "e": 4545, "s": 3914, "text": "Tell your Apache server where you want to serve files from and what extension(s) you want to identify the PHP files (.php is the standard, but you can use .html, .phtml, or whatever you want). Go to your HTTP configuration files (C:\\Program Files\\Apache Group\\Apache\\conf or whatever your path is), and open httpd.conf with a text editor. Search for the word DocumentRoot (which should appear twice) and change both the paths to the directory you want to serve files out of. (The default is C:\\Program Files\\Apache Group\\Apache\\htdocs.). Add at least one PHP extension directive as shown in the first line of the following code −" }, { "code": null, "e": 5176, "s": 4545, "text": "Tell your Apache server where you want to serve files from and what extension(s) you want to identify the PHP files (.php is the standard, but you can use .html, .phtml, or whatever you want). Go to your HTTP configuration files (C:\\Program Files\\Apache Group\\Apache\\conf or whatever your path is), and open httpd.conf with a text editor. Search for the word DocumentRoot (which should appear twice) and change both the paths to the directory you want to serve files out of. (The default is C:\\Program Files\\Apache Group\\Apache\\htdocs.). Add at least one PHP extension directive as shown in the first line of the following code −" }, { "code": null, "e": 5331, "s": 5176, "text": "AddHandler application/x-httpd-php .php\nAddType application/x-httpd-php .php .html\nLoadModule php7_module \"C:/php7/php7apache2_4.dll\"\nPHPiniDir \"c:/php7\"\n" }, { "code": null, "e": 5697, "s": 5331, "text": "Open a text editor. Type: <?php phpinfo(); ?>. Save this file in your Web server's document root as info.php. Start any Web browser and browse the file. You must always use an HTTP request (http://www.testdomain.com/info.php or http://localhost/info.php or http://127.0.0.1/info.php) rather than a filename (/home/httpd/info.php) for the file to be parsed correctly" } ]
Communication Technologies - Web Services
Let us discuss some terms commonly used with regard to the Internet. WWW is the acronym for World Wide Web. WWW is an information space inhabited by interlinked documents and other media that can be accessed via the Internet. WWW was invented by British scientist Tim Berners-Lee in 1989 and developed the first web browser in 1990 to facilitate exchange of information through the use of interlinked hypertexts. A text that contains link to another piece of text is called hypertext. The web resources were identified by a unique name called URL to avoid confusion. World Wide Web has revolutionized the way we create, store and exchange information. Success of WWW can be attributed to these factors − User friendly Use of multimedia Interlinking of pages through hypertexts Interactive HTML stands for Hypertext Markup Language. A language designed such that parts of text can be marked to specify its structure, layout and style in context of the whole page is called a markup language. Its primary function is defining, processing and presenting text. HTML is the standard language for creating web pages and web applications, and loading them in web browsers. Like WWW it was created by Time Berners-Lee to enable users to access pages from any page easily. When you send request for a page, the web server sends file in HTML form. This HTML file is interpreted by the web browser and displayed. XML stands for eXtensible Markup Language. It is a markup language designed to store and transport data in safe, secure and correct way. As the word extensible indicates, XML provides users with a tool to define their own language, especially to display documents on the Internet. Any XML document has two parts – structure and content. Let’s take an example to understand this. Suppose your school library wants to create a database of magazines it subscribes to. This is the CATALOG XML file that needs to be created. <CATALOG> <MAGAZINE> <TITLE>Magic Pot</TITLE> <PUBLISHER>MM Publications</PUBLISHER> <FREQUENCY>Weekly</FREQUENCY> <PRICE>15</PRICE> </MAGAZINE> <MAGAZINE> <TITLE>Competition Refresher</TITLE> <PUBLISHER>Bright Publications</PUBLISHER> <FREQUENCY>Monthly</FREQUENC> <PRICE>100</PRICE> </MAGAZINE> </CATALOG> Each magazine has title, publisher, frequency and price information stored about it. This is the structure of catalog. Values like Magic Pot, MM Publication, Monthly, Weekly, etc. are the content. This XML file has information about all the magazines available in the library. Remember that this file will not do anything on its own. But another piece of code can be easily written to extract, analyze and present data stored here. HTTP stands for Hypertext Transfer Protocol. It is the most fundamental protocol used for transferring text, graphics, image, video and other multimedia files on the World Wide Web. HTTP is an application layer protocol of the TCP/IP suite in client-server networking model and was outlined for the first time by Time Berners-Lee, father of World Wide Web. HTTP is a request-response protocol. Here is how it functions − Client submits request to HTTP. Client submits request to HTTP. TCP connection is established with the server. TCP connection is established with the server. After necessary processing server sends back status request as well as a message. The message may have the requested content or an error message. After necessary processing server sends back status request as well as a message. The message may have the requested content or an error message. An HTTP request is called method. Some of the most popular methods are GET, PUT, POST, CONNECT, etc. Methods that have in-built security mechanisms are called safe methods while others are called unsafe. The version of HTTP that is completely secure is HTTPS where S stands for secure. Here all methods are secure. An example of use of HTTP protocol is − https://www.tutorialspoint.com/videotutorials/index.htm The user is requesting (by clicking on a link) the index page of video tutorials on the tutorialspoint.com website. Other parts of the request are discussed later in the chapter. Domain name is a unique name given to a server to identify it on the World Wide Web. In the example request given earlier − https://www.tutorialspoint.com/videotutorials/index.htm tutorialspoint.com is the domain name. Domain name has multiple parts called labels separated by dots. Let us discuss the labels of this domain name. The right most label .com is called top level domain (TLD). Other examples of TLDs include .net, .org, .co, .au, etc. The label left to the TLD, i.e. tutorialspoint, is the second level domain. In the above image, .co label in .co.uk is second level domain and .uk is the TLD. www is simply a label used to create the subdomain of tutorialspoint.com. Another label could be ftp to create the subdomain ftp.tutorialspoint.com. This logical tree structure of domain names, starting from top level domain to lower level domain names is called domain name hierarchy. Root of the domain name hierarchy is nameless. The maximum length of complete domain name is 253 ASCII characters. URL stands for Uniform Resource Locator. URL refers to the location of a web resource on computer network and mechanism for retrieving it. Let us continue with the above example − https://www.tutorialspoint.com/videotutorials/index.htm This complete string is a URL. Let’s discuss its parts − index.htm is the resource (web page in this case) that needs to be retrieved index.htm is the resource (web page in this case) that needs to be retrieved www.tutorialspoint.com is the server on which this page is located www.tutorialspoint.com is the server on which this page is located videotutorials is the folder on server where the resource is located videotutorials is the folder on server where the resource is located www.tutorialspoint.com/videotutorials is the complete pathname of the resource www.tutorialspoint.com/videotutorials is the complete pathname of the resource https is the protocol to be used to retrieve the resource https is the protocol to be used to retrieve the resource URL is displayed in the address bar of the web browser. Website is a set of web pages under a single domain name. Web page is a text document located on a server and connected to the World Wide Web through hypertexts. Using the image depicting domain name hierarchy, these are the websites that can be constructed − www.tutorialspoint.com ftp.tutorialspoint.com indianrail.gov.in cbse.nic.in Note that there is no protocol associated with websites 3 and 4 but they will still load, using their default protocol. Web browser is an application software for accessing, retrieving, presenting and traversing any resource identified by a URL on the World Wide Web. Most popular web browsers include − Chrome Internet Explorer Firefox Apple Safari Opera Web server is any software application, computer or networked device that serves files to the users as per their request. These requests are sent by client devices through HTTP or HTTPS requests. Popular web server software include Apache, Microsoft IIS, and Nginx. Web hosting is an Internet service that enables individuals, organizations or businesses to store web pages that can be accessed on the Internet. Web hosting service providers have web servers on which they host web sites and their pages. They also provide the technologies necessary for making a web page available upon client request, as discussed in HTTP above. Script is a set of instructions written using any programming language and interpreted (rather than compiled) by another program. Embedding scripts within web pages to make them dynamic is called web scripting. As you know, web pages are created using HTML, stored on the server and then loaded into web browsers upon client’s request. Earlier these web pages were static in nature, i.e. what was once created was the only version displayed to the users. However, modern users as well as website owners demand some interaction with the web pages. Examples of interaction includes validating online forms filled by users, showing messages after user has registered a choice, etc. All this can be achieved by web scripting. Web scripting is of two types − Client side scripting − Here the scripts embedded in a page are executed by the client computer itself using web browser. Most popular client side scripting languages are JavaScript, VBScript, AJAX, etc. Client side scripting − Here the scripts embedded in a page are executed by the client computer itself using web browser. Most popular client side scripting languages are JavaScript, VBScript, AJAX, etc. Server side scripting − Here scripts are run on the server. Web page requested by the client is generated and sent after the scripts are run. Most popular server side scripting languages are PHP, Python, ASP .Net, etc. Server side scripting − Here scripts are run on the server. Web page requested by the client is generated and sent after the scripts are run. Most popular server side scripting languages are PHP, Python, ASP .Net, etc. Web 2.0 is the second stage of development in World Wide Web where the emphasis is on dynamic and user generated content rather than static content. As discussed above, World Wide Web initially supported creation and presentation of static content using HTML. However, as the users evolved, demand for interactive content grew and web scripting was used to add this dynamism to content. In 1999, Darcy DiNucci coined the term Web 2.0 to emphasize the paradigm shift in the way web pages were being designed and presented to the user. It became popularity around 2004. Examples of user generated content in Web 2.0 include social media websites, virtual communities, live chats, etc. These have revolutionized the way we experience and use the Internet.
[ { "code": null, "e": 2090, "s": 2021, "text": "Let us discuss some terms commonly used with regard to the Internet." }, { "code": null, "e": 2434, "s": 2090, "text": "WWW is the acronym for World Wide Web. WWW is an information space inhabited by interlinked documents and other media that can be accessed via the Internet. WWW was invented by British scientist Tim Berners-Lee in 1989 and developed the first web browser in 1990 to facilitate exchange of information through the use of interlinked hypertexts." }, { "code": null, "e": 2588, "s": 2434, "text": "A text that contains link to another piece of text is called hypertext. The web resources were identified by a unique name called URL to avoid confusion." }, { "code": null, "e": 2725, "s": 2588, "text": "World Wide Web has revolutionized the way we create, store and exchange information. Success of WWW can be attributed to these factors −" }, { "code": null, "e": 2739, "s": 2725, "text": "User friendly" }, { "code": null, "e": 2757, "s": 2739, "text": "Use of multimedia" }, { "code": null, "e": 2798, "s": 2757, "text": "Interlinking of pages through hypertexts" }, { "code": null, "e": 2810, "s": 2798, "text": "Interactive" }, { "code": null, "e": 3078, "s": 2810, "text": "HTML stands for Hypertext Markup Language. A language designed such that parts of text can be marked to specify its structure, layout and style in context of the whole page is called a markup language. Its primary function is defining, processing and presenting text." }, { "code": null, "e": 3285, "s": 3078, "text": "HTML is the standard language for creating web pages and web applications, and loading them in web browsers. Like WWW it was created by Time Berners-Lee to enable users to access pages from any page easily." }, { "code": null, "e": 3423, "s": 3285, "text": "When you send request for a page, the web server sends file in HTML form. This HTML file is interpreted by the web browser and displayed." }, { "code": null, "e": 3704, "s": 3423, "text": "XML stands for eXtensible Markup Language. It is a markup language designed to store and transport data in safe, secure and correct way. As the word extensible indicates, XML provides users with a tool to define their own language, especially to display documents on the Internet." }, { "code": null, "e": 3943, "s": 3704, "text": "Any XML document has two parts – structure and content. Let’s take an example to understand this. Suppose your school library wants to create a database of magazines it subscribes to. This is the CATALOG XML file that needs to be created." }, { "code": null, "e": 4315, "s": 3943, "text": "<CATALOG>\n <MAGAZINE>\n <TITLE>Magic Pot</TITLE>\n <PUBLISHER>MM Publications</PUBLISHER>\n <FREQUENCY>Weekly</FREQUENCY>\n <PRICE>15</PRICE>\n </MAGAZINE>\n \n <MAGAZINE>\n <TITLE>Competition Refresher</TITLE>\n <PUBLISHER>Bright Publications</PUBLISHER>\n <FREQUENCY>Monthly</FREQUENC>\n <PRICE>100</PRICE>\n </MAGAZINE>\n</CATALOG>" }, { "code": null, "e": 4512, "s": 4315, "text": "Each magazine has title, publisher, frequency and price information stored about it. This is the structure of catalog. Values like Magic Pot, MM Publication, Monthly, Weekly, etc. are the content." }, { "code": null, "e": 4747, "s": 4512, "text": "This XML file has information about all the magazines available in the library. Remember that this file will not do anything on its own. But another piece of code can be easily written to extract, analyze and present data stored here." }, { "code": null, "e": 5104, "s": 4747, "text": "HTTP stands for Hypertext Transfer Protocol. It is the most fundamental protocol used for transferring text, graphics, image, video and other multimedia files on the World Wide Web. HTTP is an application layer protocol of the TCP/IP suite in client-server networking model and was outlined for the first time by Time Berners-Lee, father of World Wide Web." }, { "code": null, "e": 5168, "s": 5104, "text": "HTTP is a request-response protocol. Here is how it functions −" }, { "code": null, "e": 5200, "s": 5168, "text": "Client submits request to HTTP." }, { "code": null, "e": 5232, "s": 5200, "text": "Client submits request to HTTP." }, { "code": null, "e": 5279, "s": 5232, "text": "TCP connection is established with the server." }, { "code": null, "e": 5326, "s": 5279, "text": "TCP connection is established with the server." }, { "code": null, "e": 5472, "s": 5326, "text": "After necessary processing server sends back status request as well as a message. The message may have the requested content or an error message." }, { "code": null, "e": 5618, "s": 5472, "text": "After necessary processing server sends back status request as well as a message. The message may have the requested content or an error message." }, { "code": null, "e": 5933, "s": 5618, "text": "An HTTP request is called method. Some of the most popular methods are GET, PUT, POST, CONNECT, etc. Methods that have in-built security mechanisms are called safe methods while others are called unsafe. The version of HTTP that is completely secure is HTTPS where S stands for secure. Here all methods are secure." }, { "code": null, "e": 5973, "s": 5933, "text": "An example of use of HTTP protocol is −" }, { "code": null, "e": 6029, "s": 5973, "text": "https://www.tutorialspoint.com/videotutorials/index.htm" }, { "code": null, "e": 6208, "s": 6029, "text": "The user is requesting (by clicking on a link) the index page of video tutorials on the tutorialspoint.com website. Other parts of the request are discussed later in the chapter." }, { "code": null, "e": 6332, "s": 6208, "text": "Domain name is a unique name given to a server to identify it on the World Wide Web. In the example request given earlier −" }, { "code": null, "e": 6388, "s": 6332, "text": "https://www.tutorialspoint.com/videotutorials/index.htm" }, { "code": null, "e": 6656, "s": 6388, "text": "tutorialspoint.com is the domain name. Domain name has multiple parts called labels separated by dots. Let us discuss the labels of this domain name. The right most label .com is called top level domain (TLD). Other examples of TLDs include .net, .org, .co, .au, etc." }, { "code": null, "e": 6964, "s": 6656, "text": "The label left to the TLD, i.e. tutorialspoint, is the second level domain. In the above image, .co label in .co.uk is second level domain and .uk is the TLD. www is simply a label used to create the subdomain of tutorialspoint.com. Another label could be ftp to create the subdomain ftp.tutorialspoint.com." }, { "code": null, "e": 7216, "s": 6964, "text": "This logical tree structure of domain names, starting from top level domain to lower level domain names is called domain name hierarchy. Root of the domain name hierarchy is nameless. The maximum length of complete domain name is 253 ASCII characters." }, { "code": null, "e": 7396, "s": 7216, "text": "URL stands for Uniform Resource Locator. URL refers to the location of a web resource on computer network and mechanism for retrieving it. Let us continue with the above example −" }, { "code": null, "e": 7452, "s": 7396, "text": "https://www.tutorialspoint.com/videotutorials/index.htm" }, { "code": null, "e": 7509, "s": 7452, "text": "This complete string is a URL. Let’s discuss its parts −" }, { "code": null, "e": 7586, "s": 7509, "text": "index.htm is the resource (web page in this case) that needs to be retrieved" }, { "code": null, "e": 7663, "s": 7586, "text": "index.htm is the resource (web page in this case) that needs to be retrieved" }, { "code": null, "e": 7730, "s": 7663, "text": "www.tutorialspoint.com is the server on which this page is located" }, { "code": null, "e": 7797, "s": 7730, "text": "www.tutorialspoint.com is the server on which this page is located" }, { "code": null, "e": 7866, "s": 7797, "text": "videotutorials is the folder on server where the resource is located" }, { "code": null, "e": 7935, "s": 7866, "text": "videotutorials is the folder on server where the resource is located" }, { "code": null, "e": 8014, "s": 7935, "text": "www.tutorialspoint.com/videotutorials is the complete pathname of the resource" }, { "code": null, "e": 8093, "s": 8014, "text": "www.tutorialspoint.com/videotutorials is the complete pathname of the resource" }, { "code": null, "e": 8151, "s": 8093, "text": "https is the protocol to be used to retrieve the resource" }, { "code": null, "e": 8209, "s": 8151, "text": "https is the protocol to be used to retrieve the resource" }, { "code": null, "e": 8265, "s": 8209, "text": "URL is displayed in the address bar of the web browser." }, { "code": null, "e": 8525, "s": 8265, "text": "Website is a set of web pages under a single domain name. Web page is a text document located on a server and connected to the World Wide Web through hypertexts. Using the image depicting domain name hierarchy, these are the websites that can be constructed −" }, { "code": null, "e": 8548, "s": 8525, "text": "www.tutorialspoint.com" }, { "code": null, "e": 8571, "s": 8548, "text": "ftp.tutorialspoint.com" }, { "code": null, "e": 8589, "s": 8571, "text": "indianrail.gov.in" }, { "code": null, "e": 8601, "s": 8589, "text": "cbse.nic.in" }, { "code": null, "e": 8721, "s": 8601, "text": "Note that there is no protocol associated with websites 3 and 4 but they will still load, using their default protocol." }, { "code": null, "e": 8905, "s": 8721, "text": "Web browser is an application software for accessing, retrieving, presenting and traversing any resource identified by a URL on the World Wide Web. Most popular web browsers include −" }, { "code": null, "e": 8912, "s": 8905, "text": "Chrome" }, { "code": null, "e": 8930, "s": 8912, "text": "Internet Explorer" }, { "code": null, "e": 8938, "s": 8930, "text": "Firefox" }, { "code": null, "e": 8951, "s": 8938, "text": "Apple Safari" }, { "code": null, "e": 8957, "s": 8951, "text": "Opera" }, { "code": null, "e": 9223, "s": 8957, "text": "Web server is any software application, computer or networked device that serves files to the users as per their request. These requests are sent by client devices through HTTP or HTTPS requests. Popular web server software include Apache, Microsoft IIS, and Nginx." }, { "code": null, "e": 9588, "s": 9223, "text": "Web hosting is an Internet service that enables individuals, organizations or businesses to store web pages that can be accessed on the Internet. Web hosting service providers have web servers on which they host web sites and their pages. They also provide the technologies necessary for making a web page available upon client request, as discussed in HTTP above." }, { "code": null, "e": 9799, "s": 9588, "text": "Script is a set of instructions written using any programming language and interpreted (rather than compiled) by another program. Embedding scripts within web pages to make them dynamic is called web scripting." }, { "code": null, "e": 10135, "s": 9799, "text": "As you know, web pages are created using HTML, stored on the server and then loaded into web browsers upon client’s request. Earlier these web pages were static in nature, i.e. what was once created was the only version displayed to the users. However, modern users as well as website owners demand some interaction with the web pages." }, { "code": null, "e": 10342, "s": 10135, "text": "Examples of interaction includes validating online forms filled by users, showing messages after user has registered a choice, etc. All this can be achieved by web scripting. Web scripting is of two types −" }, { "code": null, "e": 10546, "s": 10342, "text": "Client side scripting − Here the scripts embedded in a page are executed by the client computer itself using web browser. Most popular client side scripting languages are JavaScript, VBScript, AJAX, etc." }, { "code": null, "e": 10750, "s": 10546, "text": "Client side scripting − Here the scripts embedded in a page are executed by the client computer itself using web browser. Most popular client side scripting languages are JavaScript, VBScript, AJAX, etc." }, { "code": null, "e": 10969, "s": 10750, "text": "Server side scripting − Here scripts are run on the server. Web page requested by the client is generated and sent after the scripts are run. Most popular server side scripting languages are PHP, Python, ASP .Net, etc." }, { "code": null, "e": 11188, "s": 10969, "text": "Server side scripting − Here scripts are run on the server. Web page requested by the client is generated and sent after the scripts are run. Most popular server side scripting languages are PHP, Python, ASP .Net, etc." }, { "code": null, "e": 11575, "s": 11188, "text": "Web 2.0 is the second stage of development in World Wide Web where the emphasis is on dynamic and user generated content rather than static content. As discussed above, World Wide Web initially supported creation and presentation of static content using HTML. However, as the users evolved, demand for interactive content grew and web scripting was used to add this dynamism to content." }, { "code": null, "e": 11756, "s": 11575, "text": "In 1999, Darcy DiNucci coined the term Web 2.0 to emphasize the paradigm shift in the way web pages were being designed and presented to the user. It became popularity around 2004." } ]
NoSQL Data Architecture Patterns
21 Sep, 2021 Architecture Pattern is a logical way of categorizing data that will be stored on the Database. NoSQL is a type of database which helps to perform operations on big data and store it in a valid format. It is widely used because of its flexibility and a wide variety of services. Architecture Patterns of NoSQL: The data is stored in NoSQL in any of the following four data architecture patterns. 1. Key-Value Store Database 2. Column Store Database 3. Document Database 4. Graph Database These are explained as following below. 1. Key-Value Store Database: This model is one of the most basic models of NoSQL databases. As the name suggests, the data is stored in form of Key-Value Pairs. The key is usually a sequence of strings, integers or characters but can also be a more advanced data type. The value is typically linked or co-related to the key. The key-value pair storage databases generally store data as a hash table where each key is unique. The value can be of any type (JSON, BLOB(Binary Large Object), strings, etc). This type of pattern is usually used in shopping websites or e-commerce applications. Advantages: Can handle large amounts of data and heavy load, Easy retrieval of data by keys. Limitations: Complex queries may attempt to involve multiple key-value pairs which may delay performance. Data can be involving many-to-many relationships which may collide. Examples: DynamoDB Berkeley DB 2. Column Store Database: Rather than storing data in relational tuples, the data is stored in individual cells which are further grouped into columns. Column-oriented databases work only on columns. They store large amounts of data into columns together. Format and titles of the columns can diverge from one row to other. Every column is treated separately. But still, each individual column may contain multiple other columns like traditional databases. Basically, columns are mode of storage in this type. Advantages: Data is readily available Queries like SUM, AVERAGE, COUNT can be easily performed on columns. Examples: HBase Bigtable by Google Cassandra 3. Document Database: The document database fetches and accumulates data in form of key-value pairs but here, the values are called as Documents. Document can be stated as a complex data structure. Document here can be a form of text, arrays, strings, JSON, XML or any such format. The use of nested documents is also very common. It is very effective as most of the data created is usually in form of JSONs and is unstructured. Advantages: This type of format is very useful and apt for semi-structured data. Storage retrieval and managing of documents is easy. Limitations: Handling multiple documents is challenging Aggregation operations may not work accurately. Examples: MongoDB CouchDB 4. Graph Databases: Clearly, this architecture pattern deals with the storage and management of data in graphs. Graphs are basically structures that depict connections between two or more objects in some data. The objects or entities are called as nodes and are joined together by relationships called Edges. Each edge has a unique identifier. Each node serves as a point of contact for the graph. This pattern is very commonly used in social networks where there are a large number of entities and each entity has one or many characteristics which are connected by edges. The relational database pattern has tables that are loosely connected, whereas graphs are often very strong and rigid in nature. Advantages: Fastest traversal because of connections. Spatial data can be easily handled. Limitations: Wrong connections may lead to infinite loops. Examples: Neo4J FlockDB( Used by Twitter) nidhi_biet sweetyty DBMS Technical Scripter DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Difference between Clustered and Non-clustered index SQL Interview Questions SQL | Views Data Preprocessing in Data Mining Difference between DELETE, DROP and TRUNCATE Indexing in Databases | Set 1 Difference between Primary Key and Foreign Key SQL | GROUP BY Difference between DDL and DML in DBMS
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Sep, 2021" }, { "code": null, "e": 308, "s": 28, "text": "Architecture Pattern is a logical way of categorizing data that will be stored on the Database. NoSQL is a type of database which helps to perform operations on big data and store it in a valid format. It is widely used because of its flexibility and a wide variety of services. " }, { "code": null, "e": 426, "s": 308, "text": "Architecture Patterns of NoSQL: The data is stored in NoSQL in any of the following four data architecture patterns. " }, { "code": null, "e": 519, "s": 426, "text": "1. Key-Value Store Database\n2. Column Store Database\n3. Document Database\n4. Graph Database " }, { "code": null, "e": 560, "s": 519, "text": "These are explained as following below. " }, { "code": null, "e": 1150, "s": 560, "text": "1. Key-Value Store Database: This model is one of the most basic models of NoSQL databases. As the name suggests, the data is stored in form of Key-Value Pairs. The key is usually a sequence of strings, integers or characters but can also be a more advanced data type. The value is typically linked or co-related to the key. The key-value pair storage databases generally store data as a hash table where each key is unique. The value can be of any type (JSON, BLOB(Binary Large Object), strings, etc). This type of pattern is usually used in shopping websites or e-commerce applications. " }, { "code": null, "e": 1163, "s": 1150, "text": "Advantages: " }, { "code": null, "e": 1213, "s": 1163, "text": "Can handle large amounts of data and heavy load, " }, { "code": null, "e": 1246, "s": 1213, "text": "Easy retrieval of data by keys. " }, { "code": null, "e": 1260, "s": 1246, "text": "Limitations: " }, { "code": null, "e": 1354, "s": 1260, "text": "Complex queries may attempt to involve multiple key-value pairs which may delay performance. " }, { "code": null, "e": 1423, "s": 1354, "text": "Data can be involving many-to-many relationships which may collide. " }, { "code": null, "e": 1434, "s": 1423, "text": "Examples: " }, { "code": null, "e": 1443, "s": 1434, "text": "DynamoDB" }, { "code": null, "e": 1455, "s": 1443, "text": "Berkeley DB" }, { "code": null, "e": 1966, "s": 1455, "text": "2. Column Store Database: Rather than storing data in relational tuples, the data is stored in individual cells which are further grouped into columns. Column-oriented databases work only on columns. They store large amounts of data into columns together. Format and titles of the columns can diverge from one row to other. Every column is treated separately. But still, each individual column may contain multiple other columns like traditional databases. Basically, columns are mode of storage in this type. " }, { "code": null, "e": 1979, "s": 1966, "text": "Advantages: " }, { "code": null, "e": 2006, "s": 1979, "text": "Data is readily available " }, { "code": null, "e": 2076, "s": 2006, "text": "Queries like SUM, AVERAGE, COUNT can be easily performed on columns. " }, { "code": null, "e": 2087, "s": 2076, "text": "Examples: " }, { "code": null, "e": 2093, "s": 2087, "text": "HBase" }, { "code": null, "e": 2112, "s": 2093, "text": "Bigtable by Google" }, { "code": null, "e": 2122, "s": 2112, "text": "Cassandra" }, { "code": null, "e": 2552, "s": 2122, "text": "3. Document Database: The document database fetches and accumulates data in form of key-value pairs but here, the values are called as Documents. Document can be stated as a complex data structure. Document here can be a form of text, arrays, strings, JSON, XML or any such format. The use of nested documents is also very common. It is very effective as most of the data created is usually in form of JSONs and is unstructured. " }, { "code": null, "e": 2565, "s": 2552, "text": "Advantages: " }, { "code": null, "e": 2635, "s": 2565, "text": "This type of format is very useful and apt for semi-structured data. " }, { "code": null, "e": 2689, "s": 2635, "text": "Storage retrieval and managing of documents is easy. " }, { "code": null, "e": 2704, "s": 2689, "text": "Limitations: " }, { "code": null, "e": 2748, "s": 2704, "text": "Handling multiple documents is challenging " }, { "code": null, "e": 2797, "s": 2748, "text": "Aggregation operations may not work accurately. " }, { "code": null, "e": 2808, "s": 2797, "text": "Examples: " }, { "code": null, "e": 2816, "s": 2808, "text": "MongoDB" }, { "code": null, "e": 2824, "s": 2816, "text": "CouchDB" }, { "code": null, "e": 3529, "s": 2826, "text": "4. Graph Databases: Clearly, this architecture pattern deals with the storage and management of data in graphs. Graphs are basically structures that depict connections between two or more objects in some data. The objects or entities are called as nodes and are joined together by relationships called Edges. Each edge has a unique identifier. Each node serves as a point of contact for the graph. This pattern is very commonly used in social networks where there are a large number of entities and each entity has one or many characteristics which are connected by edges. The relational database pattern has tables that are loosely connected, whereas graphs are often very strong and rigid in nature. " }, { "code": null, "e": 3542, "s": 3529, "text": "Advantages: " }, { "code": null, "e": 3585, "s": 3542, "text": "Fastest traversal because of connections. " }, { "code": null, "e": 3622, "s": 3585, "text": "Spatial data can be easily handled. " }, { "code": null, "e": 3682, "s": 3622, "text": "Limitations: Wrong connections may lead to infinite loops. " }, { "code": null, "e": 3694, "s": 3682, "text": "Examples: " }, { "code": null, "e": 3700, "s": 3694, "text": "Neo4J" }, { "code": null, "e": 3726, "s": 3700, "text": "FlockDB( Used by Twitter)" }, { "code": null, "e": 3739, "s": 3728, "text": "nidhi_biet" }, { "code": null, "e": 3748, "s": 3739, "text": "sweetyty" }, { "code": null, "e": 3753, "s": 3748, "text": "DBMS" }, { "code": null, "e": 3772, "s": 3753, "text": "Technical Scripter" }, { "code": null, "e": 3777, "s": 3772, "text": "DBMS" }, { "code": null, "e": 3875, "s": 3777, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3886, "s": 3875, "text": "CTE in SQL" }, { "code": null, "e": 3939, "s": 3886, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 3963, "s": 3939, "text": "SQL Interview Questions" }, { "code": null, "e": 3975, "s": 3963, "text": "SQL | Views" }, { "code": null, "e": 4009, "s": 3975, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 4054, "s": 4009, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 4084, "s": 4054, "text": "Indexing in Databases | Set 1" }, { "code": null, "e": 4131, "s": 4084, "text": "Difference between Primary Key and Foreign Key" }, { "code": null, "e": 4146, "s": 4131, "text": "SQL | GROUP BY" } ]
Python | Count number of items in a dictionary value that is a list
04 Jun, 2022 In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a key is a list. To check that the value is a list or not we use the isinstance() method which is inbuilt in Python. isinstance() method takes two parameters: object - object to be checked classinfo - class, type, or tuple of classes and types It return a boolean whether the object is an instance of the given class or not. Let’s discuss different methods to count number of items in a dictionary value that is a list. Method #1 Using in operator Python3 # Python program to count number of items# in a dictionary value that is a list.def main(): # defining the dictionary d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9], 'B' : 34, 'C' : 12, 'D' : [7, 8, 9, 6, 4] } # using the in operator count = 0 for x in d: if isinstance(d[x], list): count += len(d[x]) print(count) # Calling Main if __name__ == '__main__': main() 14 Method #2: Using list comprehension Python3 # Python program to count number of items# in a dictionary value that is a list.def main(): # defining the dictionary d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9], 'B' : 34, 'C' : 12, 'D' : [7, 8, 9, 6, 4] } # using list comprehension print(sum([len(d[x]) for x in d if isinstance(d[x], list)])) if __name__ == '__main__': main() 14 Method #3: Using dict.items() Python3 # Python program to count number of items# in a dictionary value that is a list.def main(): # defining the dictionary d = { 'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9], 'B' : 34, 'C' : 12, 'D' : [7, 8, 9, 6, 4] } # using dict.items() count = 0 for key, value in d.items(): if isinstance(value, list): count += len(value) print(count) if __name__ == '__main__': main() 14 Method #4: Using enumerate() Python3 # Python program to count number of items# in a dictionary value that is a list.def main(): # defining the dictionary d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9], 'B' : 34, 'C' : 12, 'D' : [7, 8, 9, 6, 4] } # using enumerate() count = 0 for x in enumerate(d.items()): # enumerate function returns a tuple in the form # (index, (key, value)) it is a nested tuple # for accessing the value we do indexing x[1][1] if isinstance(x[1][1], list): count += len(x[1][1]) print(count) if __name__ == '__main__': main() 14 Method#5: Using values(),find() and type(). Python3 # Python program to count number of items# in a dictionary value that is a list.def main(): # defining the dictionary d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9], 'B' : 34, 'C' : 12, 'D' : [7, 8, 9, 6, 4] } # values() - to fetch values of dictionary count = 0 for x in list(d.values()): # type() - returns type of a variable type1=str(type(x)) # find() - returns position of a specified value if found else returns -1 if(type1.find('list')!=-1): count+=len(x) print(count) if __name__ == '__main__': main() 14 shubham_singh kogantibhavya Picked Python dictionary-programs python-dict Python Python Programs python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jun, 2022" }, { "code": null, "e": 483, "s": 28, "text": "In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a key is a list. To check that the value is a list or not we use the isinstance() method which is inbuilt in Python. isinstance() method takes two parameters:" }, { "code": null, "e": 568, "s": 483, "text": "object - object to be checked\nclassinfo - class, type, or tuple of classes and types" }, { "code": null, "e": 773, "s": 568, "text": "It return a boolean whether the object is an instance of the given class or not. Let’s discuss different methods to count number of items in a dictionary value that is a list. Method #1 Using in operator " }, { "code": null, "e": 781, "s": 773, "text": "Python3" }, { "code": "# Python program to count number of items# in a dictionary value that is a list.def main(): # defining the dictionary d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9], 'B' : 34, 'C' : 12, 'D' : [7, 8, 9, 6, 4] } # using the in operator count = 0 for x in d: if isinstance(d[x], list): count += len(d[x]) print(count) # Calling Main if __name__ == '__main__': main()", "e": 1201, "s": 781, "text": null }, { "code": null, "e": 1204, "s": 1201, "text": "14" }, { "code": null, "e": 1243, "s": 1204, "text": " Method #2: Using list comprehension " }, { "code": null, "e": 1251, "s": 1243, "text": "Python3" }, { "code": "# Python program to count number of items# in a dictionary value that is a list.def main(): # defining the dictionary d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9], 'B' : 34, 'C' : 12, 'D' : [7, 8, 9, 6, 4] } # using list comprehension print(sum([len(d[x]) for x in d if isinstance(d[x], list)])) if __name__ == '__main__': main()", "e": 1617, "s": 1251, "text": null }, { "code": null, "e": 1620, "s": 1617, "text": "14" }, { "code": null, "e": 1653, "s": 1620, "text": " Method #3: Using dict.items() " }, { "code": null, "e": 1661, "s": 1653, "text": "Python3" }, { "code": "# Python program to count number of items# in a dictionary value that is a list.def main(): # defining the dictionary d = { 'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9], 'B' : 34, 'C' : 12, 'D' : [7, 8, 9, 6, 4] } # using dict.items() count = 0 for key, value in d.items(): if isinstance(value, list): count += len(value) print(count) if __name__ == '__main__': main()", "e": 2087, "s": 1661, "text": null }, { "code": null, "e": 2090, "s": 2087, "text": "14" }, { "code": null, "e": 2122, "s": 2090, "text": " Method #4: Using enumerate() " }, { "code": null, "e": 2130, "s": 2122, "text": "Python3" }, { "code": "# Python program to count number of items# in a dictionary value that is a list.def main(): # defining the dictionary d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9], 'B' : 34, 'C' : 12, 'D' : [7, 8, 9, 6, 4] } # using enumerate() count = 0 for x in enumerate(d.items()): # enumerate function returns a tuple in the form # (index, (key, value)) it is a nested tuple # for accessing the value we do indexing x[1][1] if isinstance(x[1][1], list): count += len(x[1][1]) print(count) if __name__ == '__main__': main()", "e": 2719, "s": 2130, "text": null }, { "code": null, "e": 2722, "s": 2719, "text": "14" }, { "code": null, "e": 2766, "s": 2722, "text": "Method#5: Using values(),find() and type()." }, { "code": null, "e": 2774, "s": 2766, "text": "Python3" }, { "code": "# Python program to count number of items# in a dictionary value that is a list.def main(): # defining the dictionary d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9], 'B' : 34, 'C' : 12, 'D' : [7, 8, 9, 6, 4] } # values() - to fetch values of dictionary count = 0 for x in list(d.values()): # type() - returns type of a variable type1=str(type(x)) # find() - returns position of a specified value if found else returns -1 if(type1.find('list')!=-1): count+=len(x) print(count) if __name__ == '__main__': main()", "e": 3392, "s": 2774, "text": null }, { "code": null, "e": 3395, "s": 3392, "text": "14" }, { "code": null, "e": 3409, "s": 3395, "text": "shubham_singh" }, { "code": null, "e": 3423, "s": 3409, "text": "kogantibhavya" }, { "code": null, "e": 3430, "s": 3423, "text": "Picked" }, { "code": null, "e": 3457, "s": 3430, "text": "Python dictionary-programs" }, { "code": null, "e": 3469, "s": 3457, "text": "python-dict" }, { "code": null, "e": 3476, "s": 3469, "text": "Python" }, { "code": null, "e": 3492, "s": 3476, "text": "Python Programs" }, { "code": null, "e": 3504, "s": 3492, "text": "python-dict" }, { "code": null, "e": 3602, "s": 3504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3620, "s": 3602, "text": "Python Dictionary" }, { "code": null, "e": 3662, "s": 3620, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3684, "s": 3662, "text": "Enumerate() in Python" }, { "code": null, "e": 3719, "s": 3684, "text": "Read a file line by line in Python" }, { "code": null, "e": 3745, "s": 3719, "text": "Python String | replace()" }, { "code": null, "e": 3788, "s": 3745, "text": "Python program to convert a list to string" }, { "code": null, "e": 3810, "s": 3788, "text": "Defaultdict in Python" }, { "code": null, "e": 3848, "s": 3810, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3897, "s": 3848, "text": "Python | Convert string dictionary to dictionary" } ]
numpy.quantile() in Python
29 Nov, 2018 numpy.quantile(arr, q, axis = None) : Compute the qth quantile of the given data (array elements) along the specified axis. Quantile plays a very important role in Statistics when one deals with the Normal Distribution.In the figure given above, Q2 is the median of the normally distributed data. Q3 - Q2 represents the Interquantile Range of the given dataset. Parameters :arr : [array_like]input array.q : quantile value.axis : [int or tuples of int]axis along which we want to calculate the quantile value. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.out : [ndarray, optional]Different array in which we want to place the result. The array must have same dimensions as expected output. Results : qth quantile of the array (a scalar value if axis is none) or array with quantile values along specified axis. Code #1: # Python Program illustrating # numpy.quantile() method import numpy as np # 1D array arr = [20, 2, 7, 1, 34] print("arr : ", arr) print("Q2 quantile of arr : ", np.quantile(arr, .50))print("Q1 quantile of arr : ", np.quantile(arr, .25))print("Q3 quantile of arr : ", np.quantile(arr, .75))print("100th quantile of arr : ", np.quantile(arr, .1)) Output : arr : [20, 2, 7, 1, 34] Q2 quantile of arr : 7.0) Q1 quantile of arr : 2.0) Q3 quantile of arr : 20.0) 100th quantile of arr : 1.4) Code #2: # Python Program illustrating # numpy.quantile() method import numpy as np # 2D array arr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4, ]] print("\narr : \n", arr) # quantile of the flattened array print("\n50th quantile of arr, axis = None : ", np.quantile(arr, .50)) print("0th quantile of arr, axis = None : ", np.quantile(arr, 0)) # quantile along the axis = 0 print("\n50th quantile of arr, axis = 0 : ", np.quantile(arr, .25, axis = 0)) print("0th quantile of arr, axis = 0 : ", np.quantile(arr, 0, axis = 0)) # quantile along the axis = 1 print("\n50th quantile of arr, axis = 1 : ", np.quantile(arr, .50, axis = 1)) print("0th quantile of arr, axis = 1 : ", np.quantile(arr, 0, axis = 1)) print("\n0th quantile of arr, axis = 1 : \n", np.quantile(arr, .50, axis = 1, keepdims = True))print("\n0th quantile of arr, axis = 1 : \n", np.quantile(arr, 0, axis = 1, keepdims = True)) Output : arr : [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4]] 50th quantile of arr, axis = None : 15.0 0th quantile of arr, axis = None : 1) 50th quantile of arr, axis = 0 : [14.5 4. 19.5 4.5 11.5] 0th quantile of arr, axis = 0 : [14 2 12 1 4] 50th quantile of arr, axis = 1 : [17. 15. 4.] 0th quantile of arr, axis = 1 : [12 6 1] 0th quantile of arr, axis = 1 : [[17.] [15.] [ 4.]] 0th quantile of arr, axis = 1 : [[12] [ 6] [ 1]] Python numpy-Statistics Functions Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2018" }, { "code": null, "e": 152, "s": 28, "text": "numpy.quantile(arr, q, axis = None) : Compute the qth quantile of the given data (array elements) along the specified axis." }, { "code": null, "e": 390, "s": 152, "text": "Quantile plays a very important role in Statistics when one deals with the Normal Distribution.In the figure given above, Q2 is the median of the normally distributed data. Q3 - Q2 represents the Interquantile Range of the given dataset." }, { "code": null, "e": 818, "s": 390, "text": "Parameters :arr : [array_like]input array.q : quantile value.axis : [int or tuples of int]axis along which we want to calculate the quantile value. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.out : [ndarray, optional]Different array in which we want to place the result. The array must have same dimensions as expected output." }, { "code": null, "e": 939, "s": 818, "text": "Results : qth quantile of the array (a scalar value if axis is none) or array with quantile values along specified axis." }, { "code": null, "e": 948, "s": 939, "text": "Code #1:" }, { "code": "# Python Program illustrating # numpy.quantile() method import numpy as np # 1D array arr = [20, 2, 7, 1, 34] print(\"arr : \", arr) print(\"Q2 quantile of arr : \", np.quantile(arr, .50))print(\"Q1 quantile of arr : \", np.quantile(arr, .25))print(\"Q3 quantile of arr : \", np.quantile(arr, .75))print(\"100th quantile of arr : \", np.quantile(arr, .1)) ", "e": 1303, "s": 948, "text": null }, { "code": null, "e": 1312, "s": 1303, "text": "Output :" }, { "code": null, "e": 1445, "s": 1312, "text": "arr : [20, 2, 7, 1, 34]\nQ2 quantile of arr : 7.0)\nQ1 quantile of arr : 2.0)\nQ3 quantile of arr : 20.0)\n100th quantile of arr : 1.4)\n" }, { "code": null, "e": 1455, "s": 1445, "text": " Code #2:" }, { "code": "# Python Program illustrating # numpy.quantile() method import numpy as np # 2D array arr = [[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4, ]] print(\"\\narr : \\n\", arr) # quantile of the flattened array print(\"\\n50th quantile of arr, axis = None : \", np.quantile(arr, .50)) print(\"0th quantile of arr, axis = None : \", np.quantile(arr, 0)) # quantile along the axis = 0 print(\"\\n50th quantile of arr, axis = 0 : \", np.quantile(arr, .25, axis = 0)) print(\"0th quantile of arr, axis = 0 : \", np.quantile(arr, 0, axis = 0)) # quantile along the axis = 1 print(\"\\n50th quantile of arr, axis = 1 : \", np.quantile(arr, .50, axis = 1)) print(\"0th quantile of arr, axis = 1 : \", np.quantile(arr, 0, axis = 1)) print(\"\\n0th quantile of arr, axis = 1 : \\n\", np.quantile(arr, .50, axis = 1, keepdims = True))print(\"\\n0th quantile of arr, axis = 1 : \\n\", np.quantile(arr, 0, axis = 1, keepdims = True))", "e": 2398, "s": 1455, "text": null }, { "code": null, "e": 2407, "s": 2398, "text": "Output :" }, { "code": null, "e": 2863, "s": 2407, "text": "arr : \n[[14, 17, 12, 33, 44], [15, 6, 27, 8, 19], [23, 2, 54, 1, 4]]\n\n50th quantile of arr, axis = None : 15.0\n0th quantile of arr, axis = None : 1)\n\n50th quantile of arr, axis = 0 : [14.5 4. 19.5 4.5 11.5]\n0th quantile of arr, axis = 0 : [14 2 12 1 4]\n\n50th quantile of arr, axis = 1 : [17. 15. 4.]\n0th quantile of arr, axis = 1 : [12 6 1]\n\n0th quantile of arr, axis = 1 : \n[[17.]\n[15.]\n[ 4.]]\n\n0th quantile of arr, axis = 1 : \n[[12]\n[ 6]\n[ 1]]\n" }, { "code": null, "e": 2897, "s": 2863, "text": "Python numpy-Statistics Functions" }, { "code": null, "e": 2910, "s": 2897, "text": "Python-numpy" }, { "code": null, "e": 2917, "s": 2910, "text": "Python" }, { "code": null, "e": 3015, "s": 2917, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3033, "s": 3015, "text": "Python Dictionary" }, { "code": null, "e": 3075, "s": 3033, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3097, "s": 3075, "text": "Enumerate() in Python" }, { "code": null, "e": 3132, "s": 3097, "text": "Read a file line by line in Python" }, { "code": null, "e": 3158, "s": 3132, "text": "Python String | replace()" }, { "code": null, "e": 3190, "s": 3158, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3219, "s": 3190, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3246, "s": 3219, "text": "Python Classes and Objects" }, { "code": null, "e": 3276, "s": 3246, "text": "Iterate over a list in Python" } ]
How to Push Notification in Android?
21 Dec, 2020 Notification is a message which appears outside of our Application’s normal UI. A notification can appear in different formats and locations such as an icon in the status bar, a more detailed entry in the notification drawer, etc. Through the notification, we can notify users about any important updates, events of our application. By clicking the notification user can open any activity of our application or can do some action like opening any webpage etc. Let see the basic design of a notification template that appears in the navigation drawer. Part of a Notification Method for defining contents Type of argument needs to pass into the method We shall discuss all the concepts mentioned below step by step, Creating a basic notificationCreating notification channelAdding large iconMaking notification expandableMaking notification clickableAdding an action button to our notification Creating a basic notification Creating notification channel Adding large icon Making notification expandable Making notification clickable Adding an action button to our notification To create a basic notification at first we need to build a notification. Now to build notification, we must use NotificationCompat.Builder() class where we need to pass a context of activity and a channel id as an argument while making an instance of the class. Please note here we are not using Notification.Builder(). NotificationCompat gives compatibility to upper versions (Android 8.0 and above) with lower versions (below Android 8.0). Kotlin val nBuilder = NotificationCompat.Builder(this,CHANNEL_ID) .setContentTitle(et1.text.toString()) .setContentText(et2.text.toString()) .setSmallIcon(R.drawable.spp_notification_foreground) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .build() Please note, here we need to set the priority of the notification accordingly by the setPriority() method. Now to deliver the notification we need an object of NotificationManagerCompat class and then we notify it. Kotlin val nManager = NotificationManagerCompat.from(this)// Here we need to set an unique id for each// notification and the notification Builder nManager.notify(1, nBuilder) Please note that, in this method, we can deliver notification only in the android versions below 8.0 but in the android versions 8.0 and upper, no notification will appear by only this block of code. Now to deliver notifications on android version 8.0 and above versions, we need to create a notification channel. This Notification Channel concept comes from android 8.0. Here every application may have multiple channels for different types of notifications and each channel has some type of notification. Before you can deliver the notification on Android 8.0 and above versions, you must register your app’s notification channel with the system by passing an instance of NotificationChannel to createNotificationChannel(). Kotlin if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT).apply { description = CHANNEL_DESCRIPTION } val nManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager nManager.createNotificationChannel(channel) } Please note that here we must provide a unique CHANNEL_ID for each channel and also we must give a CHANNEL_NAME and CHANNEL_DESCRIPTION. Also, we must give channel importance. To set a large icon we use the setLargeIcon() method which is applied to the instance of the NotificationCompat.Builder() class. In this method, we need to pass a Bitmap form of an image. Now to convert an image file (e.g. jpg, jpeg, png, etc.) of the drawable folder into a Bitmap, we use the following code in Kotlin Kotlin // converting a jpeg file to Bitmap file and making an instance of Bitmap!val imgBitmap=BitmapFactory.decodeResource(resources,R.drawable.gfg_green) // Building notificationval nBuilder= NotificationCompat.Builder(this,CHANNEL_ID) .setContentTitle(et1.text.toString()) .setContentText(et2.text.toString()) .setSmallIcon(R.drawable.spp_notification_foreground) .setPriority(NotificationCompat.PRIORITY_DEFAULT) // passing the Bitmap object as an argument .setLargeIcon(imgBitmap) .build() In the short template of the notification, large information can’t be shown. Therefore we need to make the notification expandable like this: to make such an expandable notification we use the setStyle() method on the notification builder (nBuilder) object. In this expanded area we can display an image, any text, different messages, etc. In our Application, we have added an image by passing the instance of the NotificationCompat.BigPictureStyle class to setStyle() method. Kotlin val imgBitmap = BitmapFactory.decodeResource(resources,R.drawable.gfg_green)val nBuilder = NotificationCompat.Builder(this,CHANNEL_ID) .setContentTitle(et1.text.toString()) .setContentText(et2.text.toString()) .setSmallIcon(R.drawable.spp_notification_foreground) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setLargeIcon(imgBitmap) // Expandable notification .setStyle(NotificationCompat.BigPictureStyle() .bigPicture(imgBitmap) // as we pass null in bigLargeIcon() so the large icon // will goes away when the notification will be expanded. .bigLargeIcon(null)) .build() We need to make our notification clickable to perform some action by clicking the notification such as open an activity or system setting or any webpage etc. Now to perform such actions intent is needed (e.g. explicit or implicit intent). In our Application, we are making an Implicit intent to open the GFG official home page. Kotlin // Creating the Implicit Intent to // open the home page of GFG val intent1= Intent() intent1.action=Intent.ACTION_VIEW intent1.data=Uri.parse("https://www.geeksforgeeks.org/") Now it is not necessary that whenever the notification will appear then the user will click it instantly, user can click it whenever he /she wants and therefore we also need to make an instance of PendingIntent which basically makes the intent action pending for future purpose. Kotlin val pendingIntent1=PendingIntent.getActivity(this, 5, intent1, PendingIntent.FLAG_UPDATE_CURRENT) // Here the four parameters are context of activity,// requestCode,Intent and flag of the pendingIntent respectively// The request code is used to trigger a// particular action in application activityval nBuilder = NotificationCompat.Builder(this,CHANNEL_ID) .setContentTitle(et1.text.toString()) .setContentText(et2.text.toString()) .setSmallIcon(R.drawable.notifications) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setLargeIcon(imgBitmap) .setStyle(NotificationCompat.BigPictureStyle() .bigPicture(imgBitmap) .bigLargeIcon(null)) // here we are passing the pending intent .setContentIntent(pendingIntent1) // as we set auto cancel true, the notification // will disappear after afret clicking it .setAutoCancel(true) .build() Sometimes there exists some action button at our notification template that is used to perform some action. Here we also need an Intent and a PendingIntent. Then we need to pass the instance of the PendingIntent to addAction() method at the time of building the notification. Kotlin // Creating the Implicit Intent // to open the GFG contribution page val intent2 = Intent() intent2.action = Intent.ACTION_VIEW intent2.data = Uri.parse("https://www.geeksforgeeks.org/contribute/") val nBuilder = NotificationCompat.Builder(this,CHANNEL_ID) .setContentTitle(et1.text.toString()) .setContentText(et2.text.toString()) .setSmallIcon(R.drawable.notifications) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setLargeIcon(imgBitmap) .setStyle(NotificationCompat.BigPictureStyle() .bigPicture(imgBitmap) .bigLargeIcon(null)) .setContentIntent(pendingIntent1) .setAutoCancel(true) // Here we need to pass 3 arguments which are // icon id, title, pendingIntent respectively // Here we pass 0 as icon id which means no icon .addAction(0,"LET CONTRIBUTE",pendingIntent2) .build() Let discuss all the concepts by making an Application named GFG_PushNotification. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Choose the API level according to your choice( Here we have chosen API Level 26). After creating the project successfully, please paste some pictures into the drawable folder in the res directory. Now you can use the same pictures which I have used in my project otherwise you can choose pictures of your own choice. To download the same pictures please click on the below-given link: CLICK HERE ***Please note that it is optional*** Step 2: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:id="@+id/imgGFG" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:src="@drawable/gfg_white" /> <!-- EditText for entering the title--> <EditText android:id="@+id/et1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/imgGFG" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:background="#d7ffd9" android:hint="Enter The Title" android:padding="10dp" android:textSize="20sp" android:textStyle="bold" /> <!-- EditText for entering the text--> <EditText android:id="@+id/et2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/et1" android:layout_marginLeft="30dp" android:layout_marginTop="30dp" android:layout_marginRight="30dp" android:background="#d7ffd9" android:hint="Enter The Text" android:padding="10dp" android:textSize="20sp" android:textStyle="bold" /> <!-- Button for sending notification--> <Button android:id="@+id/btn1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/et2" android:layout_marginLeft="30dp" android:layout_marginTop="30dp" android:layout_marginRight="30dp" android:background="#0F9D58" android:text="send notification" android:textColor="#000000" android:textSize="20sp" android:textStyle="bold" /> </RelativeLayout> Step 3: Insert a vector asset into the drawable folder in the res directory Right-click on the drawable folder → New → Vector Asset → select appropriate Clip Art → give appropriate Name and adjust Size accordingly→ Next then click on the finish button as shown in the below image. Step 4: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.app.NotificationChannelimport android.app.NotificationManagerimport android.app.PendingIntentimport android.content.Contextimport android.content.Intentimport android.graphics.BitmapFactoryimport android.net.Uriimport android.os.Buildimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport androidx.appcompat.app.AppCompatActivityimport androidx.core.app.NotificationCompatimport androidx.core.app.NotificationManagerCompat class MainActivity : AppCompatActivity() { val CHANNEL_ID = "GFG" val CHANNEL_NAME = "GFG ContentWriting" val CHANNEL_DESCRIPTION = "GFG NOTIFICATION" // the String form of link for // opening the GFG home-page val link1 = "https://www.geeksforgeeks.org/" // the String form of link for opening // the GFG contribution-page val link2 = "https://www.geeksforgeeks.org/contribute/" lateinit var et1: EditText lateinit var et2: EditText lateinit var btn1: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Binding Views by their IDs et1 = findViewById(R.id.et1) et2 = findViewById(R.id.et2) btn1 = findViewById(R.id.btn1) btn1.setOnClickListener { // Converting the .png Image file to a Bitmap! val imgBitmap = BitmapFactory.decodeResource(resources, R.drawable.gfg_green) // Making intent1 to open the GFG home page val intent1 = gfgOpenerIntent(link1) // Making intent2 to open The GFG contribution page val intent2 = gfgOpenerIntent(link2) // Making pendingIntent1 to open the GFG home // page after clicking the Notification val pendingIntent1 = PendingIntent.getActivity(this, 5, intent1, PendingIntent.FLAG_UPDATE_CURRENT) // Making pendingIntent2 to open the GFG contribution // page after clicking the actionButton of the notification val pendingIntent2 = PendingIntent.getActivity(this, 6, intent2, PendingIntent.FLAG_UPDATE_CURRENT) // By invoking the notificationChannel() function we // are registering our channel to the System notificationChannel() // Building the notification val nBuilder = NotificationCompat.Builder(this, CHANNEL_ID) // adding notification Title .setContentTitle(et1.text.toString()) // adding notification Text .setContentText(et2.text.toString()) // adding notification SmallIcon .setSmallIcon(R.drawable.ic_android_black_24dp) // adding notification Priority .setPriority(NotificationCompat.PRIORITY_DEFAULT) // making the notification clickable .setContentIntent(pendingIntent1) .setAutoCancel(true) // adding action button .addAction(0, "LET CONTRIBUTE", pendingIntent2) // adding largeIcon .setLargeIcon(imgBitmap) // making notification Expandable .setStyle(NotificationCompat.BigPictureStyle() .bigPicture(imgBitmap) .bigLargeIcon(null)) .build() // finally notifying the notification val nManager = NotificationManagerCompat.from(this) nManager.notify(1, nBuilder) } } // Creating the notification channel private fun notificationChannel() { // check if the version is equal or greater // than android oreo version if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // creating notification channel and setting // the description of the channel val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT).apply { description = CHANNEL_DESCRIPTION } // registering the channel to the System val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } // The function gfgOpenerIntent() returns // an Implicit Intent to open a webpage private fun gfgOpenerIntent(link: String): Intent { val intent = Intent() intent.action = Intent.ACTION_VIEW intent.data = Uri.parse(link) return intent }} android Technical Scripter 2020 Android Kotlin Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Dec, 2020" }, { "code": null, "e": 514, "s": 53, "text": "Notification is a message which appears outside of our Application’s normal UI. A notification can appear in different formats and locations such as an icon in the status bar, a more detailed entry in the notification drawer, etc. Through the notification, we can notify users about any important updates, events of our application. By clicking the notification user can open any activity of our application or can do some action like opening any webpage etc. " }, { "code": null, "e": 606, "s": 514, "text": "Let see the basic design of a notification template that appears in the navigation drawer. " }, { "code": null, "e": 630, "s": 606, "text": "Part of a Notification " }, { "code": null, "e": 660, "s": 630, "text": "Method for defining contents " }, { "code": null, "e": 707, "s": 660, "text": "Type of argument needs to pass into the method" }, { "code": null, "e": 771, "s": 707, "text": "We shall discuss all the concepts mentioned below step by step," }, { "code": null, "e": 949, "s": 771, "text": "Creating a basic notificationCreating notification channelAdding large iconMaking notification expandableMaking notification clickableAdding an action button to our notification" }, { "code": null, "e": 979, "s": 949, "text": "Creating a basic notification" }, { "code": null, "e": 1009, "s": 979, "text": "Creating notification channel" }, { "code": null, "e": 1027, "s": 1009, "text": "Adding large icon" }, { "code": null, "e": 1058, "s": 1027, "text": "Making notification expandable" }, { "code": null, "e": 1088, "s": 1058, "text": "Making notification clickable" }, { "code": null, "e": 1132, "s": 1088, "text": "Adding an action button to our notification" }, { "code": null, "e": 1574, "s": 1132, "text": "To create a basic notification at first we need to build a notification. Now to build notification, we must use NotificationCompat.Builder() class where we need to pass a context of activity and a channel id as an argument while making an instance of the class. Please note here we are not using Notification.Builder(). NotificationCompat gives compatibility to upper versions (Android 8.0 and above) with lower versions (below Android 8.0)." }, { "code": null, "e": 1581, "s": 1574, "text": "Kotlin" }, { "code": "val nBuilder = NotificationCompat.Builder(this,CHANNEL_ID) .setContentTitle(et1.text.toString()) .setContentText(et2.text.toString()) .setSmallIcon(R.drawable.spp_notification_foreground) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .build()", "e": 1923, "s": 1581, "text": null }, { "code": null, "e": 2030, "s": 1923, "text": "Please note, here we need to set the priority of the notification accordingly by the setPriority() method." }, { "code": null, "e": 2138, "s": 2030, "text": "Now to deliver the notification we need an object of NotificationManagerCompat class and then we notify it." }, { "code": null, "e": 2145, "s": 2138, "text": "Kotlin" }, { "code": "val nManager = NotificationManagerCompat.from(this)// Here we need to set an unique id for each// notification and the notification Builder nManager.notify(1, nBuilder)", "e": 2325, "s": 2145, "text": null }, { "code": null, "e": 2525, "s": 2325, "text": "Please note that, in this method, we can deliver notification only in the android versions below 8.0 but in the android versions 8.0 and upper, no notification will appear by only this block of code." }, { "code": null, "e": 3052, "s": 2525, "text": "Now to deliver notifications on android version 8.0 and above versions, we need to create a notification channel. This Notification Channel concept comes from android 8.0. Here every application may have multiple channels for different types of notifications and each channel has some type of notification. Before you can deliver the notification on Android 8.0 and above versions, you must register your app’s notification channel with the system by passing an instance of NotificationChannel to createNotificationChannel()." }, { "code": null, "e": 3059, "s": 3052, "text": "Kotlin" }, { "code": "if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT).apply { description = CHANNEL_DESCRIPTION } val nManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager nManager.createNotificationChannel(channel) }", "e": 3486, "s": 3059, "text": null }, { "code": null, "e": 3662, "s": 3486, "text": "Please note that here we must provide a unique CHANNEL_ID for each channel and also we must give a CHANNEL_NAME and CHANNEL_DESCRIPTION. Also, we must give channel importance." }, { "code": null, "e": 3982, "s": 3662, "text": "To set a large icon we use the setLargeIcon() method which is applied to the instance of the NotificationCompat.Builder() class. In this method, we need to pass a Bitmap form of an image. Now to convert an image file (e.g. jpg, jpeg, png, etc.) of the drawable folder into a Bitmap, we use the following code in Kotlin" }, { "code": null, "e": 3989, "s": 3982, "text": "Kotlin" }, { "code": "// converting a jpeg file to Bitmap file and making an instance of Bitmap!val imgBitmap=BitmapFactory.decodeResource(resources,R.drawable.gfg_green) // Building notificationval nBuilder= NotificationCompat.Builder(this,CHANNEL_ID) .setContentTitle(et1.text.toString()) .setContentText(et2.text.toString()) .setSmallIcon(R.drawable.spp_notification_foreground) .setPriority(NotificationCompat.PRIORITY_DEFAULT) // passing the Bitmap object as an argument .setLargeIcon(imgBitmap) .build()", "e": 4612, "s": 3989, "text": null }, { "code": null, "e": 4755, "s": 4612, "text": "In the short template of the notification, large information can’t be shown. Therefore we need to make the notification expandable like this:" }, { "code": null, "e": 5091, "s": 4755, "text": "to make such an expandable notification we use the setStyle() method on the notification builder (nBuilder) object. In this expanded area we can display an image, any text, different messages, etc. In our Application, we have added an image by passing the instance of the NotificationCompat.BigPictureStyle class to setStyle() method." }, { "code": null, "e": 5098, "s": 5091, "text": "Kotlin" }, { "code": "val imgBitmap = BitmapFactory.decodeResource(resources,R.drawable.gfg_green)val nBuilder = NotificationCompat.Builder(this,CHANNEL_ID) .setContentTitle(et1.text.toString()) .setContentText(et2.text.toString()) .setSmallIcon(R.drawable.spp_notification_foreground) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setLargeIcon(imgBitmap) // Expandable notification .setStyle(NotificationCompat.BigPictureStyle() .bigPicture(imgBitmap) // as we pass null in bigLargeIcon() so the large icon // will goes away when the notification will be expanded. .bigLargeIcon(null)) .build()", "e": 5938, "s": 5098, "text": null }, { "code": null, "e": 6266, "s": 5938, "text": "We need to make our notification clickable to perform some action by clicking the notification such as open an activity or system setting or any webpage etc. Now to perform such actions intent is needed (e.g. explicit or implicit intent). In our Application, we are making an Implicit intent to open the GFG official home page." }, { "code": null, "e": 6273, "s": 6266, "text": "Kotlin" }, { "code": "// Creating the Implicit Intent to // open the home page of GFG val intent1= Intent() intent1.action=Intent.ACTION_VIEW intent1.data=Uri.parse(\"https://www.geeksforgeeks.org/\")", "e": 6466, "s": 6273, "text": null }, { "code": null, "e": 6745, "s": 6466, "text": "Now it is not necessary that whenever the notification will appear then the user will click it instantly, user can click it whenever he /she wants and therefore we also need to make an instance of PendingIntent which basically makes the intent action pending for future purpose." }, { "code": null, "e": 6752, "s": 6745, "text": "Kotlin" }, { "code": "val pendingIntent1=PendingIntent.getActivity(this, 5, intent1, PendingIntent.FLAG_UPDATE_CURRENT) // Here the four parameters are context of activity,// requestCode,Intent and flag of the pendingIntent respectively// The request code is used to trigger a// particular action in application activityval nBuilder = NotificationCompat.Builder(this,CHANNEL_ID) .setContentTitle(et1.text.toString()) .setContentText(et2.text.toString()) .setSmallIcon(R.drawable.notifications) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setLargeIcon(imgBitmap) .setStyle(NotificationCompat.BigPictureStyle() .bigPicture(imgBitmap) .bigLargeIcon(null)) // here we are passing the pending intent .setContentIntent(pendingIntent1) // as we set auto cancel true, the notification // will disappear after afret clicking it .setAutoCancel(true) .build()", "e": 7871, "s": 6752, "text": null }, { "code": null, "e": 7979, "s": 7871, "text": "Sometimes there exists some action button at our notification template that is used to perform some action." }, { "code": null, "e": 8147, "s": 7979, "text": "Here we also need an Intent and a PendingIntent. Then we need to pass the instance of the PendingIntent to addAction() method at the time of building the notification." }, { "code": null, "e": 8154, "s": 8147, "text": "Kotlin" }, { "code": "// Creating the Implicit Intent // to open the GFG contribution page val intent2 = Intent() intent2.action = Intent.ACTION_VIEW intent2.data = Uri.parse(\"https://www.geeksforgeeks.org/contribute/\") val nBuilder = NotificationCompat.Builder(this,CHANNEL_ID) .setContentTitle(et1.text.toString()) .setContentText(et2.text.toString()) .setSmallIcon(R.drawable.notifications) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setLargeIcon(imgBitmap) .setStyle(NotificationCompat.BigPictureStyle() .bigPicture(imgBitmap) .bigLargeIcon(null)) .setContentIntent(pendingIntent1) .setAutoCancel(true) // Here we need to pass 3 arguments which are // icon id, title, pendingIntent respectively // Here we pass 0 as icon id which means no icon .addAction(0,\"LET CONTRIBUTE\",pendingIntent2) .build()", "e": 9262, "s": 8154, "text": null }, { "code": null, "e": 9511, "s": 9262, "text": "Let discuss all the concepts by making an Application named GFG_PushNotification. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. " }, { "code": null, "e": 9540, "s": 9511, "text": "Step 1: Create a New Project" }, { "code": null, "e": 9786, "s": 9540, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Choose the API level according to your choice( Here we have chosen API Level 26)." }, { "code": null, "e": 10089, "s": 9786, "text": "After creating the project successfully, please paste some pictures into the drawable folder in the res directory. Now you can use the same pictures which I have used in my project otherwise you can choose pictures of your own choice. To download the same pictures please click on the below-given link:" }, { "code": null, "e": 10100, "s": 10089, "text": "CLICK HERE" }, { "code": null, "e": 10138, "s": 10100, "text": "***Please note that it is optional***" }, { "code": null, "e": 10186, "s": 10138, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 10302, "s": 10186, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 10306, "s": 10302, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <ImageView android:id=\"@+id/imgGFG\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"70dp\" android:src=\"@drawable/gfg_white\" /> <!-- EditText for entering the title--> <EditText android:id=\"@+id/et1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/imgGFG\" android:layout_marginLeft=\"30dp\" android:layout_marginRight=\"30dp\" android:background=\"#d7ffd9\" android:hint=\"Enter The Title\" android:padding=\"10dp\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <!-- EditText for entering the text--> <EditText android:id=\"@+id/et2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/et1\" android:layout_marginLeft=\"30dp\" android:layout_marginTop=\"30dp\" android:layout_marginRight=\"30dp\" android:background=\"#d7ffd9\" android:hint=\"Enter The Text\" android:padding=\"10dp\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <!-- Button for sending notification--> <Button android:id=\"@+id/btn1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/et2\" android:layout_marginLeft=\"30dp\" android:layout_marginTop=\"30dp\" android:layout_marginRight=\"30dp\" android:background=\"#0F9D58\" android:text=\"send notification\" android:textColor=\"#000000\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> </RelativeLayout>", "e": 12332, "s": 10306, "text": null }, { "code": null, "e": 12408, "s": 12332, "text": "Step 3: Insert a vector asset into the drawable folder in the res directory" }, { "code": null, "e": 12613, "s": 12408, "text": "Right-click on the drawable folder → New → Vector Asset → select appropriate Clip Art → give appropriate Name and adjust Size accordingly→ Next then click on the finish button as shown in the below image." }, { "code": null, "e": 12659, "s": 12613, "text": "Step 4: Working with the MainActivity.kt file" }, { "code": null, "e": 12845, "s": 12659, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 12852, "s": 12845, "text": "Kotlin" }, { "code": "import android.app.NotificationChannelimport android.app.NotificationManagerimport android.app.PendingIntentimport android.content.Contextimport android.content.Intentimport android.graphics.BitmapFactoryimport android.net.Uriimport android.os.Buildimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport androidx.appcompat.app.AppCompatActivityimport androidx.core.app.NotificationCompatimport androidx.core.app.NotificationManagerCompat class MainActivity : AppCompatActivity() { val CHANNEL_ID = \"GFG\" val CHANNEL_NAME = \"GFG ContentWriting\" val CHANNEL_DESCRIPTION = \"GFG NOTIFICATION\" // the String form of link for // opening the GFG home-page val link1 = \"https://www.geeksforgeeks.org/\" // the String form of link for opening // the GFG contribution-page val link2 = \"https://www.geeksforgeeks.org/contribute/\" lateinit var et1: EditText lateinit var et2: EditText lateinit var btn1: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Binding Views by their IDs et1 = findViewById(R.id.et1) et2 = findViewById(R.id.et2) btn1 = findViewById(R.id.btn1) btn1.setOnClickListener { // Converting the .png Image file to a Bitmap! val imgBitmap = BitmapFactory.decodeResource(resources, R.drawable.gfg_green) // Making intent1 to open the GFG home page val intent1 = gfgOpenerIntent(link1) // Making intent2 to open The GFG contribution page val intent2 = gfgOpenerIntent(link2) // Making pendingIntent1 to open the GFG home // page after clicking the Notification val pendingIntent1 = PendingIntent.getActivity(this, 5, intent1, PendingIntent.FLAG_UPDATE_CURRENT) // Making pendingIntent2 to open the GFG contribution // page after clicking the actionButton of the notification val pendingIntent2 = PendingIntent.getActivity(this, 6, intent2, PendingIntent.FLAG_UPDATE_CURRENT) // By invoking the notificationChannel() function we // are registering our channel to the System notificationChannel() // Building the notification val nBuilder = NotificationCompat.Builder(this, CHANNEL_ID) // adding notification Title .setContentTitle(et1.text.toString()) // adding notification Text .setContentText(et2.text.toString()) // adding notification SmallIcon .setSmallIcon(R.drawable.ic_android_black_24dp) // adding notification Priority .setPriority(NotificationCompat.PRIORITY_DEFAULT) // making the notification clickable .setContentIntent(pendingIntent1) .setAutoCancel(true) // adding action button .addAction(0, \"LET CONTRIBUTE\", pendingIntent2) // adding largeIcon .setLargeIcon(imgBitmap) // making notification Expandable .setStyle(NotificationCompat.BigPictureStyle() .bigPicture(imgBitmap) .bigLargeIcon(null)) .build() // finally notifying the notification val nManager = NotificationManagerCompat.from(this) nManager.notify(1, nBuilder) } } // Creating the notification channel private fun notificationChannel() { // check if the version is equal or greater // than android oreo version if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // creating notification channel and setting // the description of the channel val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT).apply { description = CHANNEL_DESCRIPTION } // registering the channel to the System val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } // The function gfgOpenerIntent() returns // an Implicit Intent to open a webpage private fun gfgOpenerIntent(link: String): Intent { val intent = Intent() intent.action = Intent.ACTION_VIEW intent.data = Uri.parse(link) return intent }}", "e": 17780, "s": 12852, "text": null }, { "code": null, "e": 17788, "s": 17780, "text": "android" }, { "code": null, "e": 17812, "s": 17788, "text": "Technical Scripter 2020" }, { "code": null, "e": 17820, "s": 17812, "text": "Android" }, { "code": null, "e": 17827, "s": 17820, "text": "Kotlin" }, { "code": null, "e": 17846, "s": 17827, "text": "Technical Scripter" }, { "code": null, "e": 17854, "s": 17846, "text": "Android" } ]
Sort an alphanumeric string such that the positions of alphabets and numbers remain unchanged
07 May, 2021 Given an alphanumeric string str, the task is to sort the string in such a way that if a position is occupied by an alphabet it must be occupied by an alphabet after sorting and if occupied by a number it must be occupied by a number after sorting.Examples: Input: str = “geeks12for32geeks” Output: eeeef12ggk23korssInput: str = “d4c3b2a1” Output: a1b2c3d4 Approach: We will convert the string to a character array and then sort the character array c[]. After sorting the character array the numeric characters will occupy starting indices of the array and the alphabets will occupy the remaining part of the array. The numeric half will be sorted and the alphabet part will also be sorted. We will keep two indices one at the starting index of the alphabet part al_c and one at the starting index of numeric part nu_c, now we will check the original string and if a position was occupied by an alphabet then we will replace it with c[al_c] and increment al_c else we will replace it with c[nu_c] and increment nu_c.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns the string s// in sorted form such that the// positions of alphabets and numeric// digits remain unchangedstring sort(string s){ char c[s.length() + 1]; // String to character array strcpy(c, s.c_str()); // Sort the array sort(c, c + s.length()); // Count of alphabets and numbers int al_c = 0, nu_c = 0; // Get the index from where the // alphabets start while (c[al_c] < 97) al_c++; // Now replace the string with sorted string for (int i = 0; i < s.length(); i++) { // If the position was occupied by an // alphabet then replace it with alphabet if (s[i] < 97) s[i] = c[nu_c++]; // Else replace it with a number else s[i] = c[al_c++]; } // Return the sorted string return s;} // Driver codeint main(){ string s = "d4c3b2a1"; cout << sort(s); return 0;} // A Java implementation of the approachimport java.util.*; class GFG{ // Function that returns the string s// in sorted form such that the// positions of alphabets and numeric// digits remain unchangedstatic String sort(String s){ char []c = new char[s.length() + 1]; // String to character array c = s.toCharArray(); // Sort the array Arrays.sort(c); // Count of alphabets and numbers int al_c = 0, nu_c = 0; // Get the index from where the // alphabets start while (c[al_c] < 97) al_c++; // Now replace the string with sorted string for (int i = 0; i < s.length(); i++) { // If the position was occupied by an // alphabet then replace it with alphabet if (s.charAt(i) < 97) s = s.substring(0,i)+ c[nu_c++]+s.substring(i+1); // Else replace it with a number else s = s.substring(0,i)+ c[al_c++]+s.substring(i+1); } // Return the sorted string return s;} // Driver codepublic static void main(String[] args){ String s = "d4c3b2a1"; System.out.println(sort(s));}} /* This code contributed by PrinciRaj1992 */ # Python3 implementation of the approach # Function that returns the string s# in sorted form such that the# positions of alphabets and numeric# digits remain unchangeddef sort(s): # String to character array c, s = list(s), list(s) # Sort the array c.sort() # Count of alphabets and numbers al_c = 0 nu_c = 0 # Get the index from where the # alphabets start while ord(c[al_c]) < 97: al_c += 1 # Now replace the string with sorted string for i in range(len(s)): # If the position was occupied by an # alphabet then replace it with alphabet if s[i] < 'a': s[i] = c[nu_c] nu_c += 1 # Else replace it with a number else: s[i] = c[al_c] al_c += 1 # Return the sorted string return ''.join(s) # Driver Codeif __name__ == "__main__": s = "d4c3b2a1" print(sort(s)) # This code is contributed by# sanjeev2552 // C# implementation of the approachusing System; class GFG{ // Function that returns the string s // in sorted form such that the // positions of alphabets and numeric // digits remain unchanged static string sort(string s) { char []c = new char[s.Length + 1]; // String to character array c = s.ToCharArray(); // Sort the array Array.Sort(c); // Count of alphabets and numbers int al_c = 0, nu_c = 0; // Get the index from where the // alphabets start while (c[al_c] < 97) al_c++; // Now replace the string with sorted string for (int i = 0; i < s.Length; i++) { // If the position was occupied by an // alphabet then replace it with alphabet if (s[i] < 97) s = s.Substring(0,i)+ c[nu_c++]+s.Substring(i+1); // Else replace it with a number else s = s.Substring(0,i)+ c[al_c++]+s.Substring(i+1); } // Return the sorted string return s; } // Driver code public static void Main() { string s = "d4c3b2a1"; Console.WriteLine(sort(s)); }} /* This code contributed by AnkitRai01 */ <script> // Javascript implementation of the approach // Function that returns the string s// in sorted form such that the// positions of alphabets and numeric// digits remain unchangedfunction sort(s){ var c = s.split(''); c.sort(); // Count of alphabets and numbers var al_c = 0, nu_c = 0; // Get the index from where the // alphabets start while (c[al_c].charCodeAt(0) < 97) al_c++; // Now replace the string with sorted string for (var i = 0; i < s.length; i++) { // If the position was occupied by an // alphabet then replace it with alphabet if (s[i].charCodeAt(0) < 97) s = s.substring(0,i)+ c[nu_c++]+s.substring(i+1); // Else replace it with a number else s = s.substring(0,i)+ c[al_c++]+s.substring(i+1); } // Return the sorted string return s;} // Driver codevar s = "d4c3b2a1";document.write( sort(s)); // This code is contributed by rutvik_56.</script> a1b2c3d4 Time complexity: O(N * log(N)) where N is the length of the string. princiraj1992 ankthon HarshitGargjpr sanjeev2552 rutvik_56 frequency-counting Sorting Strings Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexities of all Sorting Algorithms Merge two sorted arrays Count Inversions in an array | Set 1 (Using Merge Sort) Sort an array of 0s, 1s and 2s | Dutch National Flag problem Radix Sort Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 54, "s": 26, "text": "\n07 May, 2021" }, { "code": null, "e": 314, "s": 54, "text": "Given an alphanumeric string str, the task is to sort the string in such a way that if a position is occupied by an alphabet it must be occupied by an alphabet after sorting and if occupied by a number it must be occupied by a number after sorting.Examples: " }, { "code": null, "e": 415, "s": 314, "text": "Input: str = “geeks12for32geeks” Output: eeeef12ggk23korssInput: str = “d4c3b2a1” Output: a1b2c3d4 " }, { "code": null, "e": 1129, "s": 417, "text": "Approach: We will convert the string to a character array and then sort the character array c[]. After sorting the character array the numeric characters will occupy starting indices of the array and the alphabets will occupy the remaining part of the array. The numeric half will be sorted and the alphabet part will also be sorted. We will keep two indices one at the starting index of the alphabet part al_c and one at the starting index of numeric part nu_c, now we will check the original string and if a position was occupied by an alphabet then we will replace it with c[al_c] and increment al_c else we will replace it with c[nu_c] and increment nu_c.Below is the implementation of the above approach: " }, { "code": null, "e": 1133, "s": 1129, "text": "C++" }, { "code": null, "e": 1138, "s": 1133, "text": "Java" }, { "code": null, "e": 1146, "s": 1138, "text": "Python3" }, { "code": null, "e": 1149, "s": 1146, "text": "C#" }, { "code": null, "e": 1160, "s": 1149, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns the string s// in sorted form such that the// positions of alphabets and numeric// digits remain unchangedstring sort(string s){ char c[s.length() + 1]; // String to character array strcpy(c, s.c_str()); // Sort the array sort(c, c + s.length()); // Count of alphabets and numbers int al_c = 0, nu_c = 0; // Get the index from where the // alphabets start while (c[al_c] < 97) al_c++; // Now replace the string with sorted string for (int i = 0; i < s.length(); i++) { // If the position was occupied by an // alphabet then replace it with alphabet if (s[i] < 97) s[i] = c[nu_c++]; // Else replace it with a number else s[i] = c[al_c++]; } // Return the sorted string return s;} // Driver codeint main(){ string s = \"d4c3b2a1\"; cout << sort(s); return 0;}", "e": 2151, "s": 1160, "text": null }, { "code": "// A Java implementation of the approachimport java.util.*; class GFG{ // Function that returns the string s// in sorted form such that the// positions of alphabets and numeric// digits remain unchangedstatic String sort(String s){ char []c = new char[s.length() + 1]; // String to character array c = s.toCharArray(); // Sort the array Arrays.sort(c); // Count of alphabets and numbers int al_c = 0, nu_c = 0; // Get the index from where the // alphabets start while (c[al_c] < 97) al_c++; // Now replace the string with sorted string for (int i = 0; i < s.length(); i++) { // If the position was occupied by an // alphabet then replace it with alphabet if (s.charAt(i) < 97) s = s.substring(0,i)+ c[nu_c++]+s.substring(i+1); // Else replace it with a number else s = s.substring(0,i)+ c[al_c++]+s.substring(i+1); } // Return the sorted string return s;} // Driver codepublic static void main(String[] args){ String s = \"d4c3b2a1\"; System.out.println(sort(s));}} /* This code contributed by PrinciRaj1992 */", "e": 3287, "s": 2151, "text": null }, { "code": "# Python3 implementation of the approach # Function that returns the string s# in sorted form such that the# positions of alphabets and numeric# digits remain unchangeddef sort(s): # String to character array c, s = list(s), list(s) # Sort the array c.sort() # Count of alphabets and numbers al_c = 0 nu_c = 0 # Get the index from where the # alphabets start while ord(c[al_c]) < 97: al_c += 1 # Now replace the string with sorted string for i in range(len(s)): # If the position was occupied by an # alphabet then replace it with alphabet if s[i] < 'a': s[i] = c[nu_c] nu_c += 1 # Else replace it with a number else: s[i] = c[al_c] al_c += 1 # Return the sorted string return ''.join(s) # Driver Codeif __name__ == \"__main__\": s = \"d4c3b2a1\" print(sort(s)) # This code is contributed by# sanjeev2552", "e": 4230, "s": 3287, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function that returns the string s // in sorted form such that the // positions of alphabets and numeric // digits remain unchanged static string sort(string s) { char []c = new char[s.Length + 1]; // String to character array c = s.ToCharArray(); // Sort the array Array.Sort(c); // Count of alphabets and numbers int al_c = 0, nu_c = 0; // Get the index from where the // alphabets start while (c[al_c] < 97) al_c++; // Now replace the string with sorted string for (int i = 0; i < s.Length; i++) { // If the position was occupied by an // alphabet then replace it with alphabet if (s[i] < 97) s = s.Substring(0,i)+ c[nu_c++]+s.Substring(i+1); // Else replace it with a number else s = s.Substring(0,i)+ c[al_c++]+s.Substring(i+1); } // Return the sorted string return s; } // Driver code public static void Main() { string s = \"d4c3b2a1\"; Console.WriteLine(sort(s)); }} /* This code contributed by AnkitRai01 */", "e": 5515, "s": 4230, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function that returns the string s// in sorted form such that the// positions of alphabets and numeric// digits remain unchangedfunction sort(s){ var c = s.split(''); c.sort(); // Count of alphabets and numbers var al_c = 0, nu_c = 0; // Get the index from where the // alphabets start while (c[al_c].charCodeAt(0) < 97) al_c++; // Now replace the string with sorted string for (var i = 0; i < s.length; i++) { // If the position was occupied by an // alphabet then replace it with alphabet if (s[i].charCodeAt(0) < 97) s = s.substring(0,i)+ c[nu_c++]+s.substring(i+1); // Else replace it with a number else s = s.substring(0,i)+ c[al_c++]+s.substring(i+1); } // Return the sorted string return s;} // Driver codevar s = \"d4c3b2a1\";document.write( sort(s)); // This code is contributed by rutvik_56.</script>", "e": 6484, "s": 5515, "text": null }, { "code": null, "e": 6493, "s": 6484, "text": "a1b2c3d4" }, { "code": null, "e": 6564, "s": 6495, "text": "Time complexity: O(N * log(N)) where N is the length of the string. " }, { "code": null, "e": 6578, "s": 6564, "text": "princiraj1992" }, { "code": null, "e": 6586, "s": 6578, "text": "ankthon" }, { "code": null, "e": 6601, "s": 6586, "text": "HarshitGargjpr" }, { "code": null, "e": 6613, "s": 6601, "text": "sanjeev2552" }, { "code": null, "e": 6623, "s": 6613, "text": "rutvik_56" }, { "code": null, "e": 6642, "s": 6623, "text": "frequency-counting" }, { "code": null, "e": 6650, "s": 6642, "text": "Sorting" }, { "code": null, "e": 6658, "s": 6650, "text": "Strings" }, { "code": null, "e": 6666, "s": 6658, "text": "Strings" }, { "code": null, "e": 6674, "s": 6666, "text": "Sorting" }, { "code": null, "e": 6772, "s": 6674, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6816, "s": 6772, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 6840, "s": 6816, "text": "Merge two sorted arrays" }, { "code": null, "e": 6896, "s": 6840, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 6957, "s": 6896, "text": "Sort an array of 0s, 1s and 2s | Dutch National Flag problem" }, { "code": null, "e": 6968, "s": 6957, "text": "Radix Sort" }, { "code": null, "e": 7014, "s": 6968, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 7039, "s": 7014, "text": "Reverse a string in Java" }, { "code": null, "e": 7099, "s": 7039, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7114, "s": 7099, "text": "C++ Data Types" } ]
Chaining Commands in Linux
14 Oct, 2020 Chaining commands in Linux allows us to execute multiple commands at the same time and directly through the terminal. It’s like short shell scripts that can be executed through the terminal directly. Linux command chaining is a technique of merging several commands such that each of them can execute in sequence depending on the operator that separates them and these operators decide how the commands will get executed. It allows us to run multiple commands in succession or simultaneously. Some commonly used chaining operators are as follows: Operators Function 1. Ampersand(&) Operator: It is used to run a command in the background so that other commands can be executed. It sends a process/script/command to the background so that other commands can be executed in the foreground. It increases the effective utilization of system resources and speeds up the script execution. This is also called as Child process creation or forking in other programming languages. Ampersand sign can be used as follows: ping -cl google.com & #change the command before & ping -c1 google.com & ping -c1 geeksforgeeks.org & 2. AND (&&) Operator: The command succeeding this operator will only execute if the command preceding it gets successfully executed . It is helpful when we want to execute a command if the first command has executed successfully. echo "hello there" && echo "this is gfg" apt update && echo "hello" 3. Semi-colon(;) Operator: It is used to run multiple commands sequentially in a single go. But it is important to note that the commands chained by (;) operator always executes sequentially. If two commands are separated by the operator, then the second command will always execute independently of the exit status of the first command. Unlike the ampersand operator, the execution of the second command is independent of the exit status of the first command. Even if the first command does not get successfully executed i.e, the exit status is non-zero, the second command will always execute. who;pwd;ls The three commands will get executed sequentially. But the execution of the command preceding ( ; ) operator will execute even if the execution of the first command is not successful. 4. Logical OR (||) Operator: The command succeeding this operator will only execute if the execution of the command preceding it fails. It is much like an else statement. If the execution status of the first command is non-zero then the second command will get executed. echo "hello there" || echo "This is gfg" apt update || echo "hello" 5. Piping (|) Operator: This operator sends the output of the first command to the input of the second command. ls -l | wc -l In the above command wc -l displays the number of lines. ls -l displays the lists the files in the system. The first command displays the number of files in the directory. ls – l lists the names of the files and this output is sent to the next command which counts the number of lines in the input. As a result, by using pipe we get the number of files in the directory. 6. NOT (!) operator: It is used to negate an expression in command/. We can use it to delete all files except one in a directory. touch a.txt b.txt c.txt d.txt e.txt rm -r !(a.txt) This command will remove all files in the directory except a.txt. In the image below, we create some files using the touch command inside a directory. ls shows the files in the directory. To delete all files except ‘a.txt’ we use! Operator. If we list the files again, we can see that all files except a.txt are removed. 7. Redirection Operators(‘<‘,’>’,’>>’): This operator is used to redirect the output of a command or a group of commands to a stream or file. This operator can be used to redirect either standard input or standard output or both. Almost all commands accept input with redirection operators. cat >>file_name sort <file_name The first command creates a file with the name ‘file_name’ (The redirection operator >> allows us to give input in the file) while the second command will sort the contents of the file. Refer to the image below, we first create a file with numbers and then use this command. This sorts the content of the files. 8. AND, OR Operators as an if-else condition: This command can be used as an if-else statement. It is a combination of logical AND and logical OR operators. [ ! -d ABC ] && mkdir ABC || cd ABC This command will first check if the directory ‘ABC’ exists or not. If it does not exist then a new directory is created else ‘ABC’ becomes the current directory. Refer to the image below, the directory named ‘ABC’ does not exist and hence it is created. When the same command is executed the second time, then the directory already exists and hence ‘ABC’ becomes the current directory. 9. Concatenation Operator(\): Used to concatenate large commands over several lines in a shell. It also improves the readability for the users. A large command is split over several lines and hence, it is used to execute large commands. gedit text\(1\).txt It will open a file named text(1). 10. Precedence: This command is used to set precedent value so that multiple commands can execute in a given order. cmd1 && cmd 2 || cmd3 ( cmd1 && cmd 2 ) || cmd3 In the first case, if the first command is successful then the second will get executed but the third command will not execute. But in the second case, the third command will get executed as the precedence is set using the () operator. Refer to the image below: If the directory exists (the first command), then the current directory becomes PQR (second command) but in the first case the third command is not getting executed while in the second case when the precedence operator is used then the third command is also executed. 11. Combination Operator ({}): The execution of the command succeeding this operator depends on the execution of the first command. The set of commands combined using {} operator executes when the command preceding it has successfully executed. [ -f hello.txt ] && echo "file exists" ; echo "hello" [ -f hello.txt ] && { echo "file exists" ; echo "hello"; } In the first case, hello will always get printed. If the file exists then the command will get executed as it is preceding the && operator. If we want to execute both second and third commands only if the file exists, then we use {} operators to combine the commands. linux-command Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Oct, 2020" }, { "code": null, "e": 545, "s": 52, "text": "Chaining commands in Linux allows us to execute multiple commands at the same time and directly through the terminal. It’s like short shell scripts that can be executed through the terminal directly. Linux command chaining is a technique of merging several commands such that each of them can execute in sequence depending on the operator that separates them and these operators decide how the commands will get executed. It allows us to run multiple commands in succession or simultaneously." }, { "code": null, "e": 599, "s": 545, "text": "Some commonly used chaining operators are as follows:" }, { "code": null, "e": 609, "s": 599, "text": "Operators" }, { "code": null, "e": 618, "s": 609, "text": "Function" }, { "code": null, "e": 1063, "s": 618, "text": "1. Ampersand(&) Operator: It is used to run a command in the background so that other commands can be executed. It sends a process/script/command to the background so that other commands can be executed in the foreground. It increases the effective utilization of system resources and speeds up the script execution. This is also called as Child process creation or forking in other programming languages. Ampersand sign can be used as follows:" }, { "code": null, "e": 1166, "s": 1063, "text": "ping -cl google.com & #change the command before &\nping -c1 google.com & ping -c1 geeksforgeeks.org &\n" }, { "code": null, "e": 1396, "s": 1166, "text": "2. AND (&&) Operator: The command succeeding this operator will only execute if the command preceding it gets successfully executed . It is helpful when we want to execute a command if the first command has executed successfully." }, { "code": null, "e": 1465, "s": 1396, "text": "echo \"hello there\" && echo \"this is gfg\"\napt update && echo \"hello\"\n" }, { "code": null, "e": 2061, "s": 1465, "text": "3. Semi-colon(;) Operator: It is used to run multiple commands sequentially in a single go. But it is important to note that the commands chained by (;) operator always executes sequentially. If two commands are separated by the operator, then the second command will always execute independently of the exit status of the first command. Unlike the ampersand operator, the execution of the second command is independent of the exit status of the first command. Even if the first command does not get successfully executed i.e, the exit status is non-zero, the second command will always execute." }, { "code": null, "e": 2073, "s": 2061, "text": "who;pwd;ls\n" }, { "code": null, "e": 2257, "s": 2073, "text": "The three commands will get executed sequentially. But the execution of the command preceding ( ; ) operator will execute even if the execution of the first command is not successful." }, { "code": null, "e": 2528, "s": 2257, "text": "4. Logical OR (||) Operator: The command succeeding this operator will only execute if the execution of the command preceding it fails. It is much like an else statement. If the execution status of the first command is non-zero then the second command will get executed." }, { "code": null, "e": 2597, "s": 2528, "text": "echo \"hello there\" || echo \"This is gfg\"\napt update || echo \"hello\"\n" }, { "code": null, "e": 2709, "s": 2597, "text": "5. Piping (|) Operator: This operator sends the output of the first command to the input of the second command." }, { "code": null, "e": 2724, "s": 2709, "text": "ls -l | wc -l\n" }, { "code": null, "e": 3096, "s": 2724, "text": "In the above command wc -l displays the number of lines. ls -l displays the lists the files in the system. The first command displays the number of files in the directory. ls – l lists the names of the files and this output is sent to the next command which counts the number of lines in the input. As a result, by using pipe we get the number of files in the directory." }, { "code": null, "e": 3226, "s": 3096, "text": "6. NOT (!) operator: It is used to negate an expression in command/. We can use it to delete all files except one in a directory." }, { "code": null, "e": 3278, "s": 3226, "text": "touch a.txt b.txt c.txt d.txt e.txt\nrm -r !(a.txt)\n" }, { "code": null, "e": 3600, "s": 3278, "text": "This command will remove all files in the directory except a.txt. In the image below, we create some files using the touch command inside a directory. ls shows the files in the directory. To delete all files except ‘a.txt’ we use! Operator. If we list the files again, we can see that all files except a.txt are removed." }, { "code": null, "e": 3891, "s": 3600, "text": "7. Redirection Operators(‘<‘,’>’,’>>’): This operator is used to redirect the output of a command or a group of commands to a stream or file. This operator can be used to redirect either standard input or standard output or both. Almost all commands accept input with redirection operators." }, { "code": null, "e": 3924, "s": 3891, "text": "cat >>file_name\nsort <file_name\n" }, { "code": null, "e": 4237, "s": 3924, "text": "The first command creates a file with the name ‘file_name’ (The redirection operator >> allows us to give input in the file) while the second command will sort the contents of the file. Refer to the image below, we first create a file with numbers and then use this command. This sorts the content of the files." }, { "code": null, "e": 4394, "s": 4237, "text": "8. AND, OR Operators as an if-else condition: This command can be used as an if-else statement. It is a combination of logical AND and logical OR operators." }, { "code": null, "e": 4431, "s": 4394, "text": "[ ! -d ABC ] && mkdir ABC || cd ABC\n" }, { "code": null, "e": 4818, "s": 4431, "text": "This command will first check if the directory ‘ABC’ exists or not. If it does not exist then a new directory is created else ‘ABC’ becomes the current directory. Refer to the image below, the directory named ‘ABC’ does not exist and hence it is created. When the same command is executed the second time, then the directory already exists and hence ‘ABC’ becomes the current directory." }, { "code": null, "e": 5056, "s": 4818, "text": "9. Concatenation Operator(\\): Used to concatenate large commands over several lines in a shell. It also improves the readability for the users. A large command is split over several lines and hence, it is used to execute large commands." }, { "code": null, "e": 5077, "s": 5056, "text": "gedit text\\(1\\).txt\n" }, { "code": null, "e": 5112, "s": 5077, "text": "It will open a file named text(1)." }, { "code": null, "e": 5228, "s": 5112, "text": "10. Precedence: This command is used to set precedent value so that multiple commands can execute in a given order." }, { "code": null, "e": 5277, "s": 5228, "text": "cmd1 && cmd 2 || cmd3\n( cmd1 && cmd 2 ) || cmd3\n" }, { "code": null, "e": 5807, "s": 5277, "text": "In the first case, if the first command is successful then the second will get executed but the third command will not execute. But in the second case, the third command will get executed as the precedence is set using the () operator. Refer to the image below: If the directory exists (the first command), then the current directory becomes PQR (second command) but in the first case the third command is not getting executed while in the second case when the precedence operator is used then the third command is also executed." }, { "code": null, "e": 6052, "s": 5807, "text": "11. Combination Operator ({}): The execution of the command succeeding this operator depends on the execution of the first command. The set of commands combined using {} operator executes when the command preceding it has successfully executed." }, { "code": null, "e": 6166, "s": 6052, "text": "[ -f hello.txt ] && echo \"file exists\" ; echo \"hello\"\n[ -f hello.txt ] && { echo \"file exists\" ; echo \"hello\"; }\n" }, { "code": null, "e": 6434, "s": 6166, "text": "In the first case, hello will always get printed. If the file exists then the command will get executed as it is preceding the && operator. If we want to execute both second and third commands only if the file exists, then we use {} operators to combine the commands." }, { "code": null, "e": 6448, "s": 6434, "text": "linux-command" }, { "code": null, "e": 6459, "s": 6448, "text": "Linux-Unix" } ]
Overriding in Java programming
The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement. In object-oriented terms, overriding means to override the functionality of an existing method. Live Demo class Animal { public void move() { System.out.println("Animals can move"); } } class Dog extends Animal { public void move() { System.out.println("Dogs can walk and run"); } } public class TestDog { public static void main(String args[]) { Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move(); // runs the method in Animal class b.move(); // runs the method in Dog class } } Animals can move Dogs can walk and run In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object. Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object. Live Demo class Animal { public void move() { System.out.println("Animals can move"); } } class Dog extends Animal { public void move() { System.out.println("Dogs can walk and run"); } public void bark() { System.out.println("Dogs can bark"); } } public class TestDog { public static void main(String args[]) { Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move(); // runs the method in Animal class b.move(); // runs the method in Dog class b.bark(); } } TestDog.java:26: error: cannot find symbol b.bark(); ^ symbol: method bark() location: variable b of type Animal 1 error This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of bark. The argument list should be exactly the same as that of the overridden method. The argument list should be exactly the same as that of the overridden method. The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. The access level cannot be more restrictive than the overridden method's access level. For example: If the superclass method is declared public then the overridding method in the sub class cannot be either private or protected. The access level cannot be more restrictive than the overridden method's access level. For example: If the superclass method is declared public then the overridding method in the sub class cannot be either private or protected. Instance methods can be overridden only if they are inherited by the subclass. Instance methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited, then it cannot be overridden. If a method cannot be inherited, then it cannot be overridden. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. A subclass in a different package can only override the non-final methods declared public or protected. A subclass in a different package can only override the non-final methods declared public or protected. An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method. An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method. Constructors cannot be overridden. Constructors cannot be overridden. When invoking a superclass version of an overridden method the super keyword is used. Live Demo class Animal { public void move() { System.out.println("Animals can move"); } } class Dog extends Animal { public void move() { super.move(); // invokes the super class method System.out.println("Dogs can walk and run"); } } public class TestDog { public static void main(String args[]) { Animal b = new Dog(); // Animal reference but Dog object b.move(); // runs the method in Dog class } } Animals can move Dogs can walk and run
[ { "code": null, "e": 1244, "s": 1062, "text": "The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement." }, { "code": null, "e": 1340, "s": 1244, "text": "In object-oriented terms, overriding means to override the functionality of an existing method." }, { "code": null, "e": 1351, "s": 1340, "text": " Live Demo" }, { "code": null, "e": 1850, "s": 1351, "text": "class Animal {\n public void move() {\n System.out.println(\"Animals can move\");\n }\n}\nclass Dog extends Animal {\n public void move() {\n System.out.println(\"Dogs can walk and run\");\n }\n}\npublic class TestDog {\n public static void main(String args[]) {\n Animal a = new Animal(); // Animal reference and object\n Animal b = new Dog(); // Animal reference but Dog object\n a.move(); // runs the method in Animal class\n b.move(); // runs the method in Dog class\n }\n}" }, { "code": null, "e": 1889, "s": 1850, "text": "Animals can move\nDogs can walk and run" }, { "code": null, "e": 2208, "s": 1889, "text": "In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object." }, { "code": null, "e": 2382, "s": 2208, "text": "Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object." }, { "code": null, "e": 2393, "s": 2382, "text": " Live Demo" }, { "code": null, "e": 2980, "s": 2393, "text": "class Animal {\n public void move() {\n System.out.println(\"Animals can move\");\n }\n}\nclass Dog extends Animal {\n public void move() {\n System.out.println(\"Dogs can walk and run\");\n }\n public void bark() {\n System.out.println(\"Dogs can bark\");\n }\n}\npublic class TestDog {\n public static void main(String args[]) {\n Animal a = new Animal(); // Animal reference and object\n Animal b = new Dog(); // Animal reference but Dog object\n a.move(); // runs the method in Animal class\n b.move(); // runs the method in Dog class\n b.bark();\n }\n}" }, { "code": null, "e": 3101, "s": 2980, "text": "TestDog.java:26: error: cannot find symbol\nb.bark();\n^\nsymbol: method bark()\nlocation: variable b of type Animal\n1 error" }, { "code": null, "e": 3221, "s": 3101, "text": "This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of bark." }, { "code": null, "e": 3300, "s": 3221, "text": "The argument list should be exactly the same as that of the overridden method." }, { "code": null, "e": 3379, "s": 3300, "text": "The argument list should be exactly the same as that of the overridden method." }, { "code": null, "e": 3508, "s": 3379, "text": "The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass." }, { "code": null, "e": 3637, "s": 3508, "text": "The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass." }, { "code": null, "e": 3865, "s": 3637, "text": "The access level cannot be more restrictive than the overridden method's access level. For example: If the superclass method is declared public then the overridding method in the sub class cannot be either private or protected." }, { "code": null, "e": 4093, "s": 3865, "text": "The access level cannot be more restrictive than the overridden method's access level. For example: If the superclass method is declared public then the overridding method in the sub class cannot be either private or protected." }, { "code": null, "e": 4172, "s": 4093, "text": "Instance methods can be overridden only if they are inherited by the subclass." }, { "code": null, "e": 4251, "s": 4172, "text": "Instance methods can be overridden only if they are inherited by the subclass." }, { "code": null, "e": 4297, "s": 4251, "text": "A method declared final cannot be overridden." }, { "code": null, "e": 4343, "s": 4297, "text": "A method declared final cannot be overridden." }, { "code": null, "e": 4413, "s": 4343, "text": "A method declared static cannot be overridden but can be re-declared." }, { "code": null, "e": 4483, "s": 4413, "text": "A method declared static cannot be overridden but can be re-declared." }, { "code": null, "e": 4546, "s": 4483, "text": "If a method cannot be inherited, then it cannot be overridden." }, { "code": null, "e": 4609, "s": 4546, "text": "If a method cannot be inherited, then it cannot be overridden." }, { "code": null, "e": 4747, "s": 4609, "text": "A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final." }, { "code": null, "e": 4885, "s": 4747, "text": "A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final." }, { "code": null, "e": 4989, "s": 4885, "text": "A subclass in a different package can only override the non-final methods declared public or protected." }, { "code": null, "e": 5093, "s": 4989, "text": "A subclass in a different package can only override the non-final methods declared public or protected." }, { "code": null, "e": 5447, "s": 5093, "text": "An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method." }, { "code": null, "e": 5801, "s": 5447, "text": "An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method." }, { "code": null, "e": 5836, "s": 5801, "text": "Constructors cannot be overridden." }, { "code": null, "e": 5871, "s": 5836, "text": "Constructors cannot be overridden." }, { "code": null, "e": 5957, "s": 5871, "text": "When invoking a superclass version of an overridden method the super keyword is used." }, { "code": null, "e": 5968, "s": 5957, "text": " Live Demo" }, { "code": null, "e": 6408, "s": 5968, "text": "class Animal {\n public void move() {\n System.out.println(\"Animals can move\");\n }\n}\nclass Dog extends Animal {\n public void move() {\n super.move(); // invokes the super class method\n System.out.println(\"Dogs can walk and run\");\n }\n}\npublic class TestDog {\n public static void main(String args[]) {\n Animal b = new Dog(); // Animal reference but Dog object\n b.move(); // runs the method in Dog class\n }\n}" }, { "code": null, "e": 6447, "s": 6408, "text": "Animals can move\nDogs can walk and run" } ]
Given a number N in decimal base, find the sum of digits in any base B - GeeksforGeeks
06 Nov, 2021 Given a number N in decimal base, the task is to find the sum of digits of the number in any base B. Examples: Input: N = 100, B = 8 Output: 9 Explanation: (100)8 = 144 Sum(144) = 1 + 4 + 4 = 9Input: N = 50, B = 2 Output: 3 Explanation: (50)2 = 110010 Sum(110010) = 1 + 1 + 0 + 0 + 1 + 0 = 3 Approach: Find unit digit by performing modulo operation on number N by base B and updating the number again by N = N / B and update sum by adding the unit digit at each step. Below is the implementation of above approach C++ Java Python3 C# Javascript // C++ Implementation to Compute Sum of// Digits of Number N in Base B #include <iostream>using namespace std; // Function to compute sum of// Digits of Number N in base Bint sumOfDigit(int n, int b){ // Initialize sum with 0 int unitDigit, sum = 0; while (n > 0) { // Compute unit digit of the number unitDigit = n % b; // Add unit digit in sum sum += unitDigit; // Update value of Number n = n / b; } return sum;} // Driver functionint main(){ int n = 50; int b = 2; cout << sumOfDigit(n, b); return 0;} // Java Implementation to Compute Sum of// Digits of Number N in Base Bclass GFG{ // Function to compute sum of// Digits of Number N in base Bstatic int sumOfDigit(int n, int b){ // Initialize sum with 0 int unitDigit, sum = 0; while (n > 0) { // Compute unit digit of the number unitDigit = n % b; // Add unit digit in sum sum += unitDigit; // Update value of Number n = n / b; } return sum;} // Driver codepublic static void main(String[] args){ int n = 50; int b = 2; System.out.print(sumOfDigit(n, b));}} // This code is contributed by PrinciRaj1992 # Python3 Implementation to Compute Sum of# Digits of Number N in Base B # Function to compute sum of# Digits of Number N in base Bdef sumOfDigit(n, b): # Initialize sum with 0 unitDigit = 0 sum = 0 while (n > 0): # Compute unit digit of the number unitDigit = n % b # Add unit digit in sum sum += unitDigit # Update value of Number n = n // b return sum # Driver coden = 50b = 2print(sumOfDigit(n, b)) # This code is contributed by ApurvaRaj // C# Implementation to Compute Sum of// Digits of Number N in Base Busing System; class GFG{ // Function to compute sum of// Digits of Number N in base Bstatic int sumOfDigit(int n, int b){ // Initialize sum with 0 int unitDigit, sum = 0; while (n > 0) { // Compute unit digit of the number unitDigit = n % b; // Add unit digit in sum sum += unitDigit; // Update value of Number n = n / b; } return sum;} // Driver codepublic static void Main(String[] args){ int n = 50; int b = 2; Console.Write(sumOfDigit(n, b));}} // This code is contributed by PrinciRaj1992 <script> // Javascript Implementation to Compute Sum of// Digits of Number N in Base B // Function to compute sum of// Digits of Number N in base Bfunction sumOfDigit(n, b){ // Initialize sum with 0 var unitDigit, sum = 0; while (n > 0) { // Compute unit digit of the number unitDigit = n % b; // Add unit digit in sum sum += unitDigit; // Update value of Number n = parseInt(n / b); } return sum;} // Driver functionvar n = 50;var b = 2;document.write(sumOfDigit(n, b)); // This code is contributed by rutvik_56.</script> 3 Time Complexity: O(N), N = number of digits Auxiliary Space: O(1) ApurvaRaj princiraj1992 rutvik_56 sweetyty arorakashish0911 rohitsingh07052 base-conversion number-digits Technical Scripter 2019 Mathematical Technical Scripter Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Program to multiply two matrices Fizz Buzz Implementation Find pair with maximum GCD in an array Find Union and Intersection of two unsorted arrays Count all possible paths from top left to bottom right of a mXn matrix Count ways to reach the n'th stair
[ { "code": null, "e": 24325, "s": 24297, "text": "\n06 Nov, 2021" }, { "code": null, "e": 24438, "s": 24325, "text": "Given a number N in decimal base, the task is to find the sum of digits of the number in any base B. Examples: " }, { "code": null, "e": 24621, "s": 24438, "text": "Input: N = 100, B = 8 Output: 9 Explanation: (100)8 = 144 Sum(144) = 1 + 4 + 4 = 9Input: N = 50, B = 2 Output: 3 Explanation: (50)2 = 110010 Sum(110010) = 1 + 1 + 0 + 0 + 1 + 0 = 3 " }, { "code": null, "e": 24847, "s": 24623, "text": "Approach: Find unit digit by performing modulo operation on number N by base B and updating the number again by N = N / B and update sum by adding the unit digit at each step. Below is the implementation of above approach " }, { "code": null, "e": 24851, "s": 24847, "text": "C++" }, { "code": null, "e": 24856, "s": 24851, "text": "Java" }, { "code": null, "e": 24864, "s": 24856, "text": "Python3" }, { "code": null, "e": 24867, "s": 24864, "text": "C#" }, { "code": null, "e": 24878, "s": 24867, "text": "Javascript" }, { "code": "// C++ Implementation to Compute Sum of// Digits of Number N in Base B #include <iostream>using namespace std; // Function to compute sum of// Digits of Number N in base Bint sumOfDigit(int n, int b){ // Initialize sum with 0 int unitDigit, sum = 0; while (n > 0) { // Compute unit digit of the number unitDigit = n % b; // Add unit digit in sum sum += unitDigit; // Update value of Number n = n / b; } return sum;} // Driver functionint main(){ int n = 50; int b = 2; cout << sumOfDigit(n, b); return 0;}", "e": 25469, "s": 24878, "text": null }, { "code": "// Java Implementation to Compute Sum of// Digits of Number N in Base Bclass GFG{ // Function to compute sum of// Digits of Number N in base Bstatic int sumOfDigit(int n, int b){ // Initialize sum with 0 int unitDigit, sum = 0; while (n > 0) { // Compute unit digit of the number unitDigit = n % b; // Add unit digit in sum sum += unitDigit; // Update value of Number n = n / b; } return sum;} // Driver codepublic static void main(String[] args){ int n = 50; int b = 2; System.out.print(sumOfDigit(n, b));}} // This code is contributed by PrinciRaj1992", "e": 26108, "s": 25469, "text": null }, { "code": "# Python3 Implementation to Compute Sum of# Digits of Number N in Base B # Function to compute sum of# Digits of Number N in base Bdef sumOfDigit(n, b): # Initialize sum with 0 unitDigit = 0 sum = 0 while (n > 0): # Compute unit digit of the number unitDigit = n % b # Add unit digit in sum sum += unitDigit # Update value of Number n = n // b return sum # Driver coden = 50b = 2print(sumOfDigit(n, b)) # This code is contributed by ApurvaRaj", "e": 26621, "s": 26108, "text": null }, { "code": "// C# Implementation to Compute Sum of// Digits of Number N in Base Busing System; class GFG{ // Function to compute sum of// Digits of Number N in base Bstatic int sumOfDigit(int n, int b){ // Initialize sum with 0 int unitDigit, sum = 0; while (n > 0) { // Compute unit digit of the number unitDigit = n % b; // Add unit digit in sum sum += unitDigit; // Update value of Number n = n / b; } return sum;} // Driver codepublic static void Main(String[] args){ int n = 50; int b = 2; Console.Write(sumOfDigit(n, b));}} // This code is contributed by PrinciRaj1992", "e": 27269, "s": 26621, "text": null }, { "code": "<script> // Javascript Implementation to Compute Sum of// Digits of Number N in Base B // Function to compute sum of// Digits of Number N in base Bfunction sumOfDigit(n, b){ // Initialize sum with 0 var unitDigit, sum = 0; while (n > 0) { // Compute unit digit of the number unitDigit = n % b; // Add unit digit in sum sum += unitDigit; // Update value of Number n = parseInt(n / b); } return sum;} // Driver functionvar n = 50;var b = 2;document.write(sumOfDigit(n, b)); // This code is contributed by rutvik_56.</script>", "e": 27868, "s": 27269, "text": null }, { "code": null, "e": 27870, "s": 27868, "text": "3" }, { "code": null, "e": 27916, "s": 27872, "text": "Time Complexity: O(N), N = number of digits" }, { "code": null, "e": 27938, "s": 27916, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 27948, "s": 27938, "text": "ApurvaRaj" }, { "code": null, "e": 27962, "s": 27948, "text": "princiraj1992" }, { "code": null, "e": 27972, "s": 27962, "text": "rutvik_56" }, { "code": null, "e": 27981, "s": 27972, "text": "sweetyty" }, { "code": null, "e": 27998, "s": 27981, "text": "arorakashish0911" }, { "code": null, "e": 28014, "s": 27998, "text": "rohitsingh07052" }, { "code": null, "e": 28030, "s": 28014, "text": "base-conversion" }, { "code": null, "e": 28044, "s": 28030, "text": "number-digits" }, { "code": null, "e": 28068, "s": 28044, "text": "Technical Scripter 2019" }, { "code": null, "e": 28081, "s": 28068, "text": "Mathematical" }, { "code": null, "e": 28100, "s": 28081, "text": "Technical Scripter" }, { "code": null, "e": 28113, "s": 28100, "text": "Mathematical" }, { "code": null, "e": 28211, "s": 28113, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28220, "s": 28211, "text": "Comments" }, { "code": null, "e": 28233, "s": 28220, "text": "Old Comments" }, { "code": null, "e": 28278, "s": 28233, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 28310, "s": 28278, "text": "Check if a number is Palindrome" }, { "code": null, "e": 28354, "s": 28310, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 28388, "s": 28354, "text": "Program to add two binary strings" }, { "code": null, "e": 28421, "s": 28388, "text": "Program to multiply two matrices" }, { "code": null, "e": 28446, "s": 28421, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 28485, "s": 28446, "text": "Find pair with maximum GCD in an array" }, { "code": null, "e": 28536, "s": 28485, "text": "Find Union and Intersection of two unsorted arrays" }, { "code": null, "e": 28607, "s": 28536, "text": "Count all possible paths from top left to bottom right of a mXn matrix" } ]
GATE | GATE-CS-2003 | Question 86 - GeeksforGeeks
28 Jun, 2021 Consider the set of relations shown below and the SQL query that follows. Students: (Roll_number, Name, Date_of_birth) Courses: (Course number, Course_name, Instructor) Grades: (Roll_number, Course_number, Grade) select distinct Name from Students, Courses, Grades where Students. Roll_number = Grades.Roll_number and Courses.Instructor = Korth and Courses.Course_number = Grades.Course_number and Grades.grade = A Which of the following sets is computed by the above query?(A) Names of students who have got an A grade in all courses taught by Korth(B) Names of students who have got an A grade in all courses(C) Names of students who have got an A grade in at least one of the courses taught by Korth(D) None of the aboveAnswer: (C)Explanation: The query gives the name of all the students who have scored “A” grade in any of the courses that are taught by Korth.So, C is the correct choice. Please comment below if you find anything wrong in the above post.Quiz of this Question GATE-CS-2003 GATE-GATE-CS-2003 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2004 | Question 3 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2019 | Question 27 GATE | GATE CS 2021 | Set 1 | Question 47 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2017 (Set 2) | Question 42 GATE | GATE-IT-2004 | Question 71
[ { "code": null, "e": 24491, "s": 24463, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24565, "s": 24491, "text": "Consider the set of relations shown below and the SQL query that follows." }, { "code": null, "e": 24708, "s": 24565, "text": "Students: (Roll_number, Name, Date_of_birth)\n Courses: (Course number, Course_name, Instructor)\n Grades: (Roll_number, Course_number, Grade)" }, { "code": null, "e": 24971, "s": 24708, "text": " select distinct Name\n from Students, Courses, Grades\n where Students. Roll_number = Grades.Roll_number\n and Courses.Instructor = Korth\n and Courses.Course_number = Grades.Course_number\n and Grades.grade = A" }, { "code": null, "e": 25538, "s": 24971, "text": "Which of the following sets is computed by the above query?(A) Names of students who have got an A grade in all courses taught by Korth(B) Names of students who have got an A grade in all courses(C) Names of students who have got an A grade in at least one of the courses taught by Korth(D) None of the aboveAnswer: (C)Explanation: The query gives the name of all the students who have scored “A” grade in any of the courses that are taught by Korth.So, C is the correct choice. Please comment below if you find anything wrong in the above post.Quiz of this Question" }, { "code": null, "e": 25551, "s": 25538, "text": "GATE-CS-2003" }, { "code": null, "e": 25569, "s": 25551, "text": "GATE-GATE-CS-2003" }, { "code": null, "e": 25574, "s": 25569, "text": "GATE" }, { "code": null, "e": 25672, "s": 25574, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25706, "s": 25672, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 25748, "s": 25706, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25782, "s": 25748, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 25815, "s": 25782, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25849, "s": 25815, "text": "GATE | GATE CS 2011 | Question 65" }, { "code": null, "e": 25883, "s": 25849, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 25925, "s": 25883, "text": "GATE | GATE CS 2021 | Set 1 | Question 47" }, { "code": null, "e": 25958, "s": 25925, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 26000, "s": 25958, "text": "GATE | GATE-CS-2017 (Set 2) | Question 42" } ]
Servlets - File Uploading
A Servlet can be used with an HTML form tag to allow users to upload files to the server. An uploaded file could be a text file or image file or any document. The following HTM code below creates an uploader form. Following are the important points to be noted down − The form method attribute should be set to POST method and GET method can not be used The form method attribute should be set to POST method and GET method can not be used The form enctype attribute should be set to multipart/form-data. The form enctype attribute should be set to multipart/form-data. The form action attribute should be set to a servlet file which would handle file uploading at backend server. Following example is using UploadServlet servlet to upload file. The form action attribute should be set to a servlet file which would handle file uploading at backend server. Following example is using UploadServlet servlet to upload file. To upload a single file you should use a single <input .../> tag with attribute type="file". To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them. To upload a single file you should use a single <input .../> tag with attribute type="file". To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them. <html> <head> <title>File Uploading Form</title> </head> <body> <h3>File Upload:</h3> Select a file to upload: <br /> <form action = "UploadServlet" method = "post" enctype = "multipart/form-data"> <input type = "file" name = "file" size = "50" /> <br /> <input type = "submit" value = "Upload File" /> </form> </body> </html> This will display following result which would allow to select a file from local PC and when user would click at "Upload File", form would be submitted along with the selected fil − File Upload: Select a file to upload: NOTE: This is just dummy form and would not work. Following is the servlet UploadServlet which would take care of accepting uploaded file and to store it in directory <Tomcat-installation-directory>/webapps/data. This directory name could also be added using an external configuration such as a context-param element in web.xml as follows − <web-app> .... <context-param> <description>Location to store uploaded file</description> <param-name>file-upload</param-name> <param-value> c:\apache-tomcat-5.5.29\webapps\data\ </param-value> </context-param> .... </web-app> Following is the source code for UploadServlet which can handle multiple file uploading at a time. Before proceeding you have make sure the followings − Following example depends on FileUpload, so make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from https://commons.apache.org/fileupload/. Following example depends on FileUpload, so make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from https://commons.apache.org/fileupload/. FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from https://commons.apache.org/io/. FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from https://commons.apache.org/io/. While testing following example, you should upload a file which has less size than maxFileSize otherwise file would not be uploaded. While testing following example, you should upload a file which has less size than maxFileSize otherwise file would not be uploaded. Make sure you have created directories c:\temp and c:\apache-tomcat8.0.28\webapps\data well in advance. Make sure you have created directories c:\temp and c:\apache-tomcat8.0.28\webapps\data well in advance. // Import required java libraries import java.io.*; import java.util.*; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.output.*; public class UploadServlet extends HttpServlet { private boolean isMultipart; private String filePath; private int maxFileSize = 50 * 1024; private int maxMemSize = 4 * 1024; private File file ; public void init( ){ // Get the file location where it would be stored. filePath = getServletContext().getInitParameter("file-upload"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter( ); if( !isMultipart ) { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax( maxFileSize ); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while ( i.hasNext () ) { FileItem fi = (FileItem)i.next(); if ( !fi.isFormField () ) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if( fileName.lastIndexOf("\\") >= 0 ) { file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ; } else { file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ; } fi.write( file ) ; out.println("Uploaded Filename: " + fileName + "<br>"); } } out.println("</body>"); out.println("</html>"); } catch(Exception ex) { System.out.println(ex); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { throw new ServletException("GET method used with " + getClass( ).getName( )+": POST method required."); } } } Compile above servlet UploadServlet and create required entry in web.xml file as follows. <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/UploadServlet</url-pattern> </servlet-mapping> Now try to upload files using the HTML form which you created above. When you would try http://localhost:8080/UploadFile.htm, it would display following result which would help you uploading any file from your local machine. File Upload: Select a file to upload: Select a file to upload: If your servlet script works fine, your file should be uploaded in c:\apache-tomcat8.0.28\webapps\data\ directory. 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 31 Lectures 12.5 hours Uplatz 38 Lectures 4.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2344, "s": 2185, "text": "A Servlet can be used with an HTML form tag to allow users to upload files to the server. An uploaded file could be a text file or image file or any document." }, { "code": null, "e": 2453, "s": 2344, "text": "The following HTM code below creates an uploader form. Following are the important points to be noted down −" }, { "code": null, "e": 2539, "s": 2453, "text": "The form method attribute should be set to POST method and GET method can not be used" }, { "code": null, "e": 2625, "s": 2539, "text": "The form method attribute should be set to POST method and GET method can not be used" }, { "code": null, "e": 2690, "s": 2625, "text": "The form enctype attribute should be set to multipart/form-data." }, { "code": null, "e": 2755, "s": 2690, "text": "The form enctype attribute should be set to multipart/form-data." }, { "code": null, "e": 2931, "s": 2755, "text": "The form action attribute should be set to a servlet file which would handle file uploading at backend server. Following example is using UploadServlet servlet to upload file." }, { "code": null, "e": 3107, "s": 2931, "text": "The form action attribute should be set to a servlet file which would handle file uploading at backend server. Following example is using UploadServlet servlet to upload file." }, { "code": null, "e": 3372, "s": 3107, "text": "To upload a single file you should use a single <input .../> tag with attribute type=\"file\". To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them." }, { "code": null, "e": 3637, "s": 3372, "text": "To upload a single file you should use a single <input .../> tag with attribute type=\"file\". To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them." }, { "code": null, "e": 4039, "s": 3637, "text": " \n<html>\n <head>\n <title>File Uploading Form</title>\n </head>\n \n <body>\n <h3>File Upload:</h3>\n Select a file to upload: <br />\n <form action = \"UploadServlet\" method = \"post\" enctype = \"multipart/form-data\">\n <input type = \"file\" name = \"file\" size = \"50\" />\n <br />\n <input type = \"submit\" value = \"Upload File\" />\n </form>\n </body>\n</html>" }, { "code": null, "e": 4221, "s": 4039, "text": "This will display following result which would allow to select a file from local PC and when user would click at \"Upload File\", form would be submitted along with the selected fil −" }, { "code": null, "e": 4323, "s": 4221, "text": " \nFile Upload: \nSelect a file to upload: \n \n \n \n \nNOTE: This is just dummy form and would not work.\n" }, { "code": null, "e": 4614, "s": 4323, "text": "Following is the servlet UploadServlet which would take care of accepting uploaded file and to store it in directory <Tomcat-installation-directory>/webapps/data. This directory name could also be added using an external configuration such as a context-param element in web.xml as follows −" }, { "code": null, "e": 4892, "s": 4614, "text": " \n<web-app>\n ....\n <context-param> \n <description>Location to store uploaded file</description> \n <param-name>file-upload</param-name> \n <param-value>\n c:\\apache-tomcat-5.5.29\\webapps\\data\\\n </param-value> \n </context-param>\n ....\n</web-app>" }, { "code": null, "e": 5045, "s": 4892, "text": "Following is the source code for UploadServlet which can handle multiple file uploading at a time. Before proceeding you have make sure the followings −" }, { "code": null, "e": 5246, "s": 5045, "text": "Following example depends on FileUpload, so make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from https://commons.apache.org/fileupload/." }, { "code": null, "e": 5447, "s": 5246, "text": "Following example depends on FileUpload, so make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. You can download it from https://commons.apache.org/fileupload/." }, { "code": null, "e": 5625, "s": 5447, "text": "FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from https://commons.apache.org/io/." }, { "code": null, "e": 5803, "s": 5625, "text": "FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from https://commons.apache.org/io/." }, { "code": null, "e": 5936, "s": 5803, "text": "While testing following example, you should upload a file which has less size than maxFileSize otherwise file would not be uploaded." }, { "code": null, "e": 6069, "s": 5936, "text": "While testing following example, you should upload a file which has less size than maxFileSize otherwise file would not be uploaded." }, { "code": null, "e": 6174, "s": 6069, "text": "Make sure you have created directories c:\\temp and c:\\apache-tomcat8.0.28\\webapps\\data well in advance. " }, { "code": null, "e": 6279, "s": 6174, "text": "Make sure you have created directories c:\\temp and c:\\apache-tomcat8.0.28\\webapps\\data well in advance. " }, { "code": null, "e": 10136, "s": 6279, "text": "// Import required java libraries\nimport java.io.*;\nimport java.util.*;\n \nimport javax.servlet.ServletConfig;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n \nimport org.apache.commons.fileupload.FileItem;\nimport org.apache.commons.fileupload.FileUploadException;\nimport org.apache.commons.fileupload.disk.DiskFileItemFactory;\nimport org.apache.commons.fileupload.servlet.ServletFileUpload;\nimport org.apache.commons.io.output.*;\n\npublic class UploadServlet extends HttpServlet {\n \n private boolean isMultipart;\n private String filePath;\n private int maxFileSize = 50 * 1024;\n private int maxMemSize = 4 * 1024;\n private File file ;\n\n public void init( ){\n // Get the file location where it would be stored.\n filePath = getServletContext().getInitParameter(\"file-upload\"); \n }\n \n public void doPost(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, java.io.IOException {\n \n // Check that we have a file upload request\n isMultipart = ServletFileUpload.isMultipartContent(request);\n response.setContentType(\"text/html\");\n java.io.PrintWriter out = response.getWriter( );\n \n if( !isMultipart ) {\n out.println(\"<html>\");\n out.println(\"<head>\");\n out.println(\"<title>Servlet upload</title>\"); \n out.println(\"</head>\");\n out.println(\"<body>\");\n out.println(\"<p>No file uploaded</p>\"); \n out.println(\"</body>\");\n out.println(\"</html>\");\n return;\n }\n \n DiskFileItemFactory factory = new DiskFileItemFactory();\n \n // maximum size that will be stored in memory\n factory.setSizeThreshold(maxMemSize);\n \n // Location to save data that is larger than maxMemSize.\n factory.setRepository(new File(\"c:\\\\temp\"));\n\n // Create a new file upload handler\n ServletFileUpload upload = new ServletFileUpload(factory);\n \n // maximum file size to be uploaded.\n upload.setSizeMax( maxFileSize );\n\n try { \n // Parse the request to get file items.\n List fileItems = upload.parseRequest(request);\n\t\n // Process the uploaded file items\n Iterator i = fileItems.iterator();\n\n out.println(\"<html>\");\n out.println(\"<head>\");\n out.println(\"<title>Servlet upload</title>\"); \n out.println(\"</head>\");\n out.println(\"<body>\");\n \n while ( i.hasNext () ) {\n FileItem fi = (FileItem)i.next();\n if ( !fi.isFormField () ) {\n // Get the uploaded file parameters\n String fieldName = fi.getFieldName();\n String fileName = fi.getName();\n String contentType = fi.getContentType();\n boolean isInMemory = fi.isInMemory();\n long sizeInBytes = fi.getSize();\n \n // Write the file\n if( fileName.lastIndexOf(\"\\\\\") >= 0 ) {\n file = new File( filePath + fileName.substring( fileName.lastIndexOf(\"\\\\\"))) ;\n } else {\n file = new File( filePath + fileName.substring(fileName.lastIndexOf(\"\\\\\")+1)) ;\n }\n fi.write( file ) ;\n out.println(\"Uploaded Filename: \" + fileName + \"<br>\");\n }\n }\n out.println(\"</body>\");\n out.println(\"</html>\");\n } catch(Exception ex) {\n System.out.println(ex);\n }\n }\n \n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, java.io.IOException {\n\n throw new ServletException(\"GET method used with \" +\n getClass( ).getName( )+\": POST method required.\");\n }\n }\n}" }, { "code": null, "e": 10226, "s": 10136, "text": "Compile above servlet UploadServlet and create required entry in web.xml file as follows." }, { "code": null, "e": 10472, "s": 10226, "text": " \n<servlet>\n <servlet-name>UploadServlet</servlet-name>\n <servlet-class>UploadServlet</servlet-class>\n</servlet>\n\n<servlet-mapping>\n <servlet-name>UploadServlet</servlet-name>\n <url-pattern>/UploadServlet</url-pattern>\n</servlet-mapping>" }, { "code": null, "e": 10697, "s": 10472, "text": "Now try to upload files using the HTML form which you created above. When you would try http://localhost:8080/UploadFile.htm, it would display following result which would help you uploading any file from your local machine." }, { "code": null, "e": 10743, "s": 10697, "text": " \nFile Upload: \nSelect a file to upload:\n \n \n" }, { "code": null, "e": 10768, "s": 10743, "text": "Select a file to upload:" }, { "code": null, "e": 10883, "s": 10768, "text": "If your servlet script works fine, your file should be uploaded in c:\\apache-tomcat8.0.28\\webapps\\data\\ directory." }, { "code": null, "e": 10918, "s": 10883, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10932, "s": 10918, "text": " Karthikeya T" }, { "code": null, "e": 10967, "s": 10932, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 10983, "s": 10967, "text": " TELCOMA Global" }, { "code": null, "e": 11016, "s": 10983, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 11032, "s": 11016, "text": " TELCOMA Global" }, { "code": null, "e": 11068, "s": 11032, "text": "\n 31 Lectures \n 12.5 hours \n" }, { "code": null, "e": 11076, "s": 11068, "text": " Uplatz" }, { "code": null, "e": 11111, "s": 11076, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 11129, "s": 11111, "text": " Packt Publishing" }, { "code": null, "e": 11136, "s": 11129, "text": " Print" }, { "code": null, "e": 11147, "s": 11136, "text": " Add Notes" } ]
Dockerizing Airflow. Apache Airflow on Docker for local... | by Shah Newaz Khan | Towards Data Science
Airflow is the de facto ETL orchestration tool in most data engineers tool box. It provides an intuitive web interface for a powerful backend to schedule and manage dependencies for your ETL workflows. In my day to day work-flow, I use it to maintain and curate a data lake built on top of AWS S3. Nodes in my Airflow DAGs include multi-node EMR Apache Spark and Fargate clusters that aggregate, prune and produce para-data from the data lake. Since these work-flows are executed on distributed clusters (20+ nodes) and have heavy dependencies (output from one ETL is fed in as input to the next) it made sense to orchestrate them using Airflow. However it did not make sense to have a central Airflow deployment as I will be the only one using it. I therefore chose to Dockerize Airflow so that I could spin up a container and easily run these work-flows without having to worry about the Airflow deployment. In this post I will go over how I achieved this along with some brief explanation of design decisions along the way. In Airflow ETL work-flows are defined as directed acyclic graphs (Airflow DAG) where each node is a self-contained ETL with each downstream node being dependent on successful completion of the upstream node. Airflow has three deployment components: Webserver ( Flask backend used to trigger and monitor DAGs) Scheduler ( A daemon process to schedule and run the DAG executers ) Database ( A presistance layer for DAG & DAG instance definitions ) It is quick and easy to get started with airflow: # airflow needs a home, ~/airflow is the default,# but you can lay foundation somewhere else if you prefer# (optional)export AIRFLOW_HOME=~/airflow# install from pypi using pippip install apache-airflow# initialize the databaseairflow initdb# start the web server, default port is 8080airflow webserver -p 8080 Upon running these commands, Airflow will create the $AIRFLOW_HOME folder and lay an airflow.cfgfile with defaults that get you going fast. You can inspect the file either in $AIRFLOW_HOME/airflow.cfg, or through the UI in the Admin->Configuration menu. The PID file for the webserver will be stored in $AIRFLOW_HOME/airflow-webserver.pid or in /run/airflow/webserver.pid if started by systemd. Out of the box, Airflow uses a sqlite database, which you should outgrow fairly quickly since no parallelization is possible using this database backend. It works in conjunction with the SequentialExecutor which will only run task instances sequentially. While this is very limiting, it allows you to get up and running quickly and take a tour of the UI and the command line utilities. Here are a few commands that will trigger a few task instances. You should be able to see the status of the jobs change in the example1 DAG as you run the commands below. # run your first task instanceairflow run example_bash_operator runme_0 2018-01-01# run a backfill over 2 daysairflow backfill example_bash_operator -s 2018-01-01 -e 2018-01-02 A container’s main running process is the ENTRYPOINT and/or CMD at the end of the Dockerfile. It is generally recommended that you separate areas of concern by using one service per container. However since we want to have the Airflow Webserver & the Airflow Scheduler processes both running, we will usesupervisord as a process manager. This is a moderately heavy-weight approach that requires you to package supervisord and its configuration in the docker image (or base your image on one that includes supervisord), along with the different applications it manages. Then you start supervisord, which manages your processes for you. First we will need to define supervisord.conf : [supervisord] nodaemon=true[program:scheduler] command=airflow scheduler stdout_logfile=/var/log/supervisor/%(program_name)s.log stderr_logfile=/var/log/supervisor/%(program_name)s.log autorestart=true[program:server] command=airflow webserver -p 8080 stdout_logfile=/var/log/supervisor/%(program_name)s.log stderr_logfile=/var/log/supervisor/%(program_name)s.log autorestart=true Then we will use supervisord as the ENTRYPOINT to our Dockerfile: FROM python:3.6.3# supervisord setup RUN apt-get update && apt-get install -y supervisor COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf# Airflow setup ENV AIRFLOW_HOME=/app/airflowRUN pip install apache-airflow COPY /dags/response_rate_etl.py $AIRFLOW_HOME/dags/RUN airflow initdbEXPOSE 8080CMD ["/usr/bin/supervisord"] Build the Docker image: docker build . -t airflow Run the container: docker run -d -p 8080:8080 --rm \ --name airflow_container \ airflow Launch a DAG: docker exec airflow_container airflow trigger_dag example_bash_operator Monitor DAG run: Open a browser and navigate to http://localhost:8080 to monitor the DAG instance run. That’s all folks, stay tuned to future posts where I will go into defining AWS EMR dags, defining custom Airflow Operators, injecting AWS Credentials and more!
[ { "code": null, "e": 249, "s": 47, "text": "Airflow is the de facto ETL orchestration tool in most data engineers tool box. It provides an intuitive web interface for a powerful backend to schedule and manage dependencies for your ETL workflows." }, { "code": null, "e": 491, "s": 249, "text": "In my day to day work-flow, I use it to maintain and curate a data lake built on top of AWS S3. Nodes in my Airflow DAGs include multi-node EMR Apache Spark and Fargate clusters that aggregate, prune and produce para-data from the data lake." }, { "code": null, "e": 796, "s": 491, "text": "Since these work-flows are executed on distributed clusters (20+ nodes) and have heavy dependencies (output from one ETL is fed in as input to the next) it made sense to orchestrate them using Airflow. However it did not make sense to have a central Airflow deployment as I will be the only one using it." }, { "code": null, "e": 957, "s": 796, "text": "I therefore chose to Dockerize Airflow so that I could spin up a container and easily run these work-flows without having to worry about the Airflow deployment." }, { "code": null, "e": 1074, "s": 957, "text": "In this post I will go over how I achieved this along with some brief explanation of design decisions along the way." }, { "code": null, "e": 1282, "s": 1074, "text": "In Airflow ETL work-flows are defined as directed acyclic graphs (Airflow DAG) where each node is a self-contained ETL with each downstream node being dependent on successful completion of the upstream node." }, { "code": null, "e": 1323, "s": 1282, "text": "Airflow has three deployment components:" }, { "code": null, "e": 1383, "s": 1323, "text": "Webserver ( Flask backend used to trigger and monitor DAGs)" }, { "code": null, "e": 1452, "s": 1383, "text": "Scheduler ( A daemon process to schedule and run the DAG executers )" }, { "code": null, "e": 1520, "s": 1452, "text": "Database ( A presistance layer for DAG & DAG instance definitions )" }, { "code": null, "e": 1570, "s": 1520, "text": "It is quick and easy to get started with airflow:" }, { "code": null, "e": 1881, "s": 1570, "text": "# airflow needs a home, ~/airflow is the default,# but you can lay foundation somewhere else if you prefer# (optional)export AIRFLOW_HOME=~/airflow# install from pypi using pippip install apache-airflow# initialize the databaseairflow initdb# start the web server, default port is 8080airflow webserver -p 8080" }, { "code": null, "e": 2276, "s": 1881, "text": "Upon running these commands, Airflow will create the $AIRFLOW_HOME folder and lay an airflow.cfgfile with defaults that get you going fast. You can inspect the file either in $AIRFLOW_HOME/airflow.cfg, or through the UI in the Admin->Configuration menu. The PID file for the webserver will be stored in $AIRFLOW_HOME/airflow-webserver.pid or in /run/airflow/webserver.pid if started by systemd." }, { "code": null, "e": 2662, "s": 2276, "text": "Out of the box, Airflow uses a sqlite database, which you should outgrow fairly quickly since no parallelization is possible using this database backend. It works in conjunction with the SequentialExecutor which will only run task instances sequentially. While this is very limiting, it allows you to get up and running quickly and take a tour of the UI and the command line utilities." }, { "code": null, "e": 2833, "s": 2662, "text": "Here are a few commands that will trigger a few task instances. You should be able to see the status of the jobs change in the example1 DAG as you run the commands below." }, { "code": null, "e": 3010, "s": 2833, "text": "# run your first task instanceairflow run example_bash_operator runme_0 2018-01-01# run a backfill over 2 daysairflow backfill example_bash_operator -s 2018-01-01 -e 2018-01-02" }, { "code": null, "e": 3203, "s": 3010, "text": "A container’s main running process is the ENTRYPOINT and/or CMD at the end of the Dockerfile. It is generally recommended that you separate areas of concern by using one service per container." }, { "code": null, "e": 3348, "s": 3203, "text": "However since we want to have the Airflow Webserver & the Airflow Scheduler processes both running, we will usesupervisord as a process manager." }, { "code": null, "e": 3579, "s": 3348, "text": "This is a moderately heavy-weight approach that requires you to package supervisord and its configuration in the docker image (or base your image on one that includes supervisord), along with the different applications it manages." }, { "code": null, "e": 3693, "s": 3579, "text": "Then you start supervisord, which manages your processes for you. First we will need to define supervisord.conf :" }, { "code": null, "e": 4272, "s": 3693, "text": "[supervisord] nodaemon=true[program:scheduler] command=airflow scheduler stdout_logfile=/var/log/supervisor/%(program_name)s.log stderr_logfile=/var/log/supervisor/%(program_name)s.log autorestart=true[program:server] command=airflow webserver -p 8080 stdout_logfile=/var/log/supervisor/%(program_name)s.log stderr_logfile=/var/log/supervisor/%(program_name)s.log autorestart=true" }, { "code": null, "e": 4338, "s": 4272, "text": "Then we will use supervisord as the ENTRYPOINT to our Dockerfile:" }, { "code": null, "e": 4761, "s": 4338, "text": "FROM python:3.6.3# supervisord setup RUN apt-get update && apt-get install -y supervisor COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf# Airflow setup ENV AIRFLOW_HOME=/app/airflowRUN pip install apache-airflow COPY /dags/response_rate_etl.py $AIRFLOW_HOME/dags/RUN airflow initdbEXPOSE 8080CMD [\"/usr/bin/supervisord\"]" }, { "code": null, "e": 4785, "s": 4761, "text": "Build the Docker image:" }, { "code": null, "e": 4811, "s": 4785, "text": "docker build . -t airflow" }, { "code": null, "e": 4830, "s": 4811, "text": "Run the container:" }, { "code": null, "e": 4903, "s": 4830, "text": "docker run -d -p 8080:8080 --rm \\ --name airflow_container \\ airflow" }, { "code": null, "e": 4917, "s": 4903, "text": "Launch a DAG:" }, { "code": null, "e": 4989, "s": 4917, "text": "docker exec airflow_container airflow trigger_dag example_bash_operator" }, { "code": null, "e": 5006, "s": 4989, "text": "Monitor DAG run:" }, { "code": null, "e": 5092, "s": 5006, "text": "Open a browser and navigate to http://localhost:8080 to monitor the DAG instance run." } ]
Create a GUI to extract Lyrics from song Using Python - GeeksforGeeks
08 Dec, 2021 In this article, we are going to write a python script to extract lyrics from the song and bind with its GUI application. We will use lyrics-extractor to get lyrics of a song just by passing in the song name, it extracts and returns the song’s title and song lyrics from various websites. Before starting, install the lyrics-extractor module. Run this command into your terminal. pip install lyrics-extractor Need an API Key and Engine ID of Google Custom Search JSON API. Engine ID Create a Custom Search Engine to get your Engine ID here. We have to create our own Programmable Search Engine (Google Custom Search Engine) and add Link to fetch lyrics. Programmable Search Engine is based on Google’s core search technology. It is a search engine for your website and has a task to find information as the user choose. Choose any link of one to get your search engine: https://genius.com/ http://www.lyricsted.com/ http://www.lyricsbell.com/ https://www.glamsham.com/ http://www.lyricsoff.com/ http://www.lyricsmint.com/ JSON API : The custom search JSON API is able to retrieve and display search result from Programmable Search Engine. To use the custom search JSON API we have to create Programmable Search Engine. Visit here to get your API key. Approach: Import the modules. from lyrics_extractor import SongLyrics Pass the Google Custom Search JSON API key and Engine ID into SongLyrics(). extract_lyrics = SongLyrics(Your_API_KEY, GCS_ENGINE_ID) Get the lyrics by passing the song name as a parameter to extract_lyrics.get_lyrics() method. extract_lyrics.get_lyrics("Shape of You") Below is the implementation. Python3 # importing modulesfrom lyrics_extractor import SongLyrics # pass the GCS_API_KEY, GCS_ENGINE_IDextract_lyrics = SongLyrics("AIzaSewfsdfsdfOq0oTixw","frewrewrfsac") extract_lyrics.get_lyrics("Tujhse Naraz Nahi Zindagi Lyrics") Output: Note: Enter your own API key and engine id otherwise it will generate an error. Extract lyrics Application with Tkinter: Python3 # import modulesfrom tkinter import *from lyrics_extractor import SongLyrics # user defined functiondef get_lyrics(): extract_lyrics = SongLyrics( "Aerwerwefwdssdj-nvN3Oq0oTixw", "werwerewcxzcsda") temp = extract_lyrics.get_lyrics(str(e.get())) res = temp['lyrics'] result.set(res) # object of tkinter# and background set to light greymaster = Tk()master.configure(bg='light grey') # Variable Classes in tkinterresult = StringVar() # Creating label for each information# name using widget LabelLabel(master, text="Enter Song name : ", bg="light grey").grid(row=0, sticky=W) Label(master, text="Result :", bg="light grey").grid(row=3, sticky=W) # Creating label for class variable# name using widget EntryLabel(master, text="", textvariable=result, bg="light grey").grid(row=3, column=1, sticky=W) e = Entry(master, width=50)e.grid(row=0, column=1) # creating a button using the widgetb = Button(master, text="Show", command=get_lyrics, bg="Blue") b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5,) mainloop() Note: Enter your own API key and engine id otherwise it will generate an error. Output: avtarkumar719 sweetyty Python Tkinter-exercises Python-tkinter python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Python | Get dictionary keys as a list Bar Plot in Matplotlib Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method loops in python Python - Call function from another file Ways to filter Pandas DataFrame by column values Python | Convert set into a list Python program to find number of days between two given dates
[ { "code": null, "e": 23927, "s": 23899, "text": "\n08 Dec, 2021" }, { "code": null, "e": 24307, "s": 23927, "text": "In this article, we are going to write a python script to extract lyrics from the song and bind with its GUI application. We will use lyrics-extractor to get lyrics of a song just by passing in the song name, it extracts and returns the song’s title and song lyrics from various websites. Before starting, install the lyrics-extractor module. Run this command into your terminal." }, { "code": null, "e": 24336, "s": 24307, "text": "pip install lyrics-extractor" }, { "code": null, "e": 24400, "s": 24336, "text": "Need an API Key and Engine ID of Google Custom Search JSON API." }, { "code": null, "e": 24411, "s": 24400, "text": "Engine ID " }, { "code": null, "e": 24469, "s": 24411, "text": "Create a Custom Search Engine to get your Engine ID here." }, { "code": null, "e": 24582, "s": 24469, "text": "We have to create our own Programmable Search Engine (Google Custom Search Engine) and add Link to fetch lyrics." }, { "code": null, "e": 24654, "s": 24582, "text": "Programmable Search Engine is based on Google’s core search technology." }, { "code": null, "e": 24748, "s": 24654, "text": "It is a search engine for your website and has a task to find information as the user choose." }, { "code": null, "e": 24798, "s": 24748, "text": "Choose any link of one to get your search engine:" }, { "code": null, "e": 24950, "s": 24798, "text": "https://genius.com/\nhttp://www.lyricsted.com/\nhttp://www.lyricsbell.com/\nhttps://www.glamsham.com/\nhttp://www.lyricsoff.com/\nhttp://www.lyricsmint.com/" }, { "code": null, "e": 24961, "s": 24950, "text": "JSON API :" }, { "code": null, "e": 25067, "s": 24961, "text": "The custom search JSON API is able to retrieve and display search result from Programmable Search Engine." }, { "code": null, "e": 25147, "s": 25067, "text": "To use the custom search JSON API we have to create Programmable Search Engine." }, { "code": null, "e": 25179, "s": 25147, "text": "Visit here to get your API key." }, { "code": null, "e": 25189, "s": 25179, "text": "Approach:" }, { "code": null, "e": 25209, "s": 25189, "text": "Import the modules." }, { "code": null, "e": 25250, "s": 25209, "text": "from lyrics_extractor import SongLyrics " }, { "code": null, "e": 25326, "s": 25250, "text": "Pass the Google Custom Search JSON API key and Engine ID into SongLyrics()." }, { "code": null, "e": 25383, "s": 25326, "text": "extract_lyrics = SongLyrics(Your_API_KEY, GCS_ENGINE_ID)" }, { "code": null, "e": 25477, "s": 25383, "text": "Get the lyrics by passing the song name as a parameter to extract_lyrics.get_lyrics() method." }, { "code": null, "e": 25519, "s": 25477, "text": "extract_lyrics.get_lyrics(\"Shape of You\")" }, { "code": null, "e": 25548, "s": 25519, "text": "Below is the implementation." }, { "code": null, "e": 25556, "s": 25548, "text": "Python3" }, { "code": "# importing modulesfrom lyrics_extractor import SongLyrics # pass the GCS_API_KEY, GCS_ENGINE_IDextract_lyrics = SongLyrics(\"AIzaSewfsdfsdfOq0oTixw\",\"frewrewrfsac\") extract_lyrics.get_lyrics(\"Tujhse Naraz Nahi Zindagi Lyrics\")", "e": 25783, "s": 25556, "text": null }, { "code": null, "e": 25791, "s": 25783, "text": "Output:" }, { "code": null, "e": 25871, "s": 25791, "text": "Note: Enter your own API key and engine id otherwise it will generate an error." }, { "code": null, "e": 25913, "s": 25871, "text": "Extract lyrics Application with Tkinter: " }, { "code": null, "e": 25921, "s": 25913, "text": "Python3" }, { "code": "# import modulesfrom tkinter import *from lyrics_extractor import SongLyrics # user defined functiondef get_lyrics(): extract_lyrics = SongLyrics( \"Aerwerwefwdssdj-nvN3Oq0oTixw\", \"werwerewcxzcsda\") temp = extract_lyrics.get_lyrics(str(e.get())) res = temp['lyrics'] result.set(res) # object of tkinter# and background set to light greymaster = Tk()master.configure(bg='light grey') # Variable Classes in tkinterresult = StringVar() # Creating label for each information# name using widget LabelLabel(master, text=\"Enter Song name : \", bg=\"light grey\").grid(row=0, sticky=W) Label(master, text=\"Result :\", bg=\"light grey\").grid(row=3, sticky=W) # Creating label for class variable# name using widget EntryLabel(master, text=\"\", textvariable=result, bg=\"light grey\").grid(row=3, column=1, sticky=W) e = Entry(master, width=50)e.grid(row=0, column=1) # creating a button using the widgetb = Button(master, text=\"Show\", command=get_lyrics, bg=\"Blue\") b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5,) mainloop()", "e": 27005, "s": 25921, "text": null }, { "code": null, "e": 27085, "s": 27005, "text": "Note: Enter your own API key and engine id otherwise it will generate an error." }, { "code": null, "e": 27093, "s": 27085, "text": "Output:" }, { "code": null, "e": 27107, "s": 27093, "text": "avtarkumar719" }, { "code": null, "e": 27116, "s": 27107, "text": "sweetyty" }, { "code": null, "e": 27141, "s": 27116, "text": "Python Tkinter-exercises" }, { "code": null, "e": 27156, "s": 27141, "text": "Python-tkinter" }, { "code": null, "e": 27171, "s": 27156, "text": "python-utility" }, { "code": null, "e": 27178, "s": 27171, "text": "Python" }, { "code": null, "e": 27276, "s": 27178, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27285, "s": 27276, "text": "Comments" }, { "code": null, "e": 27298, "s": 27285, "text": "Old Comments" }, { "code": null, "e": 27334, "s": 27298, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 27373, "s": 27334, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27396, "s": 27373, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 27447, "s": 27396, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 27479, "s": 27447, "text": "Python Dictionary keys() method" }, { "code": null, "e": 27495, "s": 27479, "text": "loops in python" }, { "code": null, "e": 27536, "s": 27495, "text": "Python - Call function from another file" }, { "code": null, "e": 27585, "s": 27536, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 27618, "s": 27585, "text": "Python | Convert set into a list" } ]
Where should I put <script> tags in HTML markup?
The JavaScript code should be inserted between <script> and </script> tags in HTML. You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags. The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. The script tag takes two important attributes − Language − This attribute specifies what scripting language you are using. Typically, its value will be JavaScript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute. Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript". Let us take a simple example to print out "Hello World". We added an optional HTML comment that surrounds our JavaScript code. This is to save our code from a browser that does not support JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code. Next, we call a function document.write which writes a string into our HTML document. This function can be used to write text, HTML, or both. Take a look at the following code. <html> <body> <script language="javascript" type="text/javascript"> <!-- document.write("Hello World!") //--> </script> </body> </html> Hello World!
[ { "code": null, "e": 1317, "s": 1062, "text": "The JavaScript code should be inserted between <script> and </script> tags in HTML. You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags." }, { "code": null, "e": 1428, "s": 1317, "text": "The <script> tag alerts the browser program to start interpreting all the text between these tags as a script." }, { "code": null, "e": 1476, "s": 1428, "text": "The script tag takes two important attributes −" }, { "code": null, "e": 1695, "s": 1476, "text": "Language − This attribute specifies what scripting language you are using. Typically, its value will be JavaScript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute." }, { "code": null, "e": 1836, "s": 1695, "text": "Type − This attribute is what is now recommended to indicate the scripting language in use and its value should be set to \"text/javascript\"." }, { "code": null, "e": 2310, "s": 1836, "text": " Let us take a simple example to print out \"Hello World\". We added an optional HTML comment that surrounds our JavaScript code. This is to save our code from a browser that does not support JavaScript. The comment ends with a \"//-->\". Here \"//\" signifies a comment in JavaScript, so we add that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code. Next, we call a function document.write which writes a string into our HTML document." }, { "code": null, "e": 2402, "s": 2310, "text": " This function can be used to write text, HTML, or both. Take a look at the following code." }, { "code": null, "e": 2586, "s": 2402, "text": "<html>\n <body>\n <script language=\"javascript\" type=\"text/javascript\">\n <!--\n document.write(\"Hello World!\")\n //-->\n </script>\n </body>\n</html>" }, { "code": null, "e": 2599, "s": 2586, "text": "Hello World!" } ]
How do you find the length of an array in C#?
To find the length of an array, use the Array.Length() method. Let us see an example − Live Demo using System; class Program { static void Main(){ int[] arr = new int[10]; // finding length int arrLength = arr.Length; Console.WriteLine("Length of the array: "+arrLength); } } Length of the array: 10 Above, we have an array − int[] arr = new int[10]; Now to find the length, we used the Length() method − int arrLength = arr.Length;
[ { "code": null, "e": 1125, "s": 1062, "text": "To find the length of an array, use the Array.Length() method." }, { "code": null, "e": 1149, "s": 1125, "text": "Let us see an example −" }, { "code": null, "e": 1160, "s": 1149, "text": " Live Demo" }, { "code": null, "e": 1369, "s": 1160, "text": "using System;\nclass Program {\n static void Main(){\n int[] arr = new int[10];\n // finding length\n int arrLength = arr.Length;\n Console.WriteLine(\"Length of the array: \"+arrLength);\n }\n}" }, { "code": null, "e": 1393, "s": 1369, "text": "Length of the array: 10" }, { "code": null, "e": 1419, "s": 1393, "text": "Above, we have an array −" }, { "code": null, "e": 1444, "s": 1419, "text": "int[] arr = new int[10];" }, { "code": null, "e": 1498, "s": 1444, "text": "Now to find the length, we used the Length() method −" }, { "code": null, "e": 1526, "s": 1498, "text": "int arrLength = arr.Length;" } ]
jQuery - Widget accordion
The Widget accordion function can be used with widgets in JqueryUI.Accordion is same like as Tabs,When user click headers to expand content that is broken into logical sections. Here is the simple syntax to use Accordion − $(function() { $( "#accordion" ).accordion(); }); Following is a simple example showing the usage of Accordion − <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Accordion - Default functionality</title> <link rel = "stylesheet" href = "//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"> </script> <script> $(function() { $( "#accordion" ).accordion(); }); </script> </head> <body> <div id = "accordion"> <h3>Android</h3> <div> <p> Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. </p> </div> <h3>CSS</h3> <div> <p> CSS is the acronym for "Cascading Style Sheet". This tutorial covers both the versions CSS1,CSS2 and CSS3, and gives a complete understanding of CSS, starting from its basics to advanced concepts. </p> </div> <h3>AngularJS</h3> <div> <p> AngularJS is a very powerful JavaScript library. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0. </p> <ul> <li>List item one</li> <li>List item two</li> <li>List item three</li> </ul> </div> <h3>PHP</h3> <div> <p> The PHP Hypertext Preprocessor (PHP) is a programming language hat allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications. This tutorial helps you to build your base with PHP. </p> <p> Before proceeding with this tutorial you should have at least basic understanding of computer programming, Internet, Database, and MySQL etc is very helpful. </p> </div> </div> </body> </html> This will produce following result − Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. CSS is the acronym for "Cascading Style Sheet". This tutorial covers both the versions CSS1,CSS2 and CSS3, and gives a complete understanding of CSS, starting from its basics to advanced concepts. AngularJS is a very powerful JavaScript library. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0. List item one List item two List item three The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications. This tutorial helps you to build your base with PHP. Before proceeding with this tutorial you should have at least basic understanding of computer programming, Internet, Database, and MySQL etc is very helpful. 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2500, "s": 2322, "text": "The Widget accordion function can be used with widgets in JqueryUI.Accordion is same like as Tabs,When user click headers to expand content that is broken into logical sections." }, { "code": null, "e": 2545, "s": 2500, "text": "Here is the simple syntax to use Accordion −" }, { "code": null, "e": 2599, "s": 2545, "text": "$(function() {\n $( \"#accordion\" ).accordion();\n});\n" }, { "code": null, "e": 2662, "s": 2599, "text": "Following is a simple example showing the usage of Accordion −" }, { "code": null, "e": 5514, "s": 2662, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Accordion - Default functionality</title>\n\t\t\n <link rel = \"stylesheet\" \n href = \"//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css\">\n\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js\">\n </script>\n\t\t\n \n <script>\n $(function() {\n $( \"#accordion\" ).accordion();\n });\n </script>\n </head>\n\t\n <body>\n <div id = \"accordion\">\n <h3>Android</h3>\n\t\t\t\n <div>\n <p>\n Android is an open source and Linux-based operating system for\n mobile devices such as smartphones and tablet computers. \n Android was developed by the Open Handset Alliance, led by \n Google, and other companies.\n </p>\n </div>\n\t\t\t\n <h3>CSS</h3>\n\t\t\t\n <div>\n <p>\n CSS is the acronym for \"Cascading Style Sheet\". This \n tutorial covers both the versions CSS1,CSS2 and CSS3, \n and gives a complete understanding of CSS,\n starting from its basics to advanced concepts.\n </p>\n </div>\n\t\t\t\n <h3>AngularJS</h3>\n\t\t\t\n <div>\n <p>\n AngularJS is a very powerful JavaScript library. It is used in \n Single Page Application (SPA) projects. It extends HTML DOM\n with additional attributes and makes it more responsive to \n user actions. AngularJS is open source, completely free, \n and used by thousands of developers around the world.\n It is licensed under the Apache license version 2.0.\n </p>\n\t\t\t\t\n <ul>\n <li>List item one</li>\n <li>List item two</li>\n <li>List item three</li>\n </ul>\n\t\t\t\t\n </div>\n\t\t\t\n <h3>PHP</h3>\n\t\t\t\n <div>\n <p>\n The PHP Hypertext Preprocessor (PHP) is a programming language \n hat allows web developers to create dynamic content that\n interacts with databases. PHP is basically used for developing \n web based software applications. This tutorial helps you to \n build your base with PHP.\n </p>\n\t\t\t\t\n <p>\n Before proceeding with this tutorial you should have at least basic \n understanding of computer programming, Internet, Database, and \n MySQL etc is very helpful.\n </p>\n\t\t\t\t\n </div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 5551, "s": 5514, "text": "This will produce following result −" }, { "code": null, "e": 5768, "s": 5551, "text": "\n Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies.\n " }, { "code": null, "e": 5974, "s": 5768, "text": "\n CSS is the acronym for \"Cascading Style Sheet\". This tutorial covers both the versions CSS1,CSS2 and CSS3, and gives a complete understanding of CSS, starting from its basics to advanced concepts.\n " }, { "code": null, "e": 6330, "s": 5974, "text": "\n AngularJS is a very powerful JavaScript library. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0.\n " }, { "code": null, "e": 6344, "s": 6330, "text": "List item one" }, { "code": null, "e": 6358, "s": 6344, "text": "List item two" }, { "code": null, "e": 6374, "s": 6358, "text": "List item three" }, { "code": null, "e": 6654, "s": 6374, "text": "\n The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications. This tutorial helps you to build your base with PHP.\n " }, { "code": null, "e": 6822, "s": 6654, "text": "\n Before proceeding with this tutorial you should have at least basic understanding of computer programming, Internet, Database, and MySQL etc is very helpful.\n " }, { "code": null, "e": 6855, "s": 6822, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 6869, "s": 6855, "text": " Mahesh Kumar" }, { "code": null, "e": 6904, "s": 6869, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6918, "s": 6904, "text": " Pratik Singh" }, { "code": null, "e": 6953, "s": 6918, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6970, "s": 6953, "text": " Frahaan Hussain" }, { "code": null, "e": 7003, "s": 6970, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 7031, "s": 7003, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7064, "s": 7031, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 7085, "s": 7064, "text": " Sandip Bhattacharya" }, { "code": null, "e": 7117, "s": 7085, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 7134, "s": 7117, "text": " Laurence Svekis" }, { "code": null, "e": 7141, "s": 7134, "text": " Print" }, { "code": null, "e": 7152, "s": 7141, "text": " Add Notes" } ]
Transpose of Matrix | Practice | GeeksforGeeks
Write a program to find the transpose of a square matrix of size N*N. Transpose of a matrix is obtained by changing rows to columns and columns to rows. Example 1: Input: N = 4 mat[][] = {{1, 1, 1, 1}, {2, 2, 2, 2} {3, 3, 3, 3} {4, 4, 4, 4}} Output: {{1, 2, 3, 4}, {1, 2, 3, 4} {1, 2, 3, 4} {1, 2, 3, 4}} Example 2: Input: N = 2 mat[][] = {{1, 2}, {-9, -2}} Output: {{1, -9}, {2, -2}} Your Task: You dont need to read input or print anything. Complete the function transpose() which takes matrix[][] and N as input parameter and finds the transpose of the input matrix. You need to do this in-place. That is you need to update the original matrix with the transpose. Expected Time Complexity: O(N * N) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 100 -103 <= mat[i][j] <= 103 0 jaatgfg113 weeks ago c++ ezz pzz void transpose(vector<vector<int> >& matrix, int n) { for(int i=0;i<n;i++){ for(int j=0;j<i;j++){ swap(matrix[i][j],matrix[j][i]); } } } 0 saiakhilpodduturi1 month ago Transpose of Matrix (Java Solution) class Solution { //Function to find transpose of a matrix. static void transpose(int matrix[][], int n) { // code here for (int i=0; i<n-1; i++) { for (int j=i+1; j<n; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } } } 0 aakasshuit2 months ago //Java Solution for(int i =0 ; i<n ; i++){ for(int j =i ; j<n ; j++){ int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } 0 sunghunet2 months ago # Python Version def transpose(self, m, n): for i in range(n): for j in range(i+1, n): m[i][j], m[j][i] = m[j][i], m[i][j] +1 sunghunet2 months ago We only need to access the range of an upper triangular matrix or a lower triangular matrix. There is no need to iterate over every number of elements in the matrix. Just put j=i+1. void transpose(std::vector<std::vector<int> >& matrix, int n) { for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) std::swap(matrix[i][j], matrix[j][i]); } 0 lakshyanawandhar4573 months ago // { Driver Code Starts#include <bits/stdc++.h> using namespace std; // } Driver Code Endsclass Solution{ public: //Function to find transpose of a matrix. void transpose(vector<vector<int> >& m, int n) { // code here for(int i=0;i<n;++i){ for(int j=i;j<n;++j){ swap(m[i][j],m[j][i]); } } }}; // { Driver Code Starts. int main() { int t; cin>>t; while(t--) { int n; cin>>n; vector<vector<int> > matrix(n); for(int i=0; i<n; i++) { matrix[i].assign(n, 0); for( int j=0; j<n; j++) { cin>>matrix[i][j]; } } Solution ob; ob.transpose(matrix,n); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) cout<<matrix[i][j]<<" "; cout<<endl; } return 0;} // } Driver Code Ends 0 dcvog35f4ne2xjgysnru01jdwe9xsoscyyq121kj3 months ago void transpose(vector<vector<int> >& matrix, int n) { for(int i=0;i<n;i++){ for(int j=i+1;j<matrix[i].size();j++){ if(i==j){ continue; } swap(matrix[i][j],matrix[j][i]); } } } 0 rko163 months ago Total Time Taken: 0.1/1.1 void transpose(vector<vector<int> >& matrix, int n) { for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) swap(matrix[i][j],matrix[j][i]); } +1 gauravg770613 months ago void transpose(vector<vector<int> >& matrix, int n) { // code here for(int i=0;i<n;i++){ for(int j=0;j<i;j++){ int temp=matrix[i][j]; matrix[i][j]=matrix[j][i]; matrix[j][i]=temp; } } } 0 mindy3 months ago void transpose(vector<vector<int> >& matrix, int n) { for(int i=0; i<n; i++) { for(int j=i; j<n; j++) { if(i!=j) swap(matrix[i][j],matrix[j][i]); } } } 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": 391, "s": 226, "text": "Write a program to find the transpose of a square matrix of size N*N. Transpose of a matrix is obtained by changing rows to columns and columns to rows.\n\nExample 1:" }, { "code": null, "e": 575, "s": 391, "text": "Input:\nN = 4\nmat[][] = {{1, 1, 1, 1},\n {2, 2, 2, 2}\n {3, 3, 3, 3}\n {4, 4, 4, 4}}\nOutput: \n{{1, 2, 3, 4}, \n {1, 2, 3, 4} \n {1, 2, 3, 4}\n {1, 2, 3, 4}} \n" }, { "code": null, "e": 586, "s": 575, "text": "Example 2:" }, { "code": null, "e": 670, "s": 586, "text": "Input:\nN = 2\nmat[][] = {{1, 2},\n {-9, -2}}\nOutput:\n{{1, -9}, \n {2, -2}}\n\n" }, { "code": null, "e": 1073, "s": 670, "text": "Your Task:\nYou dont need to read input or print anything. Complete the function transpose() which takes matrix[][] and N as input parameter and finds the transpose of the input matrix. You need to do this in-place. That is you need to update the original matrix with the transpose. \n\nExpected Time Complexity: O(N * N)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n1 <= N <= 100\n-103 <= mat[i][j] <= 103" }, { "code": null, "e": 1075, "s": 1073, "text": "0" }, { "code": null, "e": 1096, "s": 1075, "text": "jaatgfg113 weeks ago" }, { "code": null, "e": 1109, "s": 1096, "text": "c++ ezz pzz" }, { "code": null, "e": 1303, "s": 1111, "text": " void transpose(vector<vector<int> >& matrix, int n) { for(int i=0;i<n;i++){ for(int j=0;j<i;j++){ swap(matrix[i][j],matrix[j][i]); } } }" }, { "code": null, "e": 1305, "s": 1303, "text": "0" }, { "code": null, "e": 1334, "s": 1305, "text": "saiakhilpodduturi1 month ago" }, { "code": null, "e": 1370, "s": 1334, "text": "Transpose of Matrix (Java Solution)" }, { "code": null, "e": 1760, "s": 1370, "text": "class Solution\n{\n //Function to find transpose of a matrix.\n static void transpose(int matrix[][], int n)\n {\n // code here\n for (int i=0; i<n-1; i++)\n {\n for (int j=i+1; j<n; j++)\n {\n int temp = matrix[i][j];\n matrix[i][j] = matrix[j][i];\n matrix[j][i] = temp;\n }\n }\n }\n}" }, { "code": null, "e": 1762, "s": 1760, "text": "0" }, { "code": null, "e": 1785, "s": 1762, "text": "aakasshuit2 months ago" }, { "code": null, "e": 2023, "s": 1785, "text": "//Java Solution\n\n for(int i =0 ; i<n ; i++){\n for(int j =i ; j<n ; j++){\n int temp = matrix[i][j];\n matrix[i][j] = matrix[j][i];\n matrix[j][i] = temp;\n }\n }" }, { "code": null, "e": 2025, "s": 2023, "text": "0" }, { "code": null, "e": 2047, "s": 2025, "text": "sunghunet2 months ago" }, { "code": null, "e": 2195, "s": 2047, "text": "# Python Version\ndef transpose(self, m, n):\n for i in range(n):\n for j in range(i+1, n):\n m[i][j], m[j][i] = m[j][i], m[i][j] " }, { "code": null, "e": 2200, "s": 2197, "text": "+1" }, { "code": null, "e": 2222, "s": 2200, "text": "sunghunet2 months ago" }, { "code": null, "e": 2388, "s": 2222, "text": "We only need to access the range of an upper triangular matrix or a lower triangular matrix. There is no need to iterate over every number of elements in the matrix." }, { "code": null, "e": 2405, "s": 2388, "text": "Just put j=i+1. " }, { "code": null, "e": 2579, "s": 2405, "text": "void transpose(std::vector<std::vector<int> >& matrix, int n) {\n for(int i=0;i<n;i++)\n for(int j=i+1;j<n;j++)\n std::swap(matrix[i][j], matrix[j][i]);\n}\n" }, { "code": null, "e": 2583, "s": 2581, "text": "0" }, { "code": null, "e": 2615, "s": 2583, "text": "lakshyanawandhar4573 months ago" }, { "code": null, "e": 2684, "s": 2615, "text": "// { Driver Code Starts#include <bits/stdc++.h> using namespace std;" }, { "code": null, "e": 2977, "s": 2684, "text": "// } Driver Code Endsclass Solution{ public: //Function to find transpose of a matrix. void transpose(vector<vector<int> >& m, int n) { // code here for(int i=0;i<n;++i){ for(int j=i;j<n;++j){ swap(m[i][j],m[j][i]); } } }};" }, { "code": null, "e": 3002, "s": 2977, "text": "// { Driver Code Starts." }, { "code": null, "e": 3120, "s": 3002, "text": "int main() { int t; cin>>t; while(t--) { int n; cin>>n; vector<vector<int> > matrix(n);" }, { "code": null, "e": 3291, "s": 3120, "text": " for(int i=0; i<n; i++) { matrix[i].assign(n, 0); for( int j=0; j<n; j++) { cin>>matrix[i][j]; } }" }, { "code": null, "e": 3510, "s": 3291, "text": " Solution ob; ob.transpose(matrix,n); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) cout<<matrix[i][j]<<\" \"; cout<<endl; } return 0;} // } Driver Code Ends" }, { "code": null, "e": 3512, "s": 3510, "text": "0" }, { "code": null, "e": 3565, "s": 3512, "text": "dcvog35f4ne2xjgysnru01jdwe9xsoscyyq121kj3 months ago" }, { "code": null, "e": 3838, "s": 3565, "text": "void transpose(vector<vector<int> >& matrix, int n) { for(int i=0;i<n;i++){ for(int j=i+1;j<matrix[i].size();j++){ if(i==j){ continue; } swap(matrix[i][j],matrix[j][i]); } } }" }, { "code": null, "e": 3840, "s": 3838, "text": "0" }, { "code": null, "e": 3858, "s": 3840, "text": "rko163 months ago" }, { "code": null, "e": 3876, "s": 3858, "text": "Total Time Taken:" }, { "code": null, "e": 3884, "s": 3876, "text": "0.1/1.1" }, { "code": null, "e": 4049, "s": 3884, "text": " void transpose(vector<vector<int> >& matrix, int n) { for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) swap(matrix[i][j],matrix[j][i]); }" }, { "code": null, "e": 4052, "s": 4049, "text": "+1" }, { "code": null, "e": 4077, "s": 4052, "text": "gauravg770613 months ago" }, { "code": null, "e": 4355, "s": 4077, "text": " void transpose(vector<vector<int> >& matrix, int n) { // code here for(int i=0;i<n;i++){ for(int j=0;j<i;j++){ int temp=matrix[i][j]; matrix[i][j]=matrix[j][i]; matrix[j][i]=temp; } } }" }, { "code": null, "e": 4357, "s": 4355, "text": "0" }, { "code": null, "e": 4375, "s": 4357, "text": "mindy3 months ago" }, { "code": null, "e": 4554, "s": 4375, "text": " void transpose(vector<vector<int> >& matrix, int n)\n { \n for(int i=0; i<n; i++)\n {\n for(int j=i; j<n; j++)\n {\n if(i!=j) swap(matrix[i][j],matrix[j][i]);\n }\n }\n }" }, { "code": null, "e": 4700, "s": 4554, "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": 4736, "s": 4700, "text": " Login to access your submissions. " }, { "code": null, "e": 4746, "s": 4736, "text": "\nProblem\n" }, { "code": null, "e": 4756, "s": 4746, "text": "\nContest\n" }, { "code": null, "e": 4819, "s": 4756, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4967, "s": 4819, "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": 5175, "s": 4967, "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": 5281, "s": 5175, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Progress Bars in Python. When dealing with large data, even... | by Sam Wilkinson | Towards Data Science
Just like a watched pot never boils, a watched for loop never ends. When dealing with large datasets, even the simplest operations can take hours. Progress bars can help make data processing jobs less of a headache because: You get a reliable estimate of how long it will take.You can see immediately if it’s gotten stuck. You get a reliable estimate of how long it will take. You can see immediately if it’s gotten stuck. The first of these is especially valuable in a business environment, where having a solid delivery estimate can make you look super professional. The best/only way I’ve found to add progress bars to Python code is with tqdm. While it is super easy to use, tqdm can be a bit finnicky to set up, especially if you use JupyterLab (which you totally should). After trawling StackOverflow and some trial and error, I think I’ve found a surefire way to get tqdm up and running (even with JupyterLab)! First, install tqdm with your package manager of choice (pip, pipenv, anaconda etc). Once it’s installed, you can activate the ipywidgets plugin for JupyterLab by running, > pip install ipywidgets > jupyter nbextension enable --py widgetsnbextension> jupyter labextension install @jupyter-widgets/jupyterlab-manager To activate tqdm in a notebook you just need to add a cell with, %%capturefrom tqdm import tqdm_notebook as tqdmtqdm().pandas() If you’re just going to be using tqdm in a script, you can skip both of these steps! You can get a progress bar for any iterable by wrapping it with tqdm(). For example, my_list = list(range(100))for x in tqdm(my_list): pass will give you a (very fast) progress bar. You also use tqdm more explicitly, my_list = list(range(100))with tqdm(total=len(my_list)) as pbar: for x in my_list: pbar.update(1) There’s also a pandas integration, df.progress_apply(lambda x: pass) For more on using tqdm, including things like nested progress bars, check out their documentation.
[ { "code": null, "e": 271, "s": 47, "text": "Just like a watched pot never boils, a watched for loop never ends. When dealing with large datasets, even the simplest operations can take hours. Progress bars can help make data processing jobs less of a headache because:" }, { "code": null, "e": 370, "s": 271, "text": "You get a reliable estimate of how long it will take.You can see immediately if it’s gotten stuck." }, { "code": null, "e": 424, "s": 370, "text": "You get a reliable estimate of how long it will take." }, { "code": null, "e": 470, "s": 424, "text": "You can see immediately if it’s gotten stuck." }, { "code": null, "e": 825, "s": 470, "text": "The first of these is especially valuable in a business environment, where having a solid delivery estimate can make you look super professional. The best/only way I’ve found to add progress bars to Python code is with tqdm. While it is super easy to use, tqdm can be a bit finnicky to set up, especially if you use JupyterLab (which you totally should)." }, { "code": null, "e": 965, "s": 825, "text": "After trawling StackOverflow and some trial and error, I think I’ve found a surefire way to get tqdm up and running (even with JupyterLab)!" }, { "code": null, "e": 1137, "s": 965, "text": "First, install tqdm with your package manager of choice (pip, pipenv, anaconda etc). Once it’s installed, you can activate the ipywidgets plugin for JupyterLab by running," }, { "code": null, "e": 1281, "s": 1137, "text": "> pip install ipywidgets > jupyter nbextension enable --py widgetsnbextension> jupyter labextension install @jupyter-widgets/jupyterlab-manager" }, { "code": null, "e": 1346, "s": 1281, "text": "To activate tqdm in a notebook you just need to add a cell with," }, { "code": null, "e": 1409, "s": 1346, "text": "%%capturefrom tqdm import tqdm_notebook as tqdmtqdm().pandas()" }, { "code": null, "e": 1494, "s": 1409, "text": "If you’re just going to be using tqdm in a script, you can skip both of these steps!" }, { "code": null, "e": 1579, "s": 1494, "text": "You can get a progress bar for any iterable by wrapping it with tqdm(). For example," }, { "code": null, "e": 1637, "s": 1579, "text": "my_list = list(range(100))for x in tqdm(my_list): pass" }, { "code": null, "e": 1714, "s": 1637, "text": "will give you a (very fast) progress bar. You also use tqdm more explicitly," }, { "code": null, "e": 1822, "s": 1714, "text": "my_list = list(range(100))with tqdm(total=len(my_list)) as pbar: for x in my_list: pbar.update(1)" }, { "code": null, "e": 1857, "s": 1822, "text": "There’s also a pandas integration," }, { "code": null, "e": 1891, "s": 1857, "text": "df.progress_apply(lambda x: pass)" } ]
How can I save HTML locally with JavaScript?
To save HTML locally with JavaScript, create an HTML file and save the following code in it. The code is for cookies in JavaScript − <!DOCTYPE html> <html> <body> <p id="visits"></p> <script> var visits = parseInt(document.cookie.split("=")[1]); if (isNaN(visits)) visits = 0; visits++; document.cookie = "visits =" + visits; document.getElementById("visits").innerHTML = "The page ran " + timesVisited + " times."; </script> </body> </html> Just save the above file and open in a web browser.
[ { "code": null, "e": 1195, "s": 1062, "text": "To save HTML locally with JavaScript, create an HTML file and save the following code in it. The code is for cookies in JavaScript −" }, { "code": null, "e": 1573, "s": 1195, "text": "<!DOCTYPE html>\n<html>\n <body>\n <p id=\"visits\"></p>\n <script>\n var visits = parseInt(document.cookie.split(\"=\")[1]);\n if (isNaN(visits)) visits = 0;\n visits++;\n document.cookie = \"visits =\" + visits;\n document.getElementById(\"visits\").innerHTML = \"The page ran \" + timesVisited + \" times.\";\n </script>\n </body>\n</html>" }, { "code": null, "e": 1625, "s": 1573, "text": "Just save the above file and open in a web browser." } ]
Understanding a TensorFlow program in simple steps. | by Nidhin Mahesh | Towards Data Science
TensorFlow is a library which can be applied to all the machine learning algorithms especially deep learning with neural network. Machine learning is simply those programs which are written to deal with large data-sets to find patterns in them and extract information. It actually learn from data to make accurate or somewhere near predictions and correct itself for the better. Just like we wanted someone to do. Image recognition, and its enhancement or even identifying it is some applications of ML. I felt happy to see welcoming changes since I wrote my first story on TF. This story focuses on some fundamentals to understand a TensorFlow program. I would suggest to try the code in your machine and see how it works. for the ability to run the same model on different problem set we need placeholders and feed dictionaries. As our TensorFlow program become more complex, our visualization needs to keep up. Regression tries to model relationship where there is cause and effect. Cause is an independent variable which occurs and Effect depends on cause. Linear regression is a straight line regression which is caused when modelling the regression X causes Y. Cause is also called explanatory variable Eg: hypothesis of wealth increases life expectancy. For equation Y=A+BX. to find the best fit, ML algorithm will give initial values to A and B. It will run the regression and find the errors with those values of A and B. These are then fed back to the input to get new values of A and B. Linear regression involves finding best fit line best fit line is found by minimizing the least square error. best fit line is the one where the sum of the square of the lengths of the line joining from bottom to the datapoint in graph is minimum. Placeholders in TensorFlow are similar to variables and you can declare it using tf.placeholder. You dont have to provide an initial value and you can specify it at runtime with feed_dict argument inside Session.run , whereas in tf.Variable you can to provide initial value when you declare it. sample program using placeholder import tensorflow as tf#setup placeholder using tf.placeholderx = tf.placeholder(tf.int32, shape=[3],name='x')'''it is of type integer and it has shape 3 meaning it is a 1D vector with 3 elements in itwe name it x. just create another placeholder y with same dimension. we treat the placeholders like we treate constants. '''y = tf.placeholder(tf.int32, shape=[3],name='y')sum_x = tf.reduce_sum(x,name="sum_x")prod_y = tf.reduce_prod(y,name="prod_y")'''we dont know what values x and y holds till we run the graph'''final_div = tf.div(sum_x,prod_y, nwe give fetches and feed_dict pass into every session.run commandame="final_div")final_mean = tf.reduce_mean([sum_x, prod_y], name="final_mean")sess = tf.Session()print ("sum(x): ", sess.run(sum_x, feed_dict={x: [100,200,300]}))print ("prod(y): ", sess.run(prod_y, feed_dict={y: [1,2,3]}))writer = tf.summary.FileWriter('./tensorflow_example',sess.graph)writer.close()sess.close() we give fetches and feed_dict pass into every session.run command. fetches parameter indicate what it is we want to compute and the feed dictionary specifies the placeholder values for that computation import tensorflow as tfW = tf.constant([10,100], name='const_W')#these placeholders can hold tensors of any shape#we will feed these placeholders laterx = tf.placeholder(tf.int32, name='x')b = tf.placeholder(tf.int32,name='b')#tf.multiply is simple multiplication and not matrixWx = tf.multiply(W,x, name="Wx")y = tf.add(Wx,b,name='y')with tf.Session() as sess: '''all the code which require a session is writer here here Wx is the fetches parameter. fetches refers to the node of the graph we want to compute feed_dict is used to pass the values for the placeholders ''' print( "Intermediate result Wx: ", sess.run(Wx, feed_dict={x: [3,33]})) print( "Final results y: ",sess.run(y, feed_dict={x:[5,50],b:[7,9]}))writer = tf.summary.FileWriter('./fetchesAndFeed',sess.graph)writer.close() Variables are constructs which allow you to change the value stored there. Supervised learning algorithms perform multiple iterations before they arrive at final conclusion use variable to store the values which change as the model converges. Our aim is to minimize the error between the regression line and the points in the data set. So we tweak the regression line with each iteration to get new values. To get the best fit line of the equation y=A+Bx, we constantly tweak the value of A and B. Variables are mutable tensor values that persist across multiple calls to sesssion.run(). I explain this with the same demo code as above. import tensorflow as tfW = tf.Variable([2.5,4.0],tf.float32, name='var_W')#here W is a Variablex = tf.placeholder(tf.float32, name='x')b = tf.Variable([5.0,10.0],tf.float32, name='var_b')#b is also a variable with initial value 5 and 10y = W * x + b#initialize all variables definedinit = tf.global_variables_initializer()#global_variable_initializer() will declare all the variable we have initilized# use with statement to instantiate and assign a sessionwith tf.Session() as sess: sess.run(init) #this computation is required to initialize the variable print("Final result: Wx + b = ", sess.run(y,feed_dict={x:[10,100]}))# changing values number = tf.Variable(2)multiplier = tf.Variable(1)init = tf.global_variables_initializer()result = number.assign(tf.multiply(number,multiplier))with tf.Session() as sess: sess.run(init)for i in range(10): print("Result number * multiplier = ",sess.run(result)) print("Increment multiplier, new value = ",sess.run(multiplier.assign_add(1))) We can explicitly create as many graphs inside a TensorFlow program. Any TensorFlow program have a default graph which contains all the placeholders and variables you have instantiated. But we can logically segment the graph by instantiating a graph explicitly using tf.graph() . Below program may answer some of your doubts. import tensorflow as tfg1 = tf.Graph()'''set g1 as default to add tensors to this graph using default methord'''with g1.as_default(): with tf.Session() as sess: A = tf.constant([5,7],tf.int32, name='A') x = tf.placeholder(tf.int32, name='x') b = tf.constant([3,4],tf.int32, name='b')y = A * x + bprint( sess.run(y, feed_dict={x: [10,100]})) '''to ensure all the tensors and computations are within the graph g1, we use assert''' assert y.graph is g1g2 = tf.Graph()with g2.as_default(): with tf.Session() as sess: A = tf.constant([5,7],tf.int32, name='A') x = tf.placeholder(tf.int32, name='x') y = tf.pow(A,x,name='y') print( sess.run(y, feed_dict={x: [3,5]})) assert y.graph is g2'''same way you can access defaut graph '''default_graph = tf.get_default_graph()with tf.Session() as sess: A = tf.constant([5,7],tf.int32, name='A') x = tf.placeholder(tf.int32, name='x') y = A + x print(sess.run(y, feed_dict={x: [3,5]}))assert y.graph is default_graph TensorBoard may be most extremely useful debugging tool, but as your graph explodes in size, you need some ways to get the details in a bigger picture. Now run the below program using TensorFlow and view its graph in TensorBoard import tensorflow as tfA = tf.constant([4], tf.int32, name='A')B = tf.constant([4], tf.int32, name='B')C = tf.constant([4], tf.int32, name='C')x = tf.placeholder(tf.int32, name='x')# y = Ax^2 + Bx + CAx2_1 = tf.multiply(A, tf.pow(x,2), name="Ax2_1")Bx = tf.multiply(A,x, name="Bx")y1 = tf.add_n([Ax2_1, Bx, C], name='y1')# y = Ax^2 + Bx^2Ax2_2 = tf.multiply(A, tf.pow(x,2),name='Ax2_2')Bx2 = tf.multiply(B, tf.pow(x,2),name='Bx2')y2 = tf.add_n([Ax2_2,Bx2],name='y2')y = y1 + y2with tf.Session() as sess: print(sess.run(y, feed_dict={x:[10]}))writer = tf.summary.FileWriter('./named_scope',sess.graph) writer.close() this graph looks really comlpicated! Now we can organize things in tensorboard using named scope. define the name scope using with tf.name_scope("name the scope"): and write the code inside this scope. Above program can be arranged using namescope as shown import tensorflow as tfA = tf.constant([4], tf.int32, name='A')B = tf.constant([4], tf.int32, name='B')C = tf.constant([4], tf.int32, name='C')x = tf.placeholder(tf.int32, name='x')# y = Ax^2 + Bx + Cwith tf.name_scope("Equation1"): Ax2_1 = tf.multiply(A, tf.pow(x,2), name="Ax2_1") Bx = tf.multiply(A,x, name="Bx") y1 = tf.add_n([Ax2_1, Bx, C], name='y1')# y = Ax^2 + Bx^2with tf.name_scope("Equation2"): Ax2_2 = tf.multiply(A, tf.pow(x,2),name='Ax2_2') Bx2 = tf.multiply(B, tf.pow(x,2),name='Bx2') y2 = tf.add_n([Ax2_2,Bx2],name='y2')with tf.name_scope("final_sum"): y = y1 + y2with tf.Session() as sess: print(sess.run(y, feed_dict={x:[10]}))writer = tf.summary.FileWriter('./named_scope',sess.graph) writer.close()
[ { "code": null, "e": 676, "s": 172, "text": "TensorFlow is a library which can be applied to all the machine learning algorithms especially deep learning with neural network. Machine learning is simply those programs which are written to deal with large data-sets to find patterns in them and extract information. It actually learn from data to make accurate or somewhere near predictions and correct itself for the better. Just like we wanted someone to do. Image recognition, and its enhancement or even identifying it is some applications of ML." }, { "code": null, "e": 896, "s": 676, "text": "I felt happy to see welcoming changes since I wrote my first story on TF. This story focuses on some fundamentals to understand a TensorFlow program. I would suggest to try the code in your machine and see how it works." }, { "code": null, "e": 1381, "s": 896, "text": "for the ability to run the same model on different problem set we need placeholders and feed dictionaries. As our TensorFlow program become more complex, our visualization needs to keep up. Regression tries to model relationship where there is cause and effect. Cause is an independent variable which occurs and Effect depends on cause. Linear regression is a straight line regression which is caused when modelling the regression X causes Y. Cause is also called explanatory variable" }, { "code": null, "e": 1433, "s": 1381, "text": "Eg: hypothesis of wealth increases life expectancy." }, { "code": null, "e": 1719, "s": 1433, "text": "For equation Y=A+BX. to find the best fit, ML algorithm will give initial values to A and B. It will run the regression and find the errors with those values of A and B. These are then fed back to the input to get new values of A and B. Linear regression involves finding best fit line" }, { "code": null, "e": 1918, "s": 1719, "text": "best fit line is found by minimizing the least square error. best fit line is the one where the sum of the square of the lengths of the line joining from bottom to the datapoint in graph is minimum." }, { "code": null, "e": 2213, "s": 1918, "text": "Placeholders in TensorFlow are similar to variables and you can declare it using tf.placeholder. You dont have to provide an initial value and you can specify it at runtime with feed_dict argument inside Session.run , whereas in tf.Variable you can to provide initial value when you declare it." }, { "code": null, "e": 2246, "s": 2213, "text": "sample program using placeholder" }, { "code": null, "e": 3177, "s": 2246, "text": "import tensorflow as tf#setup placeholder using tf.placeholderx = tf.placeholder(tf.int32, shape=[3],name='x')'''it is of type integer and it has shape 3 meaning it is a 1D vector with 3 elements in itwe name it x. just create another placeholder y with same dimension. we treat the placeholders like we treate constants. '''y = tf.placeholder(tf.int32, shape=[3],name='y')sum_x = tf.reduce_sum(x,name=\"sum_x\")prod_y = tf.reduce_prod(y,name=\"prod_y\")'''we dont know what values x and y holds till we run the graph'''final_div = tf.div(sum_x,prod_y, nwe give fetches and feed_dict pass into every session.run commandame=\"final_div\")final_mean = tf.reduce_mean([sum_x, prod_y], name=\"final_mean\")sess = tf.Session()print (\"sum(x): \", sess.run(sum_x, feed_dict={x: [100,200,300]}))print (\"prod(y): \", sess.run(prod_y, feed_dict={y: [1,2,3]}))writer = tf.summary.FileWriter('./tensorflow_example',sess.graph)writer.close()sess.close()" }, { "code": null, "e": 3379, "s": 3177, "text": "we give fetches and feed_dict pass into every session.run command. fetches parameter indicate what it is we want to compute and the feed dictionary specifies the placeholder values for that computation" }, { "code": null, "e": 4168, "s": 3379, "text": "import tensorflow as tfW = tf.constant([10,100], name='const_W')#these placeholders can hold tensors of any shape#we will feed these placeholders laterx = tf.placeholder(tf.int32, name='x')b = tf.placeholder(tf.int32,name='b')#tf.multiply is simple multiplication and not matrixWx = tf.multiply(W,x, name=\"Wx\")y = tf.add(Wx,b,name='y')with tf.Session() as sess: '''all the code which require a session is writer here here Wx is the fetches parameter. fetches refers to the node of the graph we want to compute feed_dict is used to pass the values for the placeholders ''' print( \"Intermediate result Wx: \", sess.run(Wx, feed_dict={x: [3,33]})) print( \"Final results y: \",sess.run(y, feed_dict={x:[5,50],b:[7,9]}))writer = tf.summary.FileWriter('./fetchesAndFeed',sess.graph)writer.close()" }, { "code": null, "e": 4666, "s": 4168, "text": "Variables are constructs which allow you to change the value stored there. Supervised learning algorithms perform multiple iterations before they arrive at final conclusion use variable to store the values which change as the model converges. Our aim is to minimize the error between the regression line and the points in the data set. So we tweak the regression line with each iteration to get new values. To get the best fit line of the equation y=A+Bx, we constantly tweak the value of A and B." }, { "code": null, "e": 4805, "s": 4666, "text": "Variables are mutable tensor values that persist across multiple calls to sesssion.run(). I explain this with the same demo code as above." }, { "code": null, "e": 5789, "s": 4805, "text": "import tensorflow as tfW = tf.Variable([2.5,4.0],tf.float32, name='var_W')#here W is a Variablex = tf.placeholder(tf.float32, name='x')b = tf.Variable([5.0,10.0],tf.float32, name='var_b')#b is also a variable with initial value 5 and 10y = W * x + b#initialize all variables definedinit = tf.global_variables_initializer()#global_variable_initializer() will declare all the variable we have initilized# use with statement to instantiate and assign a sessionwith tf.Session() as sess: sess.run(init) #this computation is required to initialize the variable print(\"Final result: Wx + b = \", sess.run(y,feed_dict={x:[10,100]}))# changing values number = tf.Variable(2)multiplier = tf.Variable(1)init = tf.global_variables_initializer()result = number.assign(tf.multiply(number,multiplier))with tf.Session() as sess: sess.run(init)for i in range(10): print(\"Result number * multiplier = \",sess.run(result)) print(\"Increment multiplier, new value = \",sess.run(multiplier.assign_add(1)))" }, { "code": null, "e": 6115, "s": 5789, "text": "We can explicitly create as many graphs inside a TensorFlow program. Any TensorFlow program have a default graph which contains all the placeholders and variables you have instantiated. But we can logically segment the graph by instantiating a graph explicitly using tf.graph() . Below program may answer some of your doubts." }, { "code": null, "e": 7077, "s": 6115, "text": "import tensorflow as tfg1 = tf.Graph()'''set g1 as default to add tensors to this graph using default methord'''with g1.as_default(): with tf.Session() as sess: A = tf.constant([5,7],tf.int32, name='A') x = tf.placeholder(tf.int32, name='x') b = tf.constant([3,4],tf.int32, name='b')y = A * x + bprint( sess.run(y, feed_dict={x: [10,100]})) '''to ensure all the tensors and computations are within the graph g1, we use assert''' assert y.graph is g1g2 = tf.Graph()with g2.as_default(): with tf.Session() as sess: A = tf.constant([5,7],tf.int32, name='A') x = tf.placeholder(tf.int32, name='x') y = tf.pow(A,x,name='y') print( sess.run(y, feed_dict={x: [3,5]})) assert y.graph is g2'''same way you can access defaut graph '''default_graph = tf.get_default_graph()with tf.Session() as sess: A = tf.constant([5,7],tf.int32, name='A') x = tf.placeholder(tf.int32, name='x') y = A + x print(sess.run(y, feed_dict={x: [3,5]}))assert y.graph is default_graph" }, { "code": null, "e": 7306, "s": 7077, "text": "TensorBoard may be most extremely useful debugging tool, but as your graph explodes in size, you need some ways to get the details in a bigger picture. Now run the below program using TensorFlow and view its graph in TensorBoard" }, { "code": null, "e": 7922, "s": 7306, "text": "import tensorflow as tfA = tf.constant([4], tf.int32, name='A')B = tf.constant([4], tf.int32, name='B')C = tf.constant([4], tf.int32, name='C')x = tf.placeholder(tf.int32, name='x')# y = Ax^2 + Bx + CAx2_1 = tf.multiply(A, tf.pow(x,2), name=\"Ax2_1\")Bx = tf.multiply(A,x, name=\"Bx\")y1 = tf.add_n([Ax2_1, Bx, C], name='y1')# y = Ax^2 + Bx^2Ax2_2 = tf.multiply(A, tf.pow(x,2),name='Ax2_2')Bx2 = tf.multiply(B, tf.pow(x,2),name='Bx2')y2 = tf.add_n([Ax2_2,Bx2],name='y2')y = y1 + y2with tf.Session() as sess: print(sess.run(y, feed_dict={x:[10]}))writer = tf.summary.FileWriter('./named_scope',sess.graph) writer.close()" }, { "code": null, "e": 7959, "s": 7922, "text": "this graph looks really comlpicated!" }, { "code": null, "e": 8048, "s": 7959, "text": "Now we can organize things in tensorboard using named scope. define the name scope using" }, { "code": null, "e": 8086, "s": 8048, "text": "with tf.name_scope(\"name the scope\"):" }, { "code": null, "e": 8179, "s": 8086, "text": "and write the code inside this scope. Above program can be arranged using namescope as shown" } ]
Puppet - Agent Setup
Puppet agent is a software application, provided by Puppet labs, which runs on any node in Puppet cluster. If one wants to manage any server using the Puppet master, the Puppet agent software needs to be installed on that particular server. In general, the Puppet agent will be installed on all the machines excluding the Puppet master machine on any given infrastructure. Puppet agent software has the capability to run on most of the Linux, UNIX, and Windows machines. In the following examples, we are using CentOS machine installation Puppet agent software on it. Step 1 − Enable the official Puppet labs collection repository with the following command. $ sudo rpm -ivh https://yum.puppetlabs.com/puppetlabs-release-pc1-el7.noarch.rpm Step 2 − Install the Puppet agent package. $ sudo yum -y install puppet-agent Step 3 − Once the Puppet agent is installed, enable it with the following command. $ sudo /opt/puppetlabs/bin/puppet resource service puppet ensure=running enable = true One key feature of the Puppet agent is, for the first time when the Puppet agent starts running, it generates a SSL certificate and sends it to the Puppet master which is going to manage it for signing and approval. Once the Puppet master approves the agent’s certificate signature request, it will be able to communicate and manage the agent node. Note − One needs to repeat the above steps on all the nodes which needs to be configured and managed any a given Puppet master. Print Add Notes Bookmark this page
[ { "code": null, "e": 2741, "s": 2173, "text": "Puppet agent is a software application, provided by Puppet labs, which runs on any node in Puppet cluster. If one wants to manage any server using the Puppet master, the Puppet agent software needs to be installed on that particular server. In general, the Puppet agent will be installed on all the machines excluding the Puppet master machine on any given infrastructure. Puppet agent software has the capability to run on most of the Linux, UNIX, and Windows machines. In the following examples, we are using CentOS machine installation Puppet agent software on it." }, { "code": null, "e": 2832, "s": 2741, "text": "Step 1 − Enable the official Puppet labs collection repository with the following command." }, { "code": null, "e": 2914, "s": 2832, "text": "$ sudo rpm -ivh https://yum.puppetlabs.com/puppetlabs-release-pc1-el7.noarch.rpm\n" }, { "code": null, "e": 2957, "s": 2914, "text": "Step 2 − Install the Puppet agent package." }, { "code": null, "e": 2993, "s": 2957, "text": "$ sudo yum -y install puppet-agent\n" }, { "code": null, "e": 3076, "s": 2993, "text": "Step 3 − Once the Puppet agent is installed, enable it with the following command." }, { "code": null, "e": 3164, "s": 3076, "text": "$ sudo /opt/puppetlabs/bin/puppet resource service puppet ensure=running enable = true\n" }, { "code": null, "e": 3513, "s": 3164, "text": "One key feature of the Puppet agent is, for the first time when the Puppet agent starts running, it generates a SSL certificate and sends it to the Puppet master which is going to manage it for signing and approval. Once the Puppet master approves the agent’s certificate signature request, it will be able to communicate and manage the agent node." }, { "code": null, "e": 3641, "s": 3513, "text": "Note − One needs to repeat the above steps on all the nodes which needs to be configured and managed any a given Puppet master." }, { "code": null, "e": 3648, "s": 3641, "text": " Print" }, { "code": null, "e": 3659, "s": 3648, "text": " Add Notes" } ]
VBA - Sub Procedure
Sub Procedures are similar to functions, however there are a few differences. Sub procedures DO NOT Return a value while functions may or may not return a value. Sub procedures DO NOT Return a value while functions may or may not return a value. Sub procedures CAN be called without a call keyword. Sub procedures CAN be called without a call keyword. Sub procedures are always enclosed within Sub and End Sub statements. Sub procedures are always enclosed within Sub and End Sub statements. Sub Area(x As Double, y As Double) MsgBox x * y End Sub To invoke a Procedure somewhere in the script, you can make a call from a function. We will not be able to use the same way as that of a function as sub procedure WILL NOT return a value. Function findArea(Length As Double, Width As Variant) area Length, Width ' To Calculate Area 'area' sub proc is called End Function Now you will be able to call the function only but not the sub procedure as shown in the following screenshot. The area is calculated and shown only in the Message box. The result cell displays ZERO as the area value is NOT returned from the function. In short, you cannot make a direct call to a sub procedure from the excel worksheet. 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": 2013, "s": 1935, "text": "Sub Procedures are similar to functions, however there are a few differences." }, { "code": null, "e": 2097, "s": 2013, "text": "Sub procedures DO NOT Return a value while functions may or may not return a value." }, { "code": null, "e": 2181, "s": 2097, "text": "Sub procedures DO NOT Return a value while functions may or may not return a value." }, { "code": null, "e": 2234, "s": 2181, "text": "Sub procedures CAN be called without a call keyword." }, { "code": null, "e": 2287, "s": 2234, "text": "Sub procedures CAN be called without a call keyword." }, { "code": null, "e": 2357, "s": 2287, "text": "Sub procedures are always enclosed within Sub and End Sub statements." }, { "code": null, "e": 2427, "s": 2357, "text": "Sub procedures are always enclosed within Sub and End Sub statements." }, { "code": null, "e": 2486, "s": 2427, "text": "Sub Area(x As Double, y As Double)\n MsgBox x * y\nEnd Sub" }, { "code": null, "e": 2674, "s": 2486, "text": "To invoke a Procedure somewhere in the script, you can make a call from a function. We will not be able to use the same way as that of a function as sub procedure WILL NOT return a value." }, { "code": null, "e": 2812, "s": 2674, "text": "Function findArea(Length As Double, Width As Variant)\n area Length, Width ' To Calculate Area 'area' sub proc is called\nEnd Function" }, { "code": null, "e": 2923, "s": 2812, "text": "Now you will be able to call the function only but not the sub procedure as shown in the following screenshot." }, { "code": null, "e": 2981, "s": 2923, "text": "The area is calculated and shown only in the Message box." }, { "code": null, "e": 3149, "s": 2981, "text": "The result cell displays ZERO as the area value is NOT returned from the function. In short, you cannot make a direct call to a sub procedure from the excel worksheet." }, { "code": null, "e": 3183, "s": 3149, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 3198, "s": 3183, "text": " Pavan Lalwani" }, { "code": null, "e": 3231, "s": 3198, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 3246, "s": 3231, "text": " Arnold Higuit" }, { "code": null, "e": 3281, "s": 3246, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3299, "s": 3281, "text": " Prashant Panchal" }, { "code": null, "e": 3332, "s": 3299, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 3350, "s": 3332, "text": " Prashant Panchal" }, { "code": null, "e": 3383, "s": 3350, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 3398, "s": 3383, "text": " Arnold Higuit" }, { "code": null, "e": 3434, "s": 3398, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 3462, "s": 3434, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 3469, "s": 3462, "text": " Print" }, { "code": null, "e": 3480, "s": 3469, "text": " Add Notes" } ]
A Comprehensive Tutorial to Rust Operators for Beginners | by Shinichi Okada | Towards Data Science
Table of ContentsIntroduction🦀 Arithmetic Operators🦀 Comparison Operators🦀 Logical Operators🦀 Bitwise Operators🦀 Compound Assignment Operators🦀 Operator Overloading🦀 XOR and Bitwise Operators Truth Table🦀 Problem 1: Single Number🦀 Python Solution🦀 Rust Code🦀 Method and Associated Functions🦀 Solution Using an Associated Function🦀 Problem 2: Number of Steps to Reduce a Number to ZeroConclusion [Updated on Feb-18- 2020. Codes changed to Gist and added links] Operators tell the compiler or interpreter to perform a specific mathematical, relational, or logical operation. Many programming languages make use of similar operator symbols. We will go through the important arithmetic, relational, and logical operators available in Rust and we will compare them to Python. We will learn the differences between methods and associated functions. We also convert two simple Python codes to Rust codes to learn more about Rust programming. Let’s get started! towardsdatascience.com Python and Rust share the same arithmetic symbols as you see in the above table. Rust calls % as Remainder instead of the Modulus. We will cover “Rust Overloading Trait” later in the Operator Overloading. Output: a: 20, b: 20+1=21, c: 20-2=18, d: 20*3=60, e: 20/4=5, f: 20%3=2 In Rust, you can’t use different data types in an operation. For example, if you try to subtract an unsigned integer from a signed integer, it will fail: // This will fail.fn main() { let a = 8u8; let b = 2i32; println!("{}", a - b);} Rust uses the as keyword to cast between primitive types. Please read more about the cast in Rust here. Output: 6 ExponentPython uses the ** symbol for exponents: Output: 2^3 is 83^3 is 273^3.2 is 33.63473536961897 Rust uses pow, powi, and powf depends on the type: Output: 2 ^ 3 in Rust: 2u8.pow(3) = 82 ^ 3 in Rust: 2i32.pow(3) is 83.0 ^ 3 in Rust: 3.0f32.powi(3) 273.0 ^ 3.2 in Rust: 3.0_f32.powf(3.2) is 33.63474a = 3, a ^ 3 in Rust: i32::pow(a,3) = 27b = 3.1, b ^ 3 in Rust: f64::powi(b, 3) = 29.791000000000004b = 3.1, b ^ PI in Rust: std::f64::consts::PI) = 34.96699308140392 In Rust, you can annotate a number type like 2u8 or 2_u8. u8 is an unsigned 8-bit integer type and i32 is a signed integer type. i32 and f32 have a group of built-in methods. All the integer types u8, u16, u32, u64, u128, i16,i32, i64 , i128, isize, and usize have the pow method. pub fn pow(self, exp: u32) -> i32 The above definition tells you that using the pow method raises self to the power of exp (which is u32) and returns i32 (a signed integer). The floating-point types, f32 and f64 have powi and powf methods. powi raises a number to an integer power and powf raises a number to a floating-point power. pub fn powi(self, n: i32) -> f32pub fn powf(self, n: f32) -> f32 Floor DivisionIn Python, we use // to find a floor division. For example 5//2=2. Output: 5 // 2 is 2-5 // 2 is -3 Rust’s floating-point types use the floor method. Output: 2-3 Python and Rust share the same symbols for all the comparison operators. Output: a: 7, b: 4, c: 7 == 4 is false, d: 7 != 4 is true, e: 7<4 is false, f: 7>4 is true, g: 7<=7 is true, h: 7>=7 is true Rust logical operator symbols are different from Python ones. Output: a: true, b: false, c: !true is false, d: true && false is false, e: true || false is true All the Rust and Python Bitwise operators share the same bitwise operator symbols except the bitwise NOT. Output: a: 1, b: 2, c: 1 & 2 is 0, d: 1 | 2 is 3, e: 1 ^ 2 is 3, f: 1 << 2 is 4, f2: 1 << 4 is 16, g: 1 >> 2 is 0, g2: 1 >> 2 is 1, h: !1 = -2 Bitwise negation !1 returns -2. Rust uses the two’s complement to find the bitwise negation for signed types. Rust’s signed integer types are called the signed two’s complement integer types. You can use 1 << n to find out exponents of 2. Output: 2 ^ 3 = 82 ^ 4 = 162 ^ 5 = 32 All the Rust and Python compound assignment operators have the same symbols except Rust doesn’t have the equivalence of power assignment **=, and floor division assignment //=. Output: a is 21: a += 5 is 72: a -= 2 is 53: a *= 5 is 254: a /= 2 is 125: a %= 5 is 26: a &= 2 is 27: a |= 5 is 78: a ^= 2 is 59: a <<= 1 is 1010: a >>= 2 is 2 Operator overloading is to specify more than one definition for an operator in the same scope. Python and Rust provide operator overloading. You can find Rust overloadable operators in the standard library ops module. Output: Point { x: 3, y: 3 } As we saw previously, Python and Rust use the same symbols for bitwise symbols AND, OR , and XOR. & is the bitwise AND, | is the bitwise OR , and ^ is the bitwise XOR (exclusive OR). You can see the truth table and the Venn diagram below. When you use XOR with even numbers of the same number, the output is always 0. In Rust, you can use {:#b} to print binary. Output: 0 ^ 0 = 0Binary: 0 ^ 0 = 0b01 ^ 1 = 0Binary: 1 ^ 1 = 0b02 ^ 2 = 0Binary: 2 ^ 2 = 0b03 ^ 5 ^ 3 ^ 5 = 0Binary: 3 ^ 5 ^ 3 ^ 5 = 0b01 ^ 1 ^ 1 = 1Binary: 1 ^ 1 ^ 1 = 0b11 ^ 1 ^ 5 = 5Binary: 1 ^ 1 ^ 5 = 0b101 You can find Python code here. We are going to use this XOR to solve the LeetCoder problem called Single number. In this problem, an array input has a pair of numbers except one, for example [1, 1, 5, 5, 2]. You need to find a sing number from this array and in this case the output should be 2. More example: When the input is [2, 2, 1], the output should be 1. When an input is [4, 1, 2, 1, 2] the output should be 4. This is a good example to use the XOR operator. We briefly go through the Python solution to see how the problem was solved. Output: 4 Line 1: We use Python typing which is introduced from v3.5. Line 3–4: After importing List, we create a class called Solution and method called singleNumber. With Python type hints, we capitalize the name of the type, and set the name of the type inside the collection in brackets as seen above, num: List[int]. Line 5–8: We set a variable ans to 0. Using a for loop, we iterate the input array, nums using XOR compound assignment, ans ^= n. This will output the single number from the array. Line 10–11: We instantiate the class Solution and call the method singleNumber. (You can run this Python code without type notations if you are interested.) The following is the solution for the LeetCode environment: class Solution: def singleNumber(self, nums: List[int]) -> int: ans = 0 for n in nums: ans ^= n return ans Rust structs contain named fields. We use a keyword struct and set fields with its type within the curly bracket. We put methods into a impl block. Starting code Output: 1 Line 1: We suppress dead_code warning. Line 2–4: Create a struct called Solution that takes one field nums with Vec<i32> type. (More on Vectors.) Line 6–10: We create a method single_number in impl Solution. The single_number takes the first parameter &self (More on self .) and we just return 1 for now. Line 12–17: In the main function, we create an instance and print 1 using the method. It seems all working so we are going to complete the single_number method next. Methods are defined within the context of a struct and their first parameter is always self, which represents the instance of the struct the method is being called on. - The Rust Programming Language Associated functions don’t take self as a parameter and they are not methods because they don’t have an instance of the struct to work with. A good example is String::from function. We use the :: syntax with the struct name to call this associated function whereas we use . when we call a method. A common associated function is a new function that returns a value of the type the associated function is associated with. Output: x: 5, y: 4x: 8, y: 9 Final code Line 7–11: We create a mutable variable ans with the type of i32 . Using for loop, we iterate &self.nums using ans ^=n. Output: 5 We adjust the above code to the LeetCode environment. impl Solution { pub fn single_number(nums: Vec<i32>) -> i32 { let mut ans: i32 = 0; for n in nums { ans ^= n; } ans }} The memory usage is 2.2 MB in Rust and 16.5 MB in Python. (More on Runtime & Memory usage) Since we learned about the associated function, let’s apply it to this problem. Output: 14 Line 6–10: We create an associated function, new as we have done it before. This new function takes one parameter nums that is a vector with items of i32. When the parameter names and the struct field names are exactly the same, we can use the field init shorthand syntax as nums instead of nums: nums. In the main function, we call an associated function, new and pass nums as an argument. We use method syntax to call the single_number method on the ans3 instance. In this problem, you input a non-negative integer num and return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. For example: Input: num = 14Output: 6Explanation: Step 1) 14 is even; divide by 2 and obtain 7. Step 2) 7 is odd; subtract 1 and obtain 6.Step 3) 6 is even; divide by 2 and obtain 3. Step 4) 3 is odd; subtract 1 and obtain 2. Step 5) 2 is even; divide by 2 and obtain 1. Step 6) 1 is odd; subtract 1 and obtain 0.Input: num = 8Output: 4Explanation: Step 1) 8 is even; divide by 2 and obtain 4. Step 2) 4 is even; divide by 2 and obtain 2. Step 3) 2 is even; divide by 2 and obtain 1. Step 4) 1 is odd; subtract 1 and obtain 0. This is a good example that we can use the Modulus/Remainder operator and the compound assignment operators. Python Solution Output: 64 Line: 3–10: We use a while loop for num > 0. If the modulus is 0, then it must be an even number so we divide the num by 2 using a compound assignment /=2, otherwise, we subtract 1 using a compound assignment -=1. We increase the steps by 1. Finally, we return the steps. We adjust the above code to the LeetCode environment. class Solution: def numberOfSteps (self, num: int) -> int: steps = 0 while num > 0: if num % 2 == 0: num //= 2 else: num -=1 steps += 1 return steps Rust Solution Output: 64 In Rust, we take the same steps as we did in Python. Line 7–16: We assign 0 to a mutable variable steps. While self.num is greater than 0, we use the compound assignment /=2 if self.num 's remainder is 0, otherwise, we subtract 1, and increase the number of step by 1. We adjust the above code to the LeetCode environment. impl Solution { pub fn number_of_steps (mut num: i32) -> i32 { let mut steps = 0; while num > 0 { if num % 2 == 0 { num /= 2; } else { num -=1; } steps += 1; } steps }} We learned arithmetic, comparison, logical, bitwise, and compound assignment operators in Rust. We also learned operator overloading, the difference between associated functions and methods, how to use operators in Rust by converting simple Python codes to Rust. I hope you learned something and are ready for the next step. Please stay tuned for the next post. Get full access to every story on Medium by becoming a member. The following resources were used to compile this post:
[ { "code": null, "e": 567, "s": 172, "text": "Table of ContentsIntroduction🦀 Arithmetic Operators🦀 Comparison Operators🦀 Logical Operators🦀 Bitwise Operators🦀 Compound Assignment Operators🦀 Operator Overloading🦀 XOR and Bitwise Operators Truth Table🦀 Problem 1: Single Number🦀 Python Solution🦀 Rust Code🦀 Method and Associated Functions🦀 Solution Using an Associated Function🦀 Problem 2: Number of Steps to Reduce a Number to ZeroConclusion" }, { "code": null, "e": 632, "s": 567, "text": "[Updated on Feb-18- 2020. Codes changed to Gist and added links]" }, { "code": null, "e": 810, "s": 632, "text": "Operators tell the compiler or interpreter to perform a specific mathematical, relational, or logical operation. Many programming languages make use of similar operator symbols." }, { "code": null, "e": 943, "s": 810, "text": "We will go through the important arithmetic, relational, and logical operators available in Rust and we will compare them to Python." }, { "code": null, "e": 1015, "s": 943, "text": "We will learn the differences between methods and associated functions." }, { "code": null, "e": 1107, "s": 1015, "text": "We also convert two simple Python codes to Rust codes to learn more about Rust programming." }, { "code": null, "e": 1126, "s": 1107, "text": "Let’s get started!" }, { "code": null, "e": 1149, "s": 1126, "text": "towardsdatascience.com" }, { "code": null, "e": 1280, "s": 1149, "text": "Python and Rust share the same arithmetic symbols as you see in the above table. Rust calls % as Remainder instead of the Modulus." }, { "code": null, "e": 1354, "s": 1280, "text": "We will cover “Rust Overloading Trait” later in the Operator Overloading." }, { "code": null, "e": 1362, "s": 1354, "text": "Output:" }, { "code": null, "e": 1426, "s": 1362, "text": "a: 20, b: 20+1=21, c: 20-2=18, d: 20*3=60, e: 20/4=5, f: 20%3=2" }, { "code": null, "e": 1580, "s": 1426, "text": "In Rust, you can’t use different data types in an operation. For example, if you try to subtract an unsigned integer from a signed integer, it will fail:" }, { "code": null, "e": 1670, "s": 1580, "text": "// This will fail.fn main() { let a = 8u8; let b = 2i32; println!(\"{}\", a - b);}" }, { "code": null, "e": 1774, "s": 1670, "text": "Rust uses the as keyword to cast between primitive types. Please read more about the cast in Rust here." }, { "code": null, "e": 1782, "s": 1774, "text": "Output:" }, { "code": null, "e": 1784, "s": 1782, "text": "6" }, { "code": null, "e": 1833, "s": 1784, "text": "ExponentPython uses the ** symbol for exponents:" }, { "code": null, "e": 1841, "s": 1833, "text": "Output:" }, { "code": null, "e": 1888, "s": 1841, "text": "2^3 is 83^3 is 273^3.2 is 33.63473536961897" }, { "code": null, "e": 1939, "s": 1888, "text": "Rust uses pow, powi, and powf depends on the type:" }, { "code": null, "e": 1947, "s": 1939, "text": "Output:" }, { "code": null, "e": 2256, "s": 1947, "text": "2 ^ 3 in Rust: 2u8.pow(3) = 82 ^ 3 in Rust: 2i32.pow(3) is 83.0 ^ 3 in Rust: 3.0f32.powi(3) 273.0 ^ 3.2 in Rust: 3.0_f32.powf(3.2) is 33.63474a = 3, a ^ 3 in Rust: i32::pow(a,3) = 27b = 3.1, b ^ 3 in Rust: f64::powi(b, 3) = 29.791000000000004b = 3.1, b ^ PI in Rust: std::f64::consts::PI) = 34.96699308140392" }, { "code": null, "e": 2385, "s": 2256, "text": "In Rust, you can annotate a number type like 2u8 or 2_u8. u8 is an unsigned 8-bit integer type and i32 is a signed integer type." }, { "code": null, "e": 2537, "s": 2385, "text": "i32 and f32 have a group of built-in methods. All the integer types u8, u16, u32, u64, u128, i16,i32, i64 , i128, isize, and usize have the pow method." }, { "code": null, "e": 2571, "s": 2537, "text": "pub fn pow(self, exp: u32) -> i32" }, { "code": null, "e": 2711, "s": 2571, "text": "The above definition tells you that using the pow method raises self to the power of exp (which is u32) and returns i32 (a signed integer)." }, { "code": null, "e": 2777, "s": 2711, "text": "The floating-point types, f32 and f64 have powi and powf methods." }, { "code": null, "e": 2870, "s": 2777, "text": "powi raises a number to an integer power and powf raises a number to a floating-point power." }, { "code": null, "e": 2935, "s": 2870, "text": "pub fn powi(self, n: i32) -> f32pub fn powf(self, n: f32) -> f32" }, { "code": null, "e": 3016, "s": 2935, "text": "Floor DivisionIn Python, we use // to find a floor division. For example 5//2=2." }, { "code": null, "e": 3024, "s": 3016, "text": "Output:" }, { "code": null, "e": 3051, "s": 3024, "text": "5 // 2 is 2-5 // 2 is -3" }, { "code": null, "e": 3101, "s": 3051, "text": "Rust’s floating-point types use the floor method." }, { "code": null, "e": 3109, "s": 3101, "text": "Output:" }, { "code": null, "e": 3113, "s": 3109, "text": "2-3" }, { "code": null, "e": 3186, "s": 3113, "text": "Python and Rust share the same symbols for all the comparison operators." }, { "code": null, "e": 3194, "s": 3186, "text": "Output:" }, { "code": null, "e": 3339, "s": 3194, "text": " a: 7, b: 4, c: 7 == 4 is false, d: 7 != 4 is true, e: 7<4 is false, f: 7>4 is true, g: 7<=7 is true, h: 7>=7 is true" }, { "code": null, "e": 3401, "s": 3339, "text": "Rust logical operator symbols are different from Python ones." }, { "code": null, "e": 3409, "s": 3401, "text": "Output:" }, { "code": null, "e": 3515, "s": 3409, "text": " a: true, b: false, c: !true is false, d: true && false is false, e: true || false is true" }, { "code": null, "e": 3621, "s": 3515, "text": "All the Rust and Python Bitwise operators share the same bitwise operator symbols except the bitwise NOT." }, { "code": null, "e": 3629, "s": 3621, "text": "Output:" }, { "code": null, "e": 3795, "s": 3629, "text": " a: 1, b: 2, c: 1 & 2 is 0, d: 1 | 2 is 3, e: 1 ^ 2 is 3, f: 1 << 2 is 4, f2: 1 << 4 is 16, g: 1 >> 2 is 0, g2: 1 >> 2 is 1, h: !1 = -2" }, { "code": null, "e": 3987, "s": 3795, "text": "Bitwise negation !1 returns -2. Rust uses the two’s complement to find the bitwise negation for signed types. Rust’s signed integer types are called the signed two’s complement integer types." }, { "code": null, "e": 4034, "s": 3987, "text": "You can use 1 << n to find out exponents of 2." }, { "code": null, "e": 4042, "s": 4034, "text": "Output:" }, { "code": null, "e": 4072, "s": 4042, "text": "2 ^ 3 = 82 ^ 4 = 162 ^ 5 = 32" }, { "code": null, "e": 4249, "s": 4072, "text": "All the Rust and Python compound assignment operators have the same symbols except Rust doesn’t have the equivalence of power assignment **=, and floor division assignment //=." }, { "code": null, "e": 4257, "s": 4249, "text": "Output:" }, { "code": null, "e": 4410, "s": 4257, "text": "a is 21: a += 5 is 72: a -= 2 is 53: a *= 5 is 254: a /= 2 is 125: a %= 5 is 26: a &= 2 is 27: a |= 5 is 78: a ^= 2 is 59: a <<= 1 is 1010: a >>= 2 is 2" }, { "code": null, "e": 4628, "s": 4410, "text": "Operator overloading is to specify more than one definition for an operator in the same scope. Python and Rust provide operator overloading. You can find Rust overloadable operators in the standard library ops module." }, { "code": null, "e": 4636, "s": 4628, "text": "Output:" }, { "code": null, "e": 4657, "s": 4636, "text": "Point { x: 3, y: 3 }" }, { "code": null, "e": 4755, "s": 4657, "text": "As we saw previously, Python and Rust use the same symbols for bitwise symbols AND, OR , and XOR." }, { "code": null, "e": 4896, "s": 4755, "text": "& is the bitwise AND, | is the bitwise OR , and ^ is the bitwise XOR (exclusive OR). You can see the truth table and the Venn diagram below." }, { "code": null, "e": 4975, "s": 4896, "text": "When you use XOR with even numbers of the same number, the output is always 0." }, { "code": null, "e": 5019, "s": 4975, "text": "In Rust, you can use {:#b} to print binary." }, { "code": null, "e": 5027, "s": 5019, "text": "Output:" }, { "code": null, "e": 5230, "s": 5027, "text": "0 ^ 0 = 0Binary: 0 ^ 0 = 0b01 ^ 1 = 0Binary: 1 ^ 1 = 0b02 ^ 2 = 0Binary: 2 ^ 2 = 0b03 ^ 5 ^ 3 ^ 5 = 0Binary: 3 ^ 5 ^ 3 ^ 5 = 0b01 ^ 1 ^ 1 = 1Binary: 1 ^ 1 ^ 1 = 0b11 ^ 1 ^ 5 = 5Binary: 1 ^ 1 ^ 5 = 0b101" }, { "code": null, "e": 5261, "s": 5230, "text": "You can find Python code here." }, { "code": null, "e": 5343, "s": 5261, "text": "We are going to use this XOR to solve the LeetCoder problem called Single number." }, { "code": null, "e": 5526, "s": 5343, "text": "In this problem, an array input has a pair of numbers except one, for example [1, 1, 5, 5, 2]. You need to find a sing number from this array and in this case the output should be 2." }, { "code": null, "e": 5650, "s": 5526, "text": "More example: When the input is [2, 2, 1], the output should be 1. When an input is [4, 1, 2, 1, 2] the output should be 4." }, { "code": null, "e": 5698, "s": 5650, "text": "This is a good example to use the XOR operator." }, { "code": null, "e": 5775, "s": 5698, "text": "We briefly go through the Python solution to see how the problem was solved." }, { "code": null, "e": 5783, "s": 5775, "text": "Output:" }, { "code": null, "e": 5785, "s": 5783, "text": "4" }, { "code": null, "e": 5845, "s": 5785, "text": "Line 1: We use Python typing which is introduced from v3.5." }, { "code": null, "e": 5943, "s": 5845, "text": "Line 3–4: After importing List, we create a class called Solution and method called singleNumber." }, { "code": null, "e": 6097, "s": 5943, "text": "With Python type hints, we capitalize the name of the type, and set the name of the type inside the collection in brackets as seen above, num: List[int]." }, { "code": null, "e": 6278, "s": 6097, "text": "Line 5–8: We set a variable ans to 0. Using a for loop, we iterate the input array, nums using XOR compound assignment, ans ^= n. This will output the single number from the array." }, { "code": null, "e": 6358, "s": 6278, "text": "Line 10–11: We instantiate the class Solution and call the method singleNumber." }, { "code": null, "e": 6435, "s": 6358, "text": "(You can run this Python code without type notations if you are interested.)" }, { "code": null, "e": 6495, "s": 6435, "text": "The following is the solution for the LeetCode environment:" }, { "code": null, "e": 6637, "s": 6495, "text": "class Solution: def singleNumber(self, nums: List[int]) -> int: ans = 0 for n in nums: ans ^= n return ans" }, { "code": null, "e": 6785, "s": 6637, "text": "Rust structs contain named fields. We use a keyword struct and set fields with its type within the curly bracket. We put methods into a impl block." }, { "code": null, "e": 6799, "s": 6785, "text": "Starting code" }, { "code": null, "e": 6807, "s": 6799, "text": "Output:" }, { "code": null, "e": 6809, "s": 6807, "text": "1" }, { "code": null, "e": 6848, "s": 6809, "text": "Line 1: We suppress dead_code warning." }, { "code": null, "e": 6955, "s": 6848, "text": "Line 2–4: Create a struct called Solution that takes one field nums with Vec<i32> type. (More on Vectors.)" }, { "code": null, "e": 7114, "s": 6955, "text": "Line 6–10: We create a method single_number in impl Solution. The single_number takes the first parameter &self (More on self .) and we just return 1 for now." }, { "code": null, "e": 7200, "s": 7114, "text": "Line 12–17: In the main function, we create an instance and print 1 using the method." }, { "code": null, "e": 7280, "s": 7200, "text": "It seems all working so we are going to complete the single_number method next." }, { "code": null, "e": 7480, "s": 7280, "text": "Methods are defined within the context of a struct and their first parameter is always self, which represents the instance of the struct the method is being called on. - The Rust Programming Language" }, { "code": null, "e": 7621, "s": 7480, "text": "Associated functions don’t take self as a parameter and they are not methods because they don’t have an instance of the struct to work with." }, { "code": null, "e": 7662, "s": 7621, "text": "A good example is String::from function." }, { "code": null, "e": 7777, "s": 7662, "text": "We use the :: syntax with the struct name to call this associated function whereas we use . when we call a method." }, { "code": null, "e": 7901, "s": 7777, "text": "A common associated function is a new function that returns a value of the type the associated function is associated with." }, { "code": null, "e": 7909, "s": 7901, "text": "Output:" }, { "code": null, "e": 7930, "s": 7909, "text": "x: 5, y: 4x: 8, y: 9" }, { "code": null, "e": 7941, "s": 7930, "text": "Final code" }, { "code": null, "e": 8061, "s": 7941, "text": "Line 7–11: We create a mutable variable ans with the type of i32 . Using for loop, we iterate &self.nums using ans ^=n." }, { "code": null, "e": 8069, "s": 8061, "text": "Output:" }, { "code": null, "e": 8071, "s": 8069, "text": "5" }, { "code": null, "e": 8125, "s": 8071, "text": "We adjust the above code to the LeetCode environment." }, { "code": null, "e": 8297, "s": 8125, "text": "impl Solution { pub fn single_number(nums: Vec<i32>) -> i32 { let mut ans: i32 = 0; for n in nums { ans ^= n; } ans }}" }, { "code": null, "e": 8388, "s": 8297, "text": "The memory usage is 2.2 MB in Rust and 16.5 MB in Python. (More on Runtime & Memory usage)" }, { "code": null, "e": 8468, "s": 8388, "text": "Since we learned about the associated function, let’s apply it to this problem." }, { "code": null, "e": 8476, "s": 8468, "text": "Output:" }, { "code": null, "e": 8479, "s": 8476, "text": "14" }, { "code": null, "e": 8634, "s": 8479, "text": "Line 6–10: We create an associated function, new as we have done it before. This new function takes one parameter nums that is a vector with items of i32." }, { "code": null, "e": 8782, "s": 8634, "text": "When the parameter names and the struct field names are exactly the same, we can use the field init shorthand syntax as nums instead of nums: nums." }, { "code": null, "e": 8946, "s": 8782, "text": "In the main function, we call an associated function, new and pass nums as an argument. We use method syntax to call the single_number method on the ans3 instance." }, { "code": null, "e": 9155, "s": 8946, "text": "In this problem, you input a non-negative integer num and return the number of steps to reduce it to zero. If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it." }, { "code": null, "e": 9168, "s": 9155, "text": "For example:" }, { "code": null, "e": 9682, "s": 9168, "text": "Input: num = 14Output: 6Explanation: Step 1) 14 is even; divide by 2 and obtain 7. Step 2) 7 is odd; subtract 1 and obtain 6.Step 3) 6 is even; divide by 2 and obtain 3. Step 4) 3 is odd; subtract 1 and obtain 2. Step 5) 2 is even; divide by 2 and obtain 1. Step 6) 1 is odd; subtract 1 and obtain 0.Input: num = 8Output: 4Explanation: Step 1) 8 is even; divide by 2 and obtain 4. Step 2) 4 is even; divide by 2 and obtain 2. Step 3) 2 is even; divide by 2 and obtain 1. Step 4) 1 is odd; subtract 1 and obtain 0." }, { "code": null, "e": 9791, "s": 9682, "text": "This is a good example that we can use the Modulus/Remainder operator and the compound assignment operators." }, { "code": null, "e": 9807, "s": 9791, "text": "Python Solution" }, { "code": null, "e": 9815, "s": 9807, "text": "Output:" }, { "code": null, "e": 9818, "s": 9815, "text": "64" }, { "code": null, "e": 10090, "s": 9818, "text": "Line: 3–10: We use a while loop for num > 0. If the modulus is 0, then it must be an even number so we divide the num by 2 using a compound assignment /=2, otherwise, we subtract 1 using a compound assignment -=1. We increase the steps by 1. Finally, we return the steps." }, { "code": null, "e": 10144, "s": 10090, "text": "We adjust the above code to the LeetCode environment." }, { "code": null, "e": 10382, "s": 10144, "text": "class Solution: def numberOfSteps (self, num: int) -> int: steps = 0 while num > 0: if num % 2 == 0: num //= 2 else: num -=1 steps += 1 return steps" }, { "code": null, "e": 10396, "s": 10382, "text": "Rust Solution" }, { "code": null, "e": 10404, "s": 10396, "text": "Output:" }, { "code": null, "e": 10407, "s": 10404, "text": "64" }, { "code": null, "e": 10460, "s": 10407, "text": "In Rust, we take the same steps as we did in Python." }, { "code": null, "e": 10676, "s": 10460, "text": "Line 7–16: We assign 0 to a mutable variable steps. While self.num is greater than 0, we use the compound assignment /=2 if self.num 's remainder is 0, otherwise, we subtract 1, and increase the number of step by 1." }, { "code": null, "e": 10730, "s": 10676, "text": "We adjust the above code to the LeetCode environment." }, { "code": null, "e": 11007, "s": 10730, "text": "impl Solution { pub fn number_of_steps (mut num: i32) -> i32 { let mut steps = 0; while num > 0 { if num % 2 == 0 { num /= 2; } else { num -=1; } steps += 1; } steps }}" }, { "code": null, "e": 11270, "s": 11007, "text": "We learned arithmetic, comparison, logical, bitwise, and compound assignment operators in Rust. We also learned operator overloading, the difference between associated functions and methods, how to use operators in Rust by converting simple Python codes to Rust." }, { "code": null, "e": 11369, "s": 11270, "text": "I hope you learned something and are ready for the next step. Please stay tuned for the next post." }, { "code": null, "e": 11432, "s": 11369, "text": "Get full access to every story on Medium by becoming a member." } ]
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks
19 Nov, 2018 Consider the following code sequence having five instructions I1 to I5. Each of these instructions has the following format. OP Ri, Rj, Rk where operation OP is performed on contents of registers Rj and Rk and the result is stored in register Ri. I1 : ADD R1, R2, R3 I2 : MUL R7, R1, R3 I3 : SUB R4, R1, R5 I4 : ADD R3, R2, R4 I5 : MUL R7, R8, R9 Consider the following three statements: S1: There is an anti-dependence between instructions I2 and I5. S2: There is an anti-dependence between instructions I2 and I4. S3: Within an instruction pipeline an anti-dependence always creates one or more stalls. Which one of above statements is/are correct? (A) Only S1 is true(B) Only S2 is true(C) Only S1 and S2 are true(D) Only S2 and S3 are trueAnswer: (B)Explanation: The given instructions can be written as below: I1: R1 = R2 + R3 I2: R7 = R1 * R3 I3: R4 = R1 - R5 I4: R3 = R2 + R4 I5: R7 = R8 * R9 An anti-dependency, also known as write-after-read (WAR), occurs when an instruction requires a value that is later updated. S1: There is an anti-dependence between instructions I2 and I5. False, I2 and I5 don't form any write after read situation. They both write R7. S2: There is an anti-dependence between instructions I2 and I4. True, I2 reads R3 and I4 writes it. S3: Within an instruction pipeline an anti-dependence always creates one or more stalls. Anti-dependency can be removed by renaming variables. See following example. 1. B = 3 2. A = B + 1 3. B = 7 Renaming of variables could remove the dependency. 1. B = 3 N. B2 = B 2. A = B2 + 1 3. B = 7 Quiz of this Question GATE-CS-2015 (Set 3) GATE-GATE-CS-2015 (Set 3) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2004 | Question 3 GATE | GATE CS 2010 | Question 24 GATE | GATE CS 2011 | Question 65 GATE | GATE CS 2019 | Question 27 GATE | GATE CS 2021 | Set 1 | Question 47 GATE | GATE CS 2011 | Question 7
[ { "code": null, "e": 24462, "s": 24434, "text": "\n19 Nov, 2018" }, { "code": null, "e": 24587, "s": 24462, "text": "Consider the following code sequence having five instructions I1 to I5. Each of these instructions has the following format." }, { "code": null, "e": 24606, "s": 24587, "text": " OP Ri, Rj, Rk " }, { "code": null, "e": 24714, "s": 24606, "text": "where operation OP is performed on contents of registers Rj and Rk and the result is stored in register Ri." }, { "code": null, "e": 24830, "s": 24714, "text": " I1 : ADD R1, R2, R3\n I2 : MUL R7, R1, R3\n I3 : SUB R4, R1, R5\n I4 : ADD R3, R2, R4\n I5 : MUL R7, R8, R9 " }, { "code": null, "e": 24871, "s": 24830, "text": "Consider the following three statements:" }, { "code": null, "e": 25094, "s": 24871, "text": "S1: There is an anti-dependence between instructions I2 and I5.\nS2: There is an anti-dependence between instructions I2 and I4.\nS3: Within an instruction pipeline an anti-dependence always \n creates one or more stalls. " }, { "code": null, "e": 25140, "s": 25094, "text": "Which one of above statements is/are correct?" }, { "code": null, "e": 25304, "s": 25140, "text": "(A) Only S1 is true(B) Only S2 is true(C) Only S1 and S2 are true(D) Only S2 and S3 are trueAnswer: (B)Explanation: The given instructions can be written as below:" }, { "code": null, "e": 25391, "s": 25304, "text": "I1: R1 = R2 + R3\nI2: R7 = R1 * R3\nI3: R4 = R1 - R5 \nI4: R3 = R2 + R4\nI5: R7 = R8 * R9 " }, { "code": null, "e": 25516, "s": 25391, "text": "An anti-dependency, also known as write-after-read (WAR), occurs when an instruction requires a value that is later updated." }, { "code": null, "e": 26061, "s": 25516, "text": "S1: There is an anti-dependence between instructions I2 and I5.\nFalse, I2 and I5 don't form any write after read situation. \nThey both write R7.\n\nS2: There is an anti-dependence between instructions I2 and I4.\nTrue, I2 reads R3 and I4 writes it.\n\nS3: Within an instruction pipeline an anti-dependence always \n creates one or more stalls. \nAnti-dependency can be removed by renaming variables. \nSee following example.\n1. B = 3\n2. A = B + 1\n3. B = 7\nRenaming of variables could remove the dependency.\n1. B = 3\nN. B2 = B\n2. A = B2 + 1\n3. B = 7" }, { "code": null, "e": 26083, "s": 26061, "text": "Quiz of this Question" }, { "code": null, "e": 26104, "s": 26083, "text": "GATE-CS-2015 (Set 3)" }, { "code": null, "e": 26130, "s": 26104, "text": "GATE-GATE-CS-2015 (Set 3)" }, { "code": null, "e": 26135, "s": 26130, "text": "GATE" }, { "code": null, "e": 26233, "s": 26135, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26267, "s": 26233, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 26309, "s": 26267, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26351, "s": 26309, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 26385, "s": 26351, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 26418, "s": 26385, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 26452, "s": 26418, "text": "GATE | GATE CS 2010 | Question 24" }, { "code": null, "e": 26486, "s": 26452, "text": "GATE | GATE CS 2011 | Question 65" }, { "code": null, "e": 26520, "s": 26486, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 26562, "s": 26520, "text": "GATE | GATE CS 2021 | Set 1 | Question 47" } ]
Explainable AI: Interpretation & Trust in Machine Learning Models - Lime | Towards Data Science
Why should we trust a machine learning model blindly? Wouldn’t it be wonderful if we can get a better insight into model predictions and improve our decision making? With the advent of explainable AI techniques such as LIME and SHAP, it is no longer a challenge. Nowadays, machine learning models are ubiquitous and becoming a part of our lives more than ever. These models are usually a black box in essence that it’s hard for us to assess the model behavior. From smart speakers with inbuilt conversational agents to personalized recommendation systems, we use them daily, but do we understand why they behave in a certain way? Given their ability to influence our decision, it is of paramount and supreme importance that we should be able to trust them. Explainable AI systems help us understand the inner workings of such models. So, What’s Explainable AI? Explainable AI can be summed up as a process to understand the predictions of an ML model. The central idea is to make the model as interpretable as possible which will essentially help in testing its reliability and causality of features. Broadly speaking, there are two dimensions to interpretability: Explainability(Why did it do that?)Transparency(How it works?) Explainability(Why did it do that?) Transparency(How it works?) Typically, explainable AI systems provide an assessment of model input features and identify the features which are driving force of the model. It gives us a sense of control, as we can then decide if we can rely on the predictions of these models. For instance, we would probably trust a flu identification model more if it considers features like temperature, and cough more significant than other symptoms. Now that you have an idea of explainable systems, how do we explain model predictions? There are different ways to do that. LIME is one of them. Let’s squeeze it. LIME stands for:Local: Approximate locally in the neighborhood of prediction being explained,Interpretable: Explanations produced are human-readable,Model-Agnostic: Works for any model like SVM, Neural networks, etc Explanations: Provides explanations of model predictions.(Local linear explanation of model behaviour) Lime can be used to get more insights into model prediction like explaining why models take a particular decision for an individual observation. It can also be quite useful while selecting between different models. The central idea behind Lime is that it explains locally in the vicinity of the instance being explained by perturbating the different features rather than producing explanations at the entire model level. It does so by fitting a sparse model on the locally dispersed, noise-induced dataset. This helps convert a non-linear problem into a linear one. The indicator variables with the largest coefficients in the model are then returned as the drivers of the score. You can simply pip install it or can clone the Github repo: pip install limepip install . (Git version) We will use Lime for explaining predictions of a random forest regressor model on the Diabetes dataset which is inbuilt in sci-kit learn. This post assumes that you already have some knowledge of Python, and Machine Learning. For the sake of simplicity, we will not cover all steps we usually follow in the model building pipeline like visualization and pre-processing. For the model building bit, You can clone the repo here. So, let’s cut to the chase and see how can we explain a certain instance using Lime. Understanding Model Behavior in predictions with Lime mainly comprises of two steps: Initialize an explainer Call explain_instance The first step in explaining the model prediction is to create an explainer. We can use Lime Tabular explainer, which is the main explainer used for tabular data. Lime scales and generates new data using locality and computes statistics like mean for numerical data and frequency for categorical data, due to this we need to pass our training data as a parameter. In the second step, we simply need to call explain_instance for the instance in which you need explanations. You can use a different ‘i’ if you wish to understand a different instance. Finally, we can use the explainer to display the explanation for a particular prediction in the Jupyter Notebook. As we make our model complex, its interpretability decreases and vice-versa. A word of advice would be to take care of the trade-off between model complexity and its interpretability. You can optionally save your explanations as HTML file which makes it easier to share. exp.save_to_file(“explanation.html”) Eli5 — Another Library for Model Explainability. I have used it for textual data and it works fine. You can read more on Eli5 here. SHAP — Shapley Additive Explanations as the name suggests tells you how it got the score for an instance in an additive manner. SHAP has not only a generic explainer that works for any model but also a TreeExplainer for tree-based models. It theoretically guarantees consistency and is slower than Lime. Additionally, the computational requirements of exploring all possible feature combinations grow exponentially in SHAP. Lime provides human-readable explanations and is a quick way to analyze the contribution of each feature and hence helps to gain a better insight into a Machine Learning model behavior. Once we understand, why the model predicted in a certain way, we can build trust with the model which is critical for interaction with machine learning. In this post, we used a Random Forest regression model to interpret its prediction on a particular instance. Interestingly, Lime also supports an explainer for images, textual data, and classification problems. You can explore Lime explanations further in more complex models such as Xgboost & LightGBM and compare predictions. Read more on Lime here. Also, here’s an interesting read on different tools for transparency and explainability in AI. I’d love to hear your thoughts about Lime, Machine learning, and Explainable AI in the comments below. If you found this useful and know anyone you think would benefit from this, please feel free to send it their way.
[ { "code": null, "e": 1006, "s": 172, "text": "Why should we trust a machine learning model blindly? Wouldn’t it be wonderful if we can get a better insight into model predictions and improve our decision making? With the advent of explainable AI techniques such as LIME and SHAP, it is no longer a challenge. Nowadays, machine learning models are ubiquitous and becoming a part of our lives more than ever. These models are usually a black box in essence that it’s hard for us to assess the model behavior. From smart speakers with inbuilt conversational agents to personalized recommendation systems, we use them daily, but do we understand why they behave in a certain way? Given their ability to influence our decision, it is of paramount and supreme importance that we should be able to trust them. Explainable AI systems help us understand the inner workings of such models." }, { "code": null, "e": 1033, "s": 1006, "text": "So, What’s Explainable AI?" }, { "code": null, "e": 1337, "s": 1033, "text": "Explainable AI can be summed up as a process to understand the predictions of an ML model. The central idea is to make the model as interpretable as possible which will essentially help in testing its reliability and causality of features. Broadly speaking, there are two dimensions to interpretability:" }, { "code": null, "e": 1400, "s": 1337, "text": "Explainability(Why did it do that?)Transparency(How it works?)" }, { "code": null, "e": 1436, "s": 1400, "text": "Explainability(Why did it do that?)" }, { "code": null, "e": 1464, "s": 1436, "text": "Transparency(How it works?)" }, { "code": null, "e": 1874, "s": 1464, "text": "Typically, explainable AI systems provide an assessment of model input features and identify the features which are driving force of the model. It gives us a sense of control, as we can then decide if we can rely on the predictions of these models. For instance, we would probably trust a flu identification model more if it considers features like temperature, and cough more significant than other symptoms." }, { "code": null, "e": 1961, "s": 1874, "text": "Now that you have an idea of explainable systems, how do we explain model predictions?" }, { "code": null, "e": 2037, "s": 1961, "text": "There are different ways to do that. LIME is one of them. Let’s squeeze it." }, { "code": null, "e": 2356, "s": 2037, "text": "LIME stands for:Local: Approximate locally in the neighborhood of prediction being explained,Interpretable: Explanations produced are human-readable,Model-Agnostic: Works for any model like SVM, Neural networks, etc Explanations: Provides explanations of model predictions.(Local linear explanation of model behaviour)" }, { "code": null, "e": 3036, "s": 2356, "text": "Lime can be used to get more insights into model prediction like explaining why models take a particular decision for an individual observation. It can also be quite useful while selecting between different models. The central idea behind Lime is that it explains locally in the vicinity of the instance being explained by perturbating the different features rather than producing explanations at the entire model level. It does so by fitting a sparse model on the locally dispersed, noise-induced dataset. This helps convert a non-linear problem into a linear one. The indicator variables with the largest coefficients in the model are then returned as the drivers of the score." }, { "code": null, "e": 3096, "s": 3036, "text": "You can simply pip install it or can clone the Github repo:" }, { "code": null, "e": 3140, "s": 3096, "text": "pip install limepip install . (Git version)" }, { "code": null, "e": 3567, "s": 3140, "text": "We will use Lime for explaining predictions of a random forest regressor model on the Diabetes dataset which is inbuilt in sci-kit learn. This post assumes that you already have some knowledge of Python, and Machine Learning. For the sake of simplicity, we will not cover all steps we usually follow in the model building pipeline like visualization and pre-processing. For the model building bit, You can clone the repo here." }, { "code": null, "e": 3652, "s": 3567, "text": "So, let’s cut to the chase and see how can we explain a certain instance using Lime." }, { "code": null, "e": 3737, "s": 3652, "text": "Understanding Model Behavior in predictions with Lime mainly comprises of two steps:" }, { "code": null, "e": 3761, "s": 3737, "text": "Initialize an explainer" }, { "code": null, "e": 3783, "s": 3761, "text": "Call explain_instance" }, { "code": null, "e": 4147, "s": 3783, "text": "The first step in explaining the model prediction is to create an explainer. We can use Lime Tabular explainer, which is the main explainer used for tabular data. Lime scales and generates new data using locality and computes statistics like mean for numerical data and frequency for categorical data, due to this we need to pass our training data as a parameter." }, { "code": null, "e": 4332, "s": 4147, "text": "In the second step, we simply need to call explain_instance for the instance in which you need explanations. You can use a different ‘i’ if you wish to understand a different instance." }, { "code": null, "e": 4446, "s": 4332, "text": "Finally, we can use the explainer to display the explanation for a particular prediction in the Jupyter Notebook." }, { "code": null, "e": 4630, "s": 4446, "text": "As we make our model complex, its interpretability decreases and vice-versa. A word of advice would be to take care of the trade-off between model complexity and its interpretability." }, { "code": null, "e": 4717, "s": 4630, "text": "You can optionally save your explanations as HTML file which makes it easier to share." }, { "code": null, "e": 4754, "s": 4717, "text": "exp.save_to_file(“explanation.html”)" }, { "code": null, "e": 4886, "s": 4754, "text": "Eli5 — Another Library for Model Explainability. I have used it for textual data and it works fine. You can read more on Eli5 here." }, { "code": null, "e": 5310, "s": 4886, "text": "SHAP — Shapley Additive Explanations as the name suggests tells you how it got the score for an instance in an additive manner. SHAP has not only a generic explainer that works for any model but also a TreeExplainer for tree-based models. It theoretically guarantees consistency and is slower than Lime. Additionally, the computational requirements of exploring all possible feature combinations grow exponentially in SHAP." }, { "code": null, "e": 5758, "s": 5310, "text": "Lime provides human-readable explanations and is a quick way to analyze the contribution of each feature and hence helps to gain a better insight into a Machine Learning model behavior. Once we understand, why the model predicted in a certain way, we can build trust with the model which is critical for interaction with machine learning. In this post, we used a Random Forest regression model to interpret its prediction on a particular instance." }, { "code": null, "e": 6096, "s": 5758, "text": "Interestingly, Lime also supports an explainer for images, textual data, and classification problems. You can explore Lime explanations further in more complex models such as Xgboost & LightGBM and compare predictions. Read more on Lime here. Also, here’s an interesting read on different tools for transparency and explainability in AI." } ]
JSF - template tags
Templates in a web application defines a common interface layout and style. For example, a same banner, logo in common header and copyright information in footer. JSF provides following facelet tags to provide a standard web interface layout. ui:insert Used in template file. It defines contents to be placed in a template. ui:define tag can replaced its contents. ui:define Defines the contents to be inserted in a template. ui:include Includes contents of one xhtml page into another xhtml page. ui:composition Loads a template using template attribute. It can also define a group of components to be inserted in xhtml page. Creating template for a web application is a step-by-step procedure. Following are the steps to create a sample template. Use ui:composition tag to define a default content of Header section. <ui:composition> <h1>Default Header</h1> </ui:composition> Use ui:composition tag to define a default content of Footer section. <ui:composition> <h1>Default Footer</h1> </ui:composition> Use ui:composition tag to define a default content of Content section. <ui:composition> <h1>Default Contents</h1> </ui:composition> Use ui:insert and ui:include tag to include header/footer and content file in template file. Name each section in ui:insert tag. name attribute of ui:insert tag will be used to replace the contents of the corresponding section. <h:body> <ui:insert name = "header" > <ui:include src = "header.xhtml" /> </ui:insert> <ui:insert name = "content" > <ui:include src = "contents.xhtml" /> </ui:insert> <ui:insert name = "footer" > <ui:include src = "footer.xhtml" /> </ui:insert> </h:body> Load common.xhtml, a template using ui:composition tag in any xhtml page. <h:body> <ui:composition template = "common.xhtml"> </h:body> Load common.xhtml, a template using ui:composition tag in any xhtml page. Use ui:define tag to override default values. <h:body> <ui:composition template = "templates/common.xhtml"> <ui:define name = "content"> <h:link value = "Page 1" outcome = "page1" /> &nbsp; <h:link value = "Page 2" outcome = "page2" /> </ui:define> </ui:composition> </h:body> Let us create a test JSF application to test the template tags in JSF. <?xml version = "1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:ui = "http://java.sun.com/jsf/facelets"> <body> <ui:composition> <h1>Default Header</h1> </ui:composition> </body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:ui = "http://java.sun.com/jsf/facelets"> <body> <ui:composition> <h1>Default Footer</h1> </ui:composition> </body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:ui = "http://java.sun.com/jsf/facelets"> <body> <ui:composition> <h1>Default Content</h1> </ui:composition> </body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> <h:head></h:head> <h:body> <div style = "border-width:2px; border-color:green; border-style:solid;"> <ui:insert name = "header" > <ui:include src = "/templates/header.xhtml" /> </ui:insert> </div> <br/> <div style = "border-width:2px; border-color:black; border-style:solid;"> <ui:insert name = "content" > <ui:include src = "/templates/contents.xhtml" /> </ui:insert> </div> <br/> <div style = "border-width:2px; border-color:red; border-style:solid;"> <ui:insert name = "footer" > <ui:include src = "/templates/footer.xhtml" /> </ui:insert> </div> </h:body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> <h:body> <ui:composition template = "templates/common.xhtml"> <ui:define name = "header"> <h2>Page1 header</h2> </ui:define> <ui:define name = "content"> <h2>Page1 content</h2> <h:link value = "Back To Home" outcome = "home" /> </ui:define> <ui:define name = "footer"> <h2>Page1 Footer</h2> </ui:define> </ui:composition> </h:body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> <h:body> <ui:composition template = "templates/common.xhtml"> <ui:define name = "header"> <h2>Page2 header</h2> </ui:define> <ui:define name = "content"> <h2>Page2 content</h2> <h:link value = "Back To Home" outcome = "home" /> </ui:define> <ui:define name = "footer"> <h2>Page2 Footer</h2> </ui:define> </ui:composition> </h:body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> <h:body> <ui:composition template = "templates/common.xhtml"> <ui:define name = "content"> <br/><br/> <h:link value = "Page 1" outcome = "page1" /> <h:link value = "Page 2" outcome = "page2" /> <br/><br/> </ui:define> </ui:composition> </h:body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. Click Page1 link and you'll see the following result. Or Click Page2 link and you'll see the following result. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2195, "s": 1952, "text": "Templates in a web application defines a common interface layout and style. For example, a same banner, logo in common header and copyright information in footer. JSF provides following facelet tags to provide a standard web interface layout." }, { "code": null, "e": 2205, "s": 2195, "text": "ui:insert" }, { "code": null, "e": 2317, "s": 2205, "text": "Used in template file. It defines contents to be placed in a template. ui:define tag can replaced its contents." }, { "code": null, "e": 2327, "s": 2317, "text": "ui:define" }, { "code": null, "e": 2378, "s": 2327, "text": "Defines the contents to be inserted in a template." }, { "code": null, "e": 2389, "s": 2378, "text": "ui:include" }, { "code": null, "e": 2450, "s": 2389, "text": "Includes contents of one xhtml page into another xhtml page." }, { "code": null, "e": 2465, "s": 2450, "text": "ui:composition" }, { "code": null, "e": 2579, "s": 2465, "text": "Loads a template using template attribute. It can also define a group of components to be inserted in xhtml page." }, { "code": null, "e": 2701, "s": 2579, "text": "Creating template for a web application is a step-by-step procedure. Following are the steps to create a sample template." }, { "code": null, "e": 2771, "s": 2701, "text": "Use ui:composition tag to define a default content of Header section." }, { "code": null, "e": 2836, "s": 2771, "text": "<ui:composition> \n <h1>Default Header</h1>\t\n</ui:composition>\t" }, { "code": null, "e": 2906, "s": 2836, "text": "Use ui:composition tag to define a default content of Footer section." }, { "code": null, "e": 2971, "s": 2906, "text": "<ui:composition> \n <h1>Default Footer</h1>\t\n</ui:composition>\t" }, { "code": null, "e": 3042, "s": 2971, "text": "Use ui:composition tag to define a default content of Content section." }, { "code": null, "e": 3109, "s": 3042, "text": "<ui:composition> \n <h1>Default Contents</h1>\t\n</ui:composition>\t" }, { "code": null, "e": 3238, "s": 3109, "text": "Use ui:insert and ui:include tag to include header/footer and content file in template file. Name each section in ui:insert tag." }, { "code": null, "e": 3337, "s": 3238, "text": "name attribute of ui:insert tag will be used to replace the contents of the corresponding section." }, { "code": null, "e": 3643, "s": 3337, "text": "<h:body> \n <ui:insert name = \"header\" >\n <ui:include src = \"header.xhtml\" />\n </ui:insert> \n \n <ui:insert name = \"content\" >\n <ui:include src = \"contents.xhtml\" />\n </ui:insert> \n \n <ui:insert name = \"footer\" >\n <ui:include src = \"footer.xhtml\" />\n </ui:insert>\n</h:body>" }, { "code": null, "e": 3717, "s": 3643, "text": "Load common.xhtml, a template using ui:composition tag in any xhtml page." }, { "code": null, "e": 3783, "s": 3717, "text": "<h:body>\n <ui:composition template = \"common.xhtml\">\t\n</h:body>" }, { "code": null, "e": 3903, "s": 3783, "text": "Load common.xhtml, a template using ui:composition tag in any xhtml page. Use ui:define tag to override default values." }, { "code": null, "e": 4187, "s": 3903, "text": "<h:body>\n <ui:composition template = \"templates/common.xhtml\">\t\n <ui:define name = \"content\">\t\t\t\t\n <h:link value = \"Page 1\" outcome = \"page1\" />\n &nbsp;\n <h:link value = \"Page 2\" outcome = \"page2\" />\t\t\t\n </ui:define>\n </ui:composition>\n</h:body>" }, { "code": null, "e": 4258, "s": 4187, "text": "Let us create a test JSF application to test the template tags in JSF." }, { "code": null, "e": 4636, "s": 4258, "text": "<?xml version = \"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <body>\n <ui:composition> \n <h1>Default Header</h1>\n </ui:composition>\t\n </body>\n</html>" }, { "code": null, "e": 5016, "s": 4636, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <body>\n <ui:composition> \n <h1>Default Footer</h1>\n </ui:composition>\t\n </body>\n</html>" }, { "code": null, "e": 5397, "s": 5016, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <body>\n <ui:composition> \n <h1>Default Content</h1>\n </ui:composition>\t\n </body>\n</html>" }, { "code": null, "e": 6450, "s": 5397, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\"> \n \n <h:head></h:head>\n <h:body> \n <div style = \"border-width:2px; border-color:green; border-style:solid;\">\n <ui:insert name = \"header\" >\n <ui:include src = \"/templates/header.xhtml\" />\n </ui:insert> \n </div>\n <br/>\n \n <div style = \"border-width:2px; border-color:black; border-style:solid;\">\n <ui:insert name = \"content\" >\n <ui:include src = \"/templates/contents.xhtml\" />\n </ui:insert> \n </div>\n <br/>\n \n <div style = \"border-width:2px; border-color:red; border-style:solid;\">\n <ui:insert name = \"footer\" >\n <ui:include src = \"/templates/footer.xhtml\" />\n </ui:insert>\n </div>\n \n </h:body>\n</html>" }, { "code": null, "e": 7259, "s": 6450, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <h:body> \n <ui:composition template = \"templates/common.xhtml\">\n <ui:define name = \"header\">\n <h2>Page1 header</h2>\n </ui:define>\t\t\t\n \n <ui:define name = \"content\">\n <h2>Page1 content</h2>\n <h:link value = \"Back To Home\" outcome = \"home\" />\n </ui:define> \n \n <ui:define name = \"footer\">\n <h2>Page1 Footer</h2>\n </ui:define>\t\t\t\n </ui:composition> \n \n </h:body> \n</html>\t" }, { "code": null, "e": 8068, "s": 7259, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <h:body> \n <ui:composition template = \"templates/common.xhtml\">\n <ui:define name = \"header\">\n <h2>Page2 header</h2>\n </ui:define>\t\t\t\n \n <ui:define name = \"content\">\n <h2>Page2 content</h2>\n <h:link value = \"Back To Home\" outcome = \"home\" />\n </ui:define> \n \n <ui:define name = \"footer\">\n <h2>Page2 Footer</h2>\n </ui:define>\t\t\t\n </ui:composition> \n \n </h:body> \n</html>\t" }, { "code": null, "e": 8734, "s": 8068, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <h:body>\n <ui:composition template = \"templates/common.xhtml\">\t\n <ui:define name = \"content\">\t\t\t\t\n <br/><br/>\n <h:link value = \"Page 1\" outcome = \"page1\" />\n <h:link value = \"Page 2\" outcome = \"page2\" />\t\t\t\n <br/><br/>\n </ui:define>\n </ui:composition>\n \n </h:body>\n</html>\t" }, { "code": null, "e": 8950, "s": 8734, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 9004, "s": 8950, "text": "Click Page1 link and you'll see the following result." }, { "code": null, "e": 9061, "s": 9004, "text": "Or Click Page2 link and you'll see the following result." }, { "code": null, "e": 9096, "s": 9061, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9111, "s": 9096, "text": " Chaand Sheikh" }, { "code": null, "e": 9118, "s": 9111, "text": " Print" }, { "code": null, "e": 9129, "s": 9118, "text": " Add Notes" } ]
Count subsequences having odd Bitwise OR values in an array - GeeksforGeeks
11 Feb, 2022 Given an array arr[] consisting of N positive integers, the task is to find the number of subsequences from the given array whose Bitwise OR value is odd. Examples: Input: arr = [2, 4, 1]Output: 4Explanation: Subsequences with odd Bitwise OR values are {1}, {2, 1}, {4, 1}, {2, 4, 1} Input: arr = [1, 3, 4]Output: 6 Naive Approach: The simplest approach to solve the problem is to generate all the subsequences of the given array and for each subsequence, check if its Bitwise OR value is odd or not. If it is odd, then increase the count by one. After checking for all subsequences, print the count obtained.Time Complexity: Auxiliary Space: Efficient Approach: Given problem can be solved by observing that for a subsequence to have an odd Bitwise OR value at least one element of the subsequence should be odd. Therefore at least one element in the subsequence should have the least significant digit equal to 1. Follow the steps below to solve this problem: Store the count of even and odd elements present in the array arr[] in even and odd variables respectively. Traverse the array A[] using the variable iIf the value of A[i] is odd, increase the value of odd by 1.Otherwise, increase the value of even by 1. If the value of A[i] is odd, increase the value of odd by 1. Otherwise, increase the value of even by 1. Total combinations with at least one odd element and any number of even elements can be given by: [2^(odd elements) – 1] * 2^(even elements). Since at least one odd element is needed so empty set of combinations of 1 is excluded Below is the implementation of the approach: C++ Java Python3 C# Javascript // C++ implementation for the above approach#include <bits/stdc++.h> using namespace std; // Function to count the subsequences// having odd bitwise OR valueint countSubsequences(vector<int> arr){ // Stores count of odd elements int odd = 0; // Stores count of even elements int even = 0; // Traverse the array arr[] for (int x : arr) { // If element is odd if (x & 1) odd++; else even++; } // Return the final answer return ((1 << odd) - 1) * (1 << even);} // Driver Codeint main(){ // Given array arr[] vector<int> arr = {2, 4, 1}; cout << countSubsequences(arr);} // Java implementation for the above approachimport java.io.*; class GFG { // Function to count the subsequences // having odd bitwise OR value static int countSubsequences(int arr[]) { // Stores count of odd elements int odd = 0; // Stores count of even elements int even = 0; // Traverse the array arr[] for (int i = 0; i < arr.length; i++) { // If element is odd if ((arr[i] & 1) != 0) odd++; else even++; } // Return the final answer return ((1 << odd) - 1) * (1 << even); } // Driver Code public static void main (String[] args) { // Given array arr[] int arr[] = {2, 4, 1}; System.out.println(countSubsequences(arr)); }} // This code is contributed by Dharanendra L V. # Python3 implementation for the above approach # Function to count the subsequences# having odd bitwise OR valuedef countSubsequences(arr) : # Stores count of odd elements odd = 0; # Stores count of even elements even = 0; # Traverse the array arr[] for x in arr: # If element is odd if (x & 1) : odd += 1; else : even += 1; # Return the final answer return ((1 << odd) - 1) * (1 << even); # Driver Codeif __name__ == "__main__" : # Given array arr[] arr = [2, 4, 1]; print(countSubsequences(arr)); # This code is contributed by AnkThon // Java implementation for the above approachusing System; class GFG { // Function to count the subsequences // having odd bitwise OR value static int countSubsequences(int []arr) { // Stores count of odd elements int odd = 0; // Stores count of even elements int even = 0; // Traverse the array arr[] for (int i = 0; i < arr.Length; i++) { // If element is odd if ((arr[i] & 1) != 0) odd++; else even++; } // Return the final answer return ((1 << odd) - 1) * (1 << even); } // Driver Code public static void Main (String[] args) { // Given array arr[] int []arr = {2, 4, 1}; Console.Write(countSubsequences(arr)); }} // This code is contributed by shivanisinghss2110 <script> // JavaScript Program to implement // the above approach // Function to count the subsequences// having odd bitwise OR valuefunction countSubsequences( arr){ // Stores count of odd elements let odd = 0; // Stores count of even elements let even = 0; // Traverse the array arr[] for (let x of arr) { // If element is odd if (x & 1) odd++; else even++; } // Return the final answer return ((1 << odd) - 1) * (1 << even);} // Driver Code // Given array arr[] let arr = [2, 4, 1]; document.write(countSubsequences(arr)); // This code is contributed by Potta Lokesh </script> 4 Time Complexity: Auxiliary Space: dharanendralv23 shivanisinghss2110 lokeshpotta20 ankthon avtarkumar719 Bitwise-OR Arrays Bit Magic Combinatorial Arrays Bit Magic Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer Cyclic Redundancy Check and Modulo-2 Division
[ { "code": null, "e": 24405, "s": 24377, "text": "\n11 Feb, 2022" }, { "code": null, "e": 24560, "s": 24405, "text": "Given an array arr[] consisting of N positive integers, the task is to find the number of subsequences from the given array whose Bitwise OR value is odd." }, { "code": null, "e": 24570, "s": 24560, "text": "Examples:" }, { "code": null, "e": 24689, "s": 24570, "text": "Input: arr = [2, 4, 1]Output: 4Explanation: Subsequences with odd Bitwise OR values are {1}, {2, 1}, {4, 1}, {2, 4, 1}" }, { "code": null, "e": 24721, "s": 24689, "text": "Input: arr = [1, 3, 4]Output: 6" }, { "code": null, "e": 25049, "s": 24721, "text": "Naive Approach: The simplest approach to solve the problem is to generate all the subsequences of the given array and for each subsequence, check if its Bitwise OR value is odd or not. If it is odd, then increase the count by one. After checking for all subsequences, print the count obtained.Time Complexity: Auxiliary Space: " }, { "code": null, "e": 25368, "s": 25049, "text": "Efficient Approach: Given problem can be solved by observing that for a subsequence to have an odd Bitwise OR value at least one element of the subsequence should be odd. Therefore at least one element in the subsequence should have the least significant digit equal to 1. Follow the steps below to solve this problem:" }, { "code": null, "e": 25476, "s": 25368, "text": "Store the count of even and odd elements present in the array arr[] in even and odd variables respectively." }, { "code": null, "e": 25623, "s": 25476, "text": "Traverse the array A[] using the variable iIf the value of A[i] is odd, increase the value of odd by 1.Otherwise, increase the value of even by 1." }, { "code": null, "e": 25684, "s": 25623, "text": "If the value of A[i] is odd, increase the value of odd by 1." }, { "code": null, "e": 25728, "s": 25684, "text": "Otherwise, increase the value of even by 1." }, { "code": null, "e": 25957, "s": 25728, "text": "Total combinations with at least one odd element and any number of even elements can be given by: [2^(odd elements) – 1] * 2^(even elements). Since at least one odd element is needed so empty set of combinations of 1 is excluded" }, { "code": null, "e": 26002, "s": 25957, "text": "Below is the implementation of the approach:" }, { "code": null, "e": 26006, "s": 26002, "text": "C++" }, { "code": null, "e": 26011, "s": 26006, "text": "Java" }, { "code": null, "e": 26019, "s": 26011, "text": "Python3" }, { "code": null, "e": 26022, "s": 26019, "text": "C#" }, { "code": null, "e": 26033, "s": 26022, "text": "Javascript" }, { "code": "// C++ implementation for the above approach#include <bits/stdc++.h> using namespace std; // Function to count the subsequences// having odd bitwise OR valueint countSubsequences(vector<int> arr){ // Stores count of odd elements int odd = 0; // Stores count of even elements int even = 0; // Traverse the array arr[] for (int x : arr) { // If element is odd if (x & 1) odd++; else even++; } // Return the final answer return ((1 << odd) - 1) * (1 << even);} // Driver Codeint main(){ // Given array arr[] vector<int> arr = {2, 4, 1}; cout << countSubsequences(arr);}", "e": 26699, "s": 26033, "text": null }, { "code": "// Java implementation for the above approachimport java.io.*; class GFG { // Function to count the subsequences // having odd bitwise OR value static int countSubsequences(int arr[]) { // Stores count of odd elements int odd = 0; // Stores count of even elements int even = 0; // Traverse the array arr[] for (int i = 0; i < arr.length; i++) { // If element is odd if ((arr[i] & 1) != 0) odd++; else even++; } // Return the final answer return ((1 << odd) - 1) * (1 << even); } // Driver Code public static void main (String[] args) { // Given array arr[] int arr[] = {2, 4, 1}; System.out.println(countSubsequences(arr)); }} // This code is contributed by Dharanendra L V.", "e": 27582, "s": 26699, "text": null }, { "code": "# Python3 implementation for the above approach # Function to count the subsequences# having odd bitwise OR valuedef countSubsequences(arr) : # Stores count of odd elements odd = 0; # Stores count of even elements even = 0; # Traverse the array arr[] for x in arr: # If element is odd if (x & 1) : odd += 1; else : even += 1; # Return the final answer return ((1 << odd) - 1) * (1 << even); # Driver Codeif __name__ == \"__main__\" : # Given array arr[] arr = [2, 4, 1]; print(countSubsequences(arr)); # This code is contributed by AnkThon", "e": 28218, "s": 27582, "text": null }, { "code": "// Java implementation for the above approachusing System; class GFG { // Function to count the subsequences // having odd bitwise OR value static int countSubsequences(int []arr) { // Stores count of odd elements int odd = 0; // Stores count of even elements int even = 0; // Traverse the array arr[] for (int i = 0; i < arr.Length; i++) { // If element is odd if ((arr[i] & 1) != 0) odd++; else even++; } // Return the final answer return ((1 << odd) - 1) * (1 << even); } // Driver Code public static void Main (String[] args) { // Given array arr[] int []arr = {2, 4, 1}; Console.Write(countSubsequences(arr)); }} // This code is contributed by shivanisinghss2110", "e": 29094, "s": 28218, "text": null }, { "code": " <script> // JavaScript Program to implement // the above approach // Function to count the subsequences// having odd bitwise OR valuefunction countSubsequences( arr){ // Stores count of odd elements let odd = 0; // Stores count of even elements let even = 0; // Traverse the array arr[] for (let x of arr) { // If element is odd if (x & 1) odd++; else even++; } // Return the final answer return ((1 << odd) - 1) * (1 << even);} // Driver Code // Given array arr[] let arr = [2, 4, 1]; document.write(countSubsequences(arr)); // This code is contributed by Potta Lokesh </script>", "e": 29802, "s": 29094, "text": null }, { "code": null, "e": 29807, "s": 29805, "text": "4" }, { "code": null, "e": 29844, "s": 29809, "text": "Time Complexity: Auxiliary Space: " }, { "code": null, "e": 29862, "s": 29846, "text": "dharanendralv23" }, { "code": null, "e": 29881, "s": 29862, "text": "shivanisinghss2110" }, { "code": null, "e": 29895, "s": 29881, "text": "lokeshpotta20" }, { "code": null, "e": 29903, "s": 29895, "text": "ankthon" }, { "code": null, "e": 29917, "s": 29903, "text": "avtarkumar719" }, { "code": null, "e": 29928, "s": 29917, "text": "Bitwise-OR" }, { "code": null, "e": 29935, "s": 29928, "text": "Arrays" }, { "code": null, "e": 29945, "s": 29935, "text": "Bit Magic" }, { "code": null, "e": 29959, "s": 29945, "text": "Combinatorial" }, { "code": null, "e": 29966, "s": 29959, "text": "Arrays" }, { "code": null, "e": 29976, "s": 29966, "text": "Bit Magic" }, { "code": null, "e": 29990, "s": 29976, "text": "Combinatorial" }, { "code": null, "e": 30088, "s": 29990, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30097, "s": 30088, "text": "Comments" }, { "code": null, "e": 30110, "s": 30097, "text": "Old Comments" }, { "code": null, "e": 30131, "s": 30110, "text": "Next Greater Element" }, { "code": null, "e": 30156, "s": 30131, "text": "Window Sliding Technique" }, { "code": null, "e": 30183, "s": 30156, "text": "Count pairs with given sum" }, { "code": null, "e": 30232, "s": 30183, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30270, "s": 30232, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30297, "s": 30270, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 30343, "s": 30297, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 30411, "s": 30343, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 30440, "s": 30411, "text": "Count set bits in an integer" } ]
Calculate the total fine to be collected - GeeksforGeeks
31 Mar, 2021 Given a date and an array of integer containing the numbers of the cars traveling on that date(an integer), the task is to calculate the total fine collected based on the following rules: Odd numbered cars can travel on only odd dates. Even numbered cars on only even dates. Otherwise a car would be fined 250 Rs. Examples: Input: car_num[] = {3, 4, 1, 2}, date = 15 Output: 500 Car with numbers '4' and '2' will be fined 250 each. Input: car_num[] = {1, 2, 3} , date = 16 Output: 500 Car with numbers '1' and '3' will be fined 250 each. Approach: Start traversing the given array.Check if the current car number and date doesn’t match i.e. one is even and other is odd or vice-versa.If not matched charge the fine on that car number. Else, not.Print the total fine. Start traversing the given array. Check if the current car number and date doesn’t match i.e. one is even and other is odd or vice-versa. If not matched charge the fine on that car number. Else, not. Print the total fine. Below is the implementation of above approach: C++ Java Python 3 C# PHP Javascript // C++ implementation to calculate// the total fine collected#include <bits/stdc++.h>using namespace std; // function to calculate the total fine collectedint totFine(int car_num[], int n, int date, int fine){ int tot_fine = 0; // traverse the array elements for (int i = 0; i < n; i++) // if both car no and date are odd or // both are even, then statement // evaluates to true if (((car_num[i] ^ date) & 1) == 1) tot_fine += fine; // required total fine return tot_fine;} // Driver program to test aboveint main(){ int car_num[] = { 3, 4, 1, 2 }; int n = sizeof(car_num) / sizeof(car_num[0]); int date = 15, fine = 250; cout << totFine(car_num, n, date, fine); return 0;} // Java implementation to calculate// the total fine collectedclass GFG{ // function to calculate// the total fine collectedstatic int totFine(int car_num[], int n, int date, int fine){int tot_fine = 0; // traverse the array elementsfor (int i = 0; i < n; i++) // if both car no and date // are odd or both are even, // then statement evaluates to true if (((car_num[i] ^ date) & 1) == 1) tot_fine += fine; // required total finereturn tot_fine;} // Driver Codepublic static void main(String[] args){ int car_num[] = { 3, 4, 1, 2 }; int n = car_num.length; int date = 15, fine = 250; System.out.println(totFine(car_num, n, date, fine));}} // This code is contributed// by ChitraNayal # Python 3 program to calculate# the total fine collected # function to calculate the total fine collecteddef totFine(car_num, n, date, fine) : tot_fine = 0 # traverse the array elements for i in range(n) : # if both car no and date are odd or # both are even, then statement # evaluates to true if (((car_num[i] ^ date) & 1) == 1 ): tot_fine += fine # required total fine return tot_fine # Driver Programif __name__ == "__main__" : car_num = [ 3, 4, 1, 2 ] n = len(car_num) date, fine = 15, 250 # function calling print(totFine(car_num, n, date, fine)) # This code is contributed by ANKITRAI1 // C# implementation to calculate// the total fine collectedusing System; class GFG{ // function to calculate the// total fine collectedstatic int totFine(int[] car_num, int n, int date, int fine){int tot_fine = 0; // traverse the array elementsfor (int i = 0; i < n; i++) // if both car no and date // are odd or both are even, // then statement evaluates to true if (((car_num[i] ^ date) & 1) == 1) tot_fine += fine; // required total finereturn tot_fine;} // Driver Codepublic static void Main(){ int[] car_num = { 3, 4, 1, 2 }; int n = car_num.Length; int date = 15, fine = 250; Console.Write(totFine(car_num, n, date, fine));}} // This code is contributed// by ChitraNayal <?php// PHP implementation to calculate// the total fine collected // function to calculate the// total fine collectedfunction totFine(&$car_num, $n, $date, $fine){ $tot_fine = 0; // traverse the array elements for ($i = 0; $i < $n; $i++) // if both car no and date // are odd or both are even, // then statement evaluates // to true if ((($car_num[$i] ^ $date) & 1) == 1) $tot_fine += $fine; // required total fine return $tot_fine;} // Driver Code$car_num = array(3, 4, 1, 2 );$n = sizeof($car_num);$date = 15;$fine = 250; echo totFine($car_num, $n, $date, $fine); // This code is contributed// by ChitraNayal?> <script> // Javascript implementation to calculate// the total fine collected // function to calculate the total fine collectedfunction totFine(car_num, n, date, fine){ let tot_fine = 0; // traverse the array elements for (let i = 0; i < n; i++) // if both car no and date are odd or // both are even, then statement // evaluates to true if (((car_num[i] ^ date) & 1) == 1) tot_fine += fine; // required total fine return tot_fine;} // Driver program to test above let car_num = [ 3, 4, 1, 2 ]; let n = car_num.length; let date = 15, fine = 250; document.write(totFine(car_num, n, date, fine)); //This code is contributed by Mayank Tyagi</script> 500 Source:https://www.geeksforgeeks.org/microsoft-interview-experience-for-internship/ ankthon ukasp mayanktyagi1709 BIT Microsoft Arrays Bit Magic Microsoft Arrays Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Reversal algorithm for array rotation Move all negative numbers to beginning and positive to end with constant extra space Program to find sum of elements in a given array Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer Cyclic Redundancy Check and Modulo-2 Division
[ { "code": null, "e": 24820, "s": 24792, "text": "\n31 Mar, 2021" }, { "code": null, "e": 25010, "s": 24820, "text": "Given a date and an array of integer containing the numbers of the cars traveling on that date(an integer), the task is to calculate the total fine collected based on the following rules: " }, { "code": null, "e": 25058, "s": 25010, "text": "Odd numbered cars can travel on only odd dates." }, { "code": null, "e": 25097, "s": 25058, "text": "Even numbered cars on only even dates." }, { "code": null, "e": 25136, "s": 25097, "text": "Otherwise a car would be fined 250 Rs." }, { "code": null, "e": 25148, "s": 25136, "text": "Examples: " }, { "code": null, "e": 25363, "s": 25148, "text": "Input: car_num[] = {3, 4, 1, 2}, date = 15\nOutput: 500\nCar with numbers '4' and '2' will be fined\n250 each.\n\nInput: car_num[] = {1, 2, 3} , date = 16\nOutput: 500\nCar with numbers '1' and '3' will be fined\n250 each." }, { "code": null, "e": 25377, "s": 25365, "text": "Approach: " }, { "code": null, "e": 25596, "s": 25377, "text": "Start traversing the given array.Check if the current car number and date doesn’t match i.e. one is even and other is odd or vice-versa.If not matched charge the fine on that car number. Else, not.Print the total fine." }, { "code": null, "e": 25630, "s": 25596, "text": "Start traversing the given array." }, { "code": null, "e": 25734, "s": 25630, "text": "Check if the current car number and date doesn’t match i.e. one is even and other is odd or vice-versa." }, { "code": null, "e": 25796, "s": 25734, "text": "If not matched charge the fine on that car number. Else, not." }, { "code": null, "e": 25818, "s": 25796, "text": "Print the total fine." }, { "code": null, "e": 25867, "s": 25818, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 25871, "s": 25867, "text": "C++" }, { "code": null, "e": 25876, "s": 25871, "text": "Java" }, { "code": null, "e": 25885, "s": 25876, "text": "Python 3" }, { "code": null, "e": 25888, "s": 25885, "text": "C#" }, { "code": null, "e": 25892, "s": 25888, "text": "PHP" }, { "code": null, "e": 25903, "s": 25892, "text": "Javascript" }, { "code": "// C++ implementation to calculate// the total fine collected#include <bits/stdc++.h>using namespace std; // function to calculate the total fine collectedint totFine(int car_num[], int n, int date, int fine){ int tot_fine = 0; // traverse the array elements for (int i = 0; i < n; i++) // if both car no and date are odd or // both are even, then statement // evaluates to true if (((car_num[i] ^ date) & 1) == 1) tot_fine += fine; // required total fine return tot_fine;} // Driver program to test aboveint main(){ int car_num[] = { 3, 4, 1, 2 }; int n = sizeof(car_num) / sizeof(car_num[0]); int date = 15, fine = 250; cout << totFine(car_num, n, date, fine); return 0;}", "e": 26651, "s": 25903, "text": null }, { "code": "// Java implementation to calculate// the total fine collectedclass GFG{ // function to calculate// the total fine collectedstatic int totFine(int car_num[], int n, int date, int fine){int tot_fine = 0; // traverse the array elementsfor (int i = 0; i < n; i++) // if both car no and date // are odd or both are even, // then statement evaluates to true if (((car_num[i] ^ date) & 1) == 1) tot_fine += fine; // required total finereturn tot_fine;} // Driver Codepublic static void main(String[] args){ int car_num[] = { 3, 4, 1, 2 }; int n = car_num.length; int date = 15, fine = 250; System.out.println(totFine(car_num, n, date, fine));}} // This code is contributed// by ChitraNayal", "e": 27416, "s": 26651, "text": null }, { "code": "# Python 3 program to calculate# the total fine collected # function to calculate the total fine collecteddef totFine(car_num, n, date, fine) : tot_fine = 0 # traverse the array elements for i in range(n) : # if both car no and date are odd or # both are even, then statement # evaluates to true if (((car_num[i] ^ date) & 1) == 1 ): tot_fine += fine # required total fine return tot_fine # Driver Programif __name__ == \"__main__\" : car_num = [ 3, 4, 1, 2 ] n = len(car_num) date, fine = 15, 250 # function calling print(totFine(car_num, n, date, fine)) # This code is contributed by ANKITRAI1", "e": 28105, "s": 27416, "text": null }, { "code": "// C# implementation to calculate// the total fine collectedusing System; class GFG{ // function to calculate the// total fine collectedstatic int totFine(int[] car_num, int n, int date, int fine){int tot_fine = 0; // traverse the array elementsfor (int i = 0; i < n; i++) // if both car no and date // are odd or both are even, // then statement evaluates to true if (((car_num[i] ^ date) & 1) == 1) tot_fine += fine; // required total finereturn tot_fine;} // Driver Codepublic static void Main(){ int[] car_num = { 3, 4, 1, 2 }; int n = car_num.Length; int date = 15, fine = 250; Console.Write(totFine(car_num, n, date, fine));}} // This code is contributed// by ChitraNayal", "e": 28859, "s": 28105, "text": null }, { "code": "<?php// PHP implementation to calculate// the total fine collected // function to calculate the// total fine collectedfunction totFine(&$car_num, $n, $date, $fine){ $tot_fine = 0; // traverse the array elements for ($i = 0; $i < $n; $i++) // if both car no and date // are odd or both are even, // then statement evaluates // to true if ((($car_num[$i] ^ $date) & 1) == 1) $tot_fine += $fine; // required total fine return $tot_fine;} // Driver Code$car_num = array(3, 4, 1, 2 );$n = sizeof($car_num);$date = 15;$fine = 250; echo totFine($car_num, $n, $date, $fine); // This code is contributed// by ChitraNayal?>", "e": 29579, "s": 28859, "text": null }, { "code": "<script> // Javascript implementation to calculate// the total fine collected // function to calculate the total fine collectedfunction totFine(car_num, n, date, fine){ let tot_fine = 0; // traverse the array elements for (let i = 0; i < n; i++) // if both car no and date are odd or // both are even, then statement // evaluates to true if (((car_num[i] ^ date) & 1) == 1) tot_fine += fine; // required total fine return tot_fine;} // Driver program to test above let car_num = [ 3, 4, 1, 2 ]; let n = car_num.length; let date = 15, fine = 250; document.write(totFine(car_num, n, date, fine)); //This code is contributed by Mayank Tyagi</script>", "e": 30297, "s": 29579, "text": null }, { "code": null, "e": 30301, "s": 30297, "text": "500" }, { "code": null, "e": 30389, "s": 30303, "text": "Source:https://www.geeksforgeeks.org/microsoft-interview-experience-for-internship/ " }, { "code": null, "e": 30397, "s": 30389, "text": "ankthon" }, { "code": null, "e": 30403, "s": 30397, "text": "ukasp" }, { "code": null, "e": 30419, "s": 30403, "text": "mayanktyagi1709" }, { "code": null, "e": 30423, "s": 30419, "text": "BIT" }, { "code": null, "e": 30433, "s": 30423, "text": "Microsoft" }, { "code": null, "e": 30440, "s": 30433, "text": "Arrays" }, { "code": null, "e": 30450, "s": 30440, "text": "Bit Magic" }, { "code": null, "e": 30460, "s": 30450, "text": "Microsoft" }, { "code": null, "e": 30467, "s": 30460, "text": "Arrays" }, { "code": null, "e": 30477, "s": 30467, "text": "Bit Magic" }, { "code": null, "e": 30575, "s": 30477, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30600, "s": 30575, "text": "Window Sliding Technique" }, { "code": null, "e": 30620, "s": 30600, "text": "Trapping Rain Water" }, { "code": null, "e": 30658, "s": 30620, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30743, "s": 30658, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 30792, "s": 30743, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30819, "s": 30792, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 30865, "s": 30819, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 30933, "s": 30865, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 30962, "s": 30933, "text": "Count set bits in an integer" } ]
Building a Recommendation System with Spark ML and Elasticsearch | by Lijo Abraham | Towards Data Science
While working in search teams of different product companies, there was always a constant demand for building a recommendation system for users. We have build with popular search engines like Elasticsearch, SOLR, and tried perfecting the search relevance. But there was always a limit when it comes to doing search relevance and creating recommendation system with just search engines. I was always amazed by companies like Amazon and Netflix providing recommendations based on our interest. So by using Apache spark machine learning capabilities along with elasticsearch, we are going to build a recommendation system. As in the picture above, if User 1 likes Item A, Item B, and Item C and User 2 likes Item B and Item C, there is a high probability that User 2 also likes Item A and can recommend Item A to User 2. In the field of recommendations system, there are mainly three techniques used for providing recommendations. Collaborative filtering Content-based Hybrid technique We will be using the Collaborative filtering technique in Pyspark for creating a recommendation system. Apache Spark ML implements alternating least squares (ALS) for collaborative filtering, a very popular algorithm for making recommendations. ALS is a matrix factorization algorithm that uses Alternating Least Squares with Weighted-Lambda-Regularization (ALS-WR). The main problem with Spark ALS is that it will only recommend top products for a specific user (user-products model) and top users for a specific product (product-users model). Calculating an all-pairs similarity is not scaling to big product catalogues. The growing number of combinations O(n2) leads very quickly to overly costly shuffle operations and infeasible computer times. For calculating the Item-Item similarity, we are building an item-item model using the similarity of item factors from the ALS model using spark and elasticsearch. The ALS algorithm essentially factorizes two matrix — one is userFeatures and the other is itemFeatures matrix. We are doing cosine similarity on the itemFeatures rank matrix to find item-item similarity. The dataset contains mainly two types of data from amazon.com. One is metadata, which contains the product metadata and the other is rating data of different products respective of users. Note: The dataset can be downloaded from this site. The spark version used is 2.4.6 and elasticsearch version is 7.9.0 Load the product dataset into Spark.Use Spark DataFrame operations to clean up the dataset.Load the cleaned data into Elasticsearch.Using Spark MLlib, train a collaborative filtering recommendation model from the rating data.Save the resulting model data into Elasticsearch.Using Elasticsearch queries, generate recommendations. Load the product dataset into Spark. Use Spark DataFrame operations to clean up the dataset. Load the cleaned data into Elasticsearch. Using Spark MLlib, train a collaborative filtering recommendation model from the rating data. Save the resulting model data into Elasticsearch. Using Elasticsearch queries, generate recommendations. The below code has been used for reading the product data and convert them to a spark dataframe. After loading data in spark, the dataframe looks like below. Now we need to index the product data to an Elasticsearch index. For connecting elasticsearch along with spark, we need to add a JAR file to the classpath or place the file in the jars folder of spark. The JAR file needs to be downloaded based on the spark version we have. Now that product metadata is indexed in Elasticsearch, we need to index feature vectors for every product in the model_factor column of documents based on the primary id. Feature vectors are generated by using the ItemFeatures matrix that is produced when we run the MLib ALS algorithm on user-product-ratings data. After loading the rating data in spark and converted to dataframe will be like below. After evaluating the model, we have got a Root Mean Square Error value of RMSE=0.032, which is pretty good. The lower the value, better the model. Now we have to index the item vectors back to Elasticsearch. Now the item vector has been indexed to elasticsearch, we need to find similar products. For finding the similarity between two items, we will be using cosine similarity functionality. Cosine similarity is a measure of similarity between two nonzero vectors of an inner product space that measures the cosine of the angle between them. The smaller the value of cosine distance, the more similar the items. We will be calculating cosineSimilarity score of products using script_score functionality in elasticsearch. The cosineSimilarity function calculates the measure of cosine similarity between a given query vector and document vectors. The below query has been used for fetching similar items from elasticsearch. We are filtering with category also for better results within the category. We can change the filter options according to our needs. The script adds 1.0 to the cosine similarity to prevent the score from being negative. To take advantage of the script optimizations, provide a query vector as a script parameter. The below code has been used for getting similar products. We are passing the ASIN of the product and the number of product recommendations we want. display_similar('B001A5HT94', num=5) This will give the top 5 products as result, that is similar to the product we have passed. Not bad! The results came similar to the product we have searched for. We can always tune the ALS algorithm for better performance and accuracy. We can also take implicit feedback parameters for tuning the algorithm. Essentially, instead of trying to model the matrix of ratings directly, this approach treats the data as numbers representing the strength in observations of user actions (such as the number of clicks, or the number of times the product bought). Source code can be found on Github. Collaborative filtering- https://spark.apache.org/docs/3.0.0/ml-collaborative-filtering.html Justifying recommendations using distantly-labeled reviews and fined-grained aspects. Jianmo Ni, Jiacheng Li, Julian McAuley. Empirical Methods in Natural Language Processing (EMNLP), 2019 ( PDF)
[ { "code": null, "e": 791, "s": 171, "text": "While working in search teams of different product companies, there was always a constant demand for building a recommendation system for users. We have build with popular search engines like Elasticsearch, SOLR, and tried perfecting the search relevance. But there was always a limit when it comes to doing search relevance and creating recommendation system with just search engines. I was always amazed by companies like Amazon and Netflix providing recommendations based on our interest. So by using Apache spark machine learning capabilities along with elasticsearch, we are going to build a recommendation system." }, { "code": null, "e": 989, "s": 791, "text": "As in the picture above, if User 1 likes Item A, Item B, and Item C and User 2 likes Item B and Item C, there is a high probability that User 2 also likes Item A and can recommend Item A to User 2." }, { "code": null, "e": 1099, "s": 989, "text": "In the field of recommendations system, there are mainly three techniques used for providing recommendations." }, { "code": null, "e": 1123, "s": 1099, "text": "Collaborative filtering" }, { "code": null, "e": 1137, "s": 1123, "text": "Content-based" }, { "code": null, "e": 1154, "s": 1137, "text": "Hybrid technique" }, { "code": null, "e": 1399, "s": 1154, "text": "We will be using the Collaborative filtering technique in Pyspark for creating a recommendation system. Apache Spark ML implements alternating least squares (ALS) for collaborative filtering, a very popular algorithm for making recommendations." }, { "code": null, "e": 1521, "s": 1399, "text": "ALS is a matrix factorization algorithm that uses Alternating Least Squares with Weighted-Lambda-Regularization (ALS-WR)." }, { "code": null, "e": 1699, "s": 1521, "text": "The main problem with Spark ALS is that it will only recommend top products for a specific user (user-products model) and top users for a specific product (product-users model)." }, { "code": null, "e": 2068, "s": 1699, "text": "Calculating an all-pairs similarity is not scaling to big product catalogues. The growing number of combinations O(n2) leads very quickly to overly costly shuffle operations and infeasible computer times. For calculating the Item-Item similarity, we are building an item-item model using the similarity of item factors from the ALS model using spark and elasticsearch." }, { "code": null, "e": 2273, "s": 2068, "text": "The ALS algorithm essentially factorizes two matrix — one is userFeatures and the other is itemFeatures matrix. We are doing cosine similarity on the itemFeatures rank matrix to find item-item similarity." }, { "code": null, "e": 2461, "s": 2273, "text": "The dataset contains mainly two types of data from amazon.com. One is metadata, which contains the product metadata and the other is rating data of different products respective of users." }, { "code": null, "e": 2513, "s": 2461, "text": "Note: The dataset can be downloaded from this site." }, { "code": null, "e": 2580, "s": 2513, "text": "The spark version used is 2.4.6 and elasticsearch version is 7.9.0" }, { "code": null, "e": 2909, "s": 2580, "text": "Load the product dataset into Spark.Use Spark DataFrame operations to clean up the dataset.Load the cleaned data into Elasticsearch.Using Spark MLlib, train a collaborative filtering recommendation model from the rating data.Save the resulting model data into Elasticsearch.Using Elasticsearch queries, generate recommendations." }, { "code": null, "e": 2946, "s": 2909, "text": "Load the product dataset into Spark." }, { "code": null, "e": 3002, "s": 2946, "text": "Use Spark DataFrame operations to clean up the dataset." }, { "code": null, "e": 3044, "s": 3002, "text": "Load the cleaned data into Elasticsearch." }, { "code": null, "e": 3138, "s": 3044, "text": "Using Spark MLlib, train a collaborative filtering recommendation model from the rating data." }, { "code": null, "e": 3188, "s": 3138, "text": "Save the resulting model data into Elasticsearch." }, { "code": null, "e": 3243, "s": 3188, "text": "Using Elasticsearch queries, generate recommendations." }, { "code": null, "e": 3340, "s": 3243, "text": "The below code has been used for reading the product data and convert them to a spark dataframe." }, { "code": null, "e": 3401, "s": 3340, "text": "After loading data in spark, the dataframe looks like below." }, { "code": null, "e": 3675, "s": 3401, "text": "Now we need to index the product data to an Elasticsearch index. For connecting elasticsearch along with spark, we need to add a JAR file to the classpath or place the file in the jars folder of spark. The JAR file needs to be downloaded based on the spark version we have." }, { "code": null, "e": 3846, "s": 3675, "text": "Now that product metadata is indexed in Elasticsearch, we need to index feature vectors for every product in the model_factor column of documents based on the primary id." }, { "code": null, "e": 3991, "s": 3846, "text": "Feature vectors are generated by using the ItemFeatures matrix that is produced when we run the MLib ALS algorithm on user-product-ratings data." }, { "code": null, "e": 4077, "s": 3991, "text": "After loading the rating data in spark and converted to dataframe will be like below." }, { "code": null, "e": 4224, "s": 4077, "text": "After evaluating the model, we have got a Root Mean Square Error value of RMSE=0.032, which is pretty good. The lower the value, better the model." }, { "code": null, "e": 4285, "s": 4224, "text": "Now we have to index the item vectors back to Elasticsearch." }, { "code": null, "e": 4374, "s": 4285, "text": "Now the item vector has been indexed to elasticsearch, we need to find similar products." }, { "code": null, "e": 4621, "s": 4374, "text": "For finding the similarity between two items, we will be using cosine similarity functionality. Cosine similarity is a measure of similarity between two nonzero vectors of an inner product space that measures the cosine of the angle between them." }, { "code": null, "e": 4691, "s": 4621, "text": "The smaller the value of cosine distance, the more similar the items." }, { "code": null, "e": 4925, "s": 4691, "text": "We will be calculating cosineSimilarity score of products using script_score functionality in elasticsearch. The cosineSimilarity function calculates the measure of cosine similarity between a given query vector and document vectors." }, { "code": null, "e": 5315, "s": 4925, "text": "The below query has been used for fetching similar items from elasticsearch. We are filtering with category also for better results within the category. We can change the filter options according to our needs. The script adds 1.0 to the cosine similarity to prevent the score from being negative. To take advantage of the script optimizations, provide a query vector as a script parameter." }, { "code": null, "e": 5464, "s": 5315, "text": "The below code has been used for getting similar products. We are passing the ASIN of the product and the number of product recommendations we want." }, { "code": null, "e": 5501, "s": 5464, "text": "display_similar('B001A5HT94', num=5)" }, { "code": null, "e": 5593, "s": 5501, "text": "This will give the top 5 products as result, that is similar to the product we have passed." }, { "code": null, "e": 5738, "s": 5593, "text": "Not bad! The results came similar to the product we have searched for. We can always tune the ALS algorithm for better performance and accuracy." }, { "code": null, "e": 6056, "s": 5738, "text": "We can also take implicit feedback parameters for tuning the algorithm. Essentially, instead of trying to model the matrix of ratings directly, this approach treats the data as numbers representing the strength in observations of user actions (such as the number of clicks, or the number of times the product bought)." }, { "code": null, "e": 6092, "s": 6056, "text": "Source code can be found on Github." }, { "code": null, "e": 6185, "s": 6092, "text": "Collaborative filtering- https://spark.apache.org/docs/3.0.0/ml-collaborative-filtering.html" } ]
String Concatenation in Java
You can concatenate two strings in Java either by using the concat() method or by using the ‘+’ , the “concatenation” operator. The concat() method appends one String to the end of another. This method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method. public class ConncatSample { public static void main(String []args) { String s1 = "Hello"; String s2 = "world"; String res = s1.concat(s2); System.out.print("Concatenation result:: "); System.out.println(res); } } Concatenation result:: Helloworld Just like the concat method the ‘+’ operator also performs the concatenation operation on the given operators. public class ConncatSample { public static void main(String []args) { String s1 = "Hello"; String s2 = "world"; String res = s1+s2; System.out.print("Concatenation result:: "); System.out.println(res); } } Concatenation result:: Helloworld
[ { "code": null, "e": 1190, "s": 1062, "text": "You can concatenate two strings in Java either by using the concat() method or by using the ‘+’ , the “concatenation” operator." }, { "code": null, "e": 1397, "s": 1190, "text": "The concat() method appends one String to the end of another. This method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method." }, { "code": null, "e": 1647, "s": 1397, "text": "public class ConncatSample {\n public static void main(String []args) {\n String s1 = \"Hello\";\n String s2 = \"world\";\n String res = s1.concat(s2);\n System.out.print(\"Concatenation result:: \");\n System.out.println(res);\n }\n}" }, { "code": null, "e": 1681, "s": 1647, "text": "Concatenation result:: Helloworld" }, { "code": null, "e": 1792, "s": 1681, "text": "Just like the concat method the ‘+’ operator also performs the concatenation operation on the given operators." }, { "code": null, "e": 2034, "s": 1792, "text": "public class ConncatSample {\n public static void main(String []args) {\n String s1 = \"Hello\";\n String s2 = \"world\";\n String res = s1+s2;\n System.out.print(\"Concatenation result:: \");\n System.out.println(res);\n }\n}" }, { "code": null, "e": 2068, "s": 2034, "text": "Concatenation result:: Helloworld" } ]