title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to Shut Down a Computer using Command Prompt?
01 Oct, 2020 Sometimes, situations might arise due to either a windows bug or some malicious program that start menu tray won’t open even on the press, leaving us with only forcing the desktop or laptop to shut down by either long pressing the power button or cutting off the power supply of the device. To overcome such a situation, there are various efficient least time-consuming methods of shutdown, here in this article we will show you one of such ways to shutdown a computer in multiple ways. Go through the following command and save that as a .bat file. This .bat on getting executed (by a simple double click or other methods) should initiate the shutdown process. Open Command Prompt (cmd) and type: shutdown /s or, shutdown -s The above command will schedule a shutdown, the Windows machine should be scheduled to shutdown within a minute of executing this command. It should look something like this: After execution of this command, you would see something similar like this: Canceling the Shutdown: To cancel a scheduled shutdown via this method simply type: shutdown /a or, shutdown -a Remote Shutdown: The remote shutdown of a computer (GUI aided) in network can be done with the help of the following command: shutdown /i or, shutdown -i Shutdown commands with additional parameters: You can save the above code as a .bat file, and execute it instead of always clicking start > power > shutdown. Save with -t 00 parameter, so that the shutdown is instantaneous. Basically type & save: shutdown -s -t 00 To have a windows machine shutdown after a custom set time, type: shutdown -s -t 900 ( -t is superseded by time in seconds, for example, if we want an immediate shutdown, we can write: shutdown -s -t 00. Also, as stated above, you can just as easily cancel a scheduled shutdown or restart like this by typing, shutdown -a ) To have the windows machine restart instead of shutdown, type: shutdown -r (you can have -t and other parameters in this command. Type shutdown /? for more information on other available parameters) Additional Note: For instant and most efficient shutdown process, open any text editor software, namely notepad (comes in-built with windows) and write: shutdown -s -t 00 and then save the file with .bat extension. Now simply execute this .bat file to initiate an instantaneous shutdown. How To Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Set Git Username and Password in GitBash? How to Install Jupyter Notebook on MacOS? How to Install and Use NVM on Windows? How to Install Python Packages for AWS Lambda Layers? How to Install Git in VS Code? How to Add External JAR File to an IntelliJ IDEA Project? How to Create and Setup Spring Boot Project in Eclipse IDE? How to Set Upstream Branch on Git? How to Install Flutter on Visual Studio Code? How to Permanently Disable Swap in Linux?
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 319, "s": 28, "text": "Sometimes, situations might arise due to either a windows bug or some malicious program that start menu tray won’t open even on the press, leaving us with only forcing the desktop or laptop to shut down by either long pressing the power button or cutting off the power supply of the device." }, { "code": null, "e": 690, "s": 319, "text": "To overcome such a situation, there are various efficient least time-consuming methods of shutdown, here in this article we will show you one of such ways to shutdown a computer in multiple ways. Go through the following command and save that as a .bat file. This .bat on getting executed (by a simple double click or other methods) should initiate the shutdown process." }, { "code": null, "e": 726, "s": 690, "text": "Open Command Prompt (cmd) and type:" }, { "code": null, "e": 739, "s": 726, "text": "shutdown /s\n" }, { "code": null, "e": 743, "s": 739, "text": "or," }, { "code": null, "e": 756, "s": 743, "text": "shutdown -s\n" }, { "code": null, "e": 932, "s": 756, "text": "The above command will schedule a shutdown, the Windows machine should be scheduled to shutdown within a minute of executing this command. It should look something like this:" }, { "code": null, "e": 1008, "s": 932, "text": "After execution of this command, you would see something similar like this:" }, { "code": null, "e": 1032, "s": 1008, "text": "Canceling the Shutdown:" }, { "code": null, "e": 1092, "s": 1032, "text": "To cancel a scheduled shutdown via this method simply type:" }, { "code": null, "e": 1105, "s": 1092, "text": "shutdown /a\n" }, { "code": null, "e": 1109, "s": 1105, "text": "or," }, { "code": null, "e": 1122, "s": 1109, "text": "shutdown -a\n" }, { "code": null, "e": 1139, "s": 1122, "text": "Remote Shutdown:" }, { "code": null, "e": 1248, "s": 1139, "text": "The remote shutdown of a computer (GUI aided) in network can be done with the help of the following command:" }, { "code": null, "e": 1261, "s": 1248, "text": "shutdown /i\n" }, { "code": null, "e": 1265, "s": 1261, "text": "or," }, { "code": null, "e": 1278, "s": 1265, "text": "shutdown -i\n" }, { "code": null, "e": 1324, "s": 1278, "text": "Shutdown commands with additional parameters:" }, { "code": null, "e": 1525, "s": 1324, "text": "You can save the above code as a .bat file, and execute it instead of always clicking start > power > shutdown. Save with -t 00 parameter, so that the shutdown is instantaneous. Basically type & save:" }, { "code": null, "e": 1543, "s": 1525, "text": "shutdown -s -t 00" }, { "code": null, "e": 1609, "s": 1543, "text": "To have a windows machine shutdown after a custom set time, type:" }, { "code": null, "e": 1629, "s": 1609, "text": "shutdown -s -t 900\n" }, { "code": null, "e": 1869, "s": 1629, "text": " ( -t is superseded by time in seconds, for example, if we want an immediate shutdown, we can write: shutdown -s -t 00. Also, as stated above, you can just as easily cancel a scheduled shutdown or restart like this by typing, shutdown -a )" }, { "code": null, "e": 1932, "s": 1869, "text": "To have the windows machine restart instead of shutdown, type:" }, { "code": null, "e": 1945, "s": 1932, "text": "shutdown -r\n" }, { "code": null, "e": 2069, "s": 1945, "text": "(you can have -t and other parameters in this command. Type shutdown /? for more information on other available parameters)" }, { "code": null, "e": 2086, "s": 2069, "text": "Additional Note:" }, { "code": null, "e": 2222, "s": 2086, "text": "For instant and most efficient shutdown process, open any text editor software, namely notepad (comes in-built with windows) and write:" }, { "code": null, "e": 2241, "s": 2222, "text": "shutdown -s -t 00\n" }, { "code": null, "e": 2358, "s": 2241, "text": "and then save the file with .bat extension. Now simply execute this .bat file to initiate an instantaneous shutdown." }, { "code": null, "e": 2365, "s": 2358, "text": "How To" }, { "code": null, "e": 2463, "s": 2365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2512, "s": 2463, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 2554, "s": 2512, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 2593, "s": 2554, "text": "How to Install and Use NVM on Windows?" }, { "code": null, "e": 2647, "s": 2593, "text": "How to Install Python Packages for AWS Lambda Layers?" }, { "code": null, "e": 2678, "s": 2647, "text": "How to Install Git in VS Code?" }, { "code": null, "e": 2736, "s": 2678, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 2796, "s": 2736, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 2831, "s": 2796, "text": "How to Set Upstream Branch on Git?" }, { "code": null, "e": 2877, "s": 2831, "text": "How to Install Flutter on Visual Studio Code?" } ]
Python – Pendulum Module
17 Dec, 2020 The pendulum is one of the popular Python DateTime libraries to ease DateTime manipulation. It provides a cleaner and easier to use API. It simplifies the problem of complex date manipulations involving timezones which are not handled correctly in native datetime instances. It inherits from the standard datetime library but provides better functionality. So you can introduce Pendulums Datetime instances in projects which are already using built-in datetime class (except for the libraries that check the type of the objects by using the type function like sqlite3). To install this module run this command into your terminal: pip install pendulum Let’s see the simple examples: You can create date-time instance using various methods like datetime(), local(),now(),from_format(). Example : Python3 # import libraryimport pendulumdt = pendulum.datetime(2020, 11, 27)print(dt) #local() creates datetime instance with local timezonelocal = pendulum.local(2020, 11,27)print(local)print(local.timezone.name) Output: 2020-11-27T00:00:00+00:00 2020-11-27T00:00:00+05:30 Asia/Calcutta You can convert timezones using the in_timezone() method or using the timezone library directly. Refer following example for a better understanding Note: UTC(Coordinated Universal Time) is the primary time standard by which the world regulates clocks and time. Example : Python3 # Importing libraryimport pendulum # Getting current UTC timeutc_time = pendulum.now('UTC') # Switching current timezone to# Kolkata timezone using in_timezone().kolkata_time = utc_time.in_timezone('Asia/Kolkata')print('Current Date Time in Kolkata =', kolkata_time) # Generating Sydney timezonesydney_tz = pendulum.timezone('Australia/Sydney') # Switching current timezone to# Sydney timezone using convert().sydney_time = sydney_tz.convert(utc_time)print('Current Date Time in Sydney =', sydney_time) Output : Current Date Time in Kolkata = 2020-11-27T15:16:36.985136+05:30 Current Date Time in Sydney = 2020-11-27T20:46:36.985136+11:00 For date-time manipulation, we can use the add() and subtract() methods. Each method returns a new DateTime instance. Example : Python3 # Importing the libraryimport pendulum# creating datetime instancedt = pendulum.datetime(2020, 11, 27)print(dt) # Manipulating datetime object using add()dt = dt.add(years=5)print(dt) # Manipulating datetime object using subtract()dt = dt.subtract(months = 1)print(dt) # Similarly you can add or subtract# months,weeks,days,hours,minutes# individually or all at a time.dt = dt.add(years=3, months=2, days=6, hours=12, minutes=30, seconds=45) print(dt) Output : 2020-11-27T00:00:00+00:00 2025-11-27T00:00:00+00:00 2025-10-27T00:00:00+00:00 2029-01-02T12:30:45+00:00 We can convert date time to a standard formatted string using the following methods. to_date_string() to_formatted_date_string() to_time_string() to_datetime_string() to_day_datetime_string() Pendulum module also has format() & strftime() function where we can specify our own format. Example : Python3 import pendulum# Creating new DateTime instancedt = pendulum.datetime(2020, 11, 27, 12, 30, 15)print(dt) # Formatting date-timedt.to_day_datetime_string()formatted_str = dt.format('dddd Do [of] MMMM YYYY HH:mm:ss A')print(formatted_str) new_str = dt.strftime('%Y-%m-%d %H:%M:%S %Z%z')print(new_str) Output : 2020-11-27T12:30:15+00:00 Friday 27th of November 2020 12:30:15 PM 2020-11-27 12:30:15 UTC+0000 parse() function is used to parse a string having commonly used formats to datetime object. If you want to pass a non-standard or more complicated string, then use the from_format() function. However, if you want the library to fall back on the dateutil parser, you have to pass strict=False. Python3 import pendulumdt = pendulum.parse('1997-11-21T22:00:00', tz = 'Asia/Calcutta')print(dt) # parsing of non standard stringdt = pendulum.from_format('2020/11/21', 'YYYY/MM/DD') print(dt) Output : 1997-11-21T22:00:00+05:30 2020-11-21T00:00:00+00:00 The Duration class inherits from the native timedelta class. However, its behavior is slightly different. Example : Python3 import pendulumtime_delta = pendulum.duration(days = 2, hours = 10, years = 2)print(time_delta) # Date when i am writing this code is 2020-11-27.print('future date =', pendulum.now() + time_delta) Output : 2 years 2 days 10 hours future date = 2022-11-30T04:38:01.256888+05:30 When you subtract a DateTime instance from another or use the diff() method, it will return a Period instance. It inherits from the Duration class with the added benefit that it is aware of the instances that generated it so that it can give access to more methods and properties. Example 1 : Python3 import pendulumstarting = pendulum.datetime(2021, 1, 1)ending = starting.add(hours = 10) # subtracting date-time instances# to ge a period instanceperiod = ending - startingperiod.hours Output : 10 Example 2 : Python3 import pendulum # You can create period instance# by using the period() methodstart = pendulum.datetime(2021, 1, 1)end = pendulum.datetime(2021, 1, 31)period = pendulum.period(start, end)period.days Output : 30 tejalkadam18m python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Dec, 2020" }, { "code": null, "e": 303, "s": 28, "text": "The pendulum is one of the popular Python DateTime libraries to ease DateTime manipulation. It provides a cleaner and easier to use API. It simplifies the problem of complex date manipulations involving timezones which are not handled correctly in native datetime instances." }, { "code": null, "e": 599, "s": 303, "text": "It inherits from the standard datetime library but provides better functionality. So you can introduce Pendulums Datetime instances in projects which are already using built-in datetime class (except for the libraries that check the type of the objects by using the type function like sqlite3)." }, { "code": null, "e": 659, "s": 599, "text": "To install this module run this command into your terminal:" }, { "code": null, "e": 681, "s": 659, "text": " pip install pendulum" }, { "code": null, "e": 712, "s": 681, "text": "Let’s see the simple examples:" }, { "code": null, "e": 815, "s": 712, "text": "You can create date-time instance using various methods like datetime(), local(),now(),from_format()." }, { "code": null, "e": 826, "s": 815, "text": "Example : " }, { "code": null, "e": 834, "s": 826, "text": "Python3" }, { "code": "# import libraryimport pendulumdt = pendulum.datetime(2020, 11, 27)print(dt) #local() creates datetime instance with local timezonelocal = pendulum.local(2020, 11,27)print(local)print(local.timezone.name)", "e": 1039, "s": 834, "text": null }, { "code": null, "e": 1049, "s": 1041, "text": "Output:" }, { "code": null, "e": 1117, "s": 1051, "text": "2020-11-27T00:00:00+00:00\n2020-11-27T00:00:00+05:30\nAsia/Calcutta" }, { "code": null, "e": 1267, "s": 1119, "text": "You can convert timezones using the in_timezone() method or using the timezone library directly. Refer following example for a better understanding" }, { "code": null, "e": 1382, "s": 1269, "text": "Note: UTC(Coordinated Universal Time) is the primary time standard by which the world regulates clocks and time." }, { "code": null, "e": 1394, "s": 1384, "text": "Example :" }, { "code": null, "e": 1404, "s": 1396, "text": "Python3" }, { "code": "# Importing libraryimport pendulum # Getting current UTC timeutc_time = pendulum.now('UTC') # Switching current timezone to# Kolkata timezone using in_timezone().kolkata_time = utc_time.in_timezone('Asia/Kolkata')print('Current Date Time in Kolkata =', kolkata_time) # Generating Sydney timezonesydney_tz = pendulum.timezone('Australia/Sydney') # Switching current timezone to# Sydney timezone using convert().sydney_time = sydney_tz.convert(utc_time)print('Current Date Time in Sydney =', sydney_time)", "e": 1907, "s": 1404, "text": null }, { "code": null, "e": 1916, "s": 1907, "text": "Output :" }, { "code": null, "e": 2043, "s": 1916, "text": "Current Date Time in Kolkata = 2020-11-27T15:16:36.985136+05:30\nCurrent Date Time in Sydney = 2020-11-27T20:46:36.985136+11:00" }, { "code": null, "e": 2161, "s": 2043, "text": "For date-time manipulation, we can use the add() and subtract() methods. Each method returns a new DateTime instance." }, { "code": null, "e": 2171, "s": 2161, "text": "Example :" }, { "code": null, "e": 2179, "s": 2171, "text": "Python3" }, { "code": "# Importing the libraryimport pendulum# creating datetime instancedt = pendulum.datetime(2020, 11, 27)print(dt) # Manipulating datetime object using add()dt = dt.add(years=5)print(dt) # Manipulating datetime object using subtract()dt = dt.subtract(months = 1)print(dt) # Similarly you can add or subtract# months,weeks,days,hours,minutes# individually or all at a time.dt = dt.add(years=3, months=2, days=6, hours=12, minutes=30, seconds=45) print(dt)", "e": 2642, "s": 2179, "text": null }, { "code": null, "e": 2655, "s": 2645, "text": "Output : " }, { "code": null, "e": 2761, "s": 2657, "text": "2020-11-27T00:00:00+00:00\n2025-11-27T00:00:00+00:00\n2025-10-27T00:00:00+00:00\n2029-01-02T12:30:45+00:00" }, { "code": null, "e": 2848, "s": 2763, "text": "We can convert date time to a standard formatted string using the following methods." }, { "code": null, "e": 2867, "s": 2850, "text": "to_date_string()" }, { "code": null, "e": 2894, "s": 2867, "text": "to_formatted_date_string()" }, { "code": null, "e": 2911, "s": 2894, "text": "to_time_string()" }, { "code": null, "e": 2932, "s": 2911, "text": "to_datetime_string()" }, { "code": null, "e": 2957, "s": 2932, "text": "to_day_datetime_string()" }, { "code": null, "e": 3052, "s": 2959, "text": "Pendulum module also has format() & strftime() function where we can specify our own format." }, { "code": null, "e": 3065, "s": 3054, "text": "Example : " }, { "code": null, "e": 3075, "s": 3067, "text": "Python3" }, { "code": "import pendulum# Creating new DateTime instancedt = pendulum.datetime(2020, 11, 27, 12, 30, 15)print(dt) # Formatting date-timedt.to_day_datetime_string()formatted_str = dt.format('dddd Do [of] MMMM YYYY HH:mm:ss A')print(formatted_str) new_str = dt.strftime('%Y-%m-%d %H:%M:%S %Z%z')print(new_str)", "e": 3374, "s": 3075, "text": null }, { "code": null, "e": 3384, "s": 3374, "text": "Output : " }, { "code": null, "e": 3480, "s": 3384, "text": "2020-11-27T12:30:15+00:00\nFriday 27th of November 2020 12:30:15 PM\n2020-11-27 12:30:15 UTC+0000" }, { "code": null, "e": 3774, "s": 3480, "text": " parse() function is used to parse a string having commonly used formats to datetime object. If you want to pass a non-standard or more complicated string, then use the from_format() function. However, if you want the library to fall back on the dateutil parser, you have to pass strict=False." }, { "code": null, "e": 3782, "s": 3774, "text": "Python3" }, { "code": "import pendulumdt = pendulum.parse('1997-11-21T22:00:00', tz = 'Asia/Calcutta')print(dt) # parsing of non standard stringdt = pendulum.from_format('2020/11/21', 'YYYY/MM/DD') print(dt)", "e": 4011, "s": 3782, "text": null }, { "code": null, "e": 4020, "s": 4011, "text": "Output :" }, { "code": null, "e": 4072, "s": 4020, "text": "1997-11-21T22:00:00+05:30\n2020-11-21T00:00:00+00:00" }, { "code": null, "e": 4178, "s": 4072, "text": "The Duration class inherits from the native timedelta class. However, its behavior is slightly different." }, { "code": null, "e": 4189, "s": 4178, "text": "Example : " }, { "code": null, "e": 4197, "s": 4189, "text": "Python3" }, { "code": "import pendulumtime_delta = pendulum.duration(days = 2, hours = 10, years = 2)print(time_delta) # Date when i am writing this code is 2020-11-27.print('future date =', pendulum.now() + time_delta)", "e": 4459, "s": 4197, "text": null }, { "code": null, "e": 4468, "s": 4459, "text": "Output :" }, { "code": null, "e": 4539, "s": 4468, "text": "2 years 2 days 10 hours\nfuture date = 2022-11-30T04:38:01.256888+05:30" }, { "code": null, "e": 4820, "s": 4539, "text": "When you subtract a DateTime instance from another or use the diff() method, it will return a Period instance. It inherits from the Duration class with the added benefit that it is aware of the instances that generated it so that it can give access to more methods and properties." }, { "code": null, "e": 4832, "s": 4820, "text": "Example 1 :" }, { "code": null, "e": 4840, "s": 4832, "text": "Python3" }, { "code": "import pendulumstarting = pendulum.datetime(2021, 1, 1)ending = starting.add(hours = 10) # subtracting date-time instances# to ge a period instanceperiod = ending - startingperiod.hours", "e": 5026, "s": 4840, "text": null }, { "code": null, "e": 5036, "s": 5026, "text": "Output : " }, { "code": null, "e": 5039, "s": 5036, "text": "10" }, { "code": null, "e": 5052, "s": 5039, "text": "Example 2 : " }, { "code": null, "e": 5060, "s": 5052, "text": "Python3" }, { "code": "import pendulum # You can create period instance# by using the period() methodstart = pendulum.datetime(2021, 1, 1)end = pendulum.datetime(2021, 1, 31)period = pendulum.period(start, end)period.days", "e": 5259, "s": 5060, "text": null }, { "code": null, "e": 5269, "s": 5259, "text": "Output : " }, { "code": null, "e": 5272, "s": 5269, "text": "30" }, { "code": null, "e": 5286, "s": 5272, "text": "tejalkadam18m" }, { "code": null, "e": 5301, "s": 5286, "text": "python-modules" }, { "code": null, "e": 5308, "s": 5301, "text": "Python" }, { "code": null, "e": 5406, "s": 5308, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5438, "s": 5406, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5465, "s": 5438, "text": "Python Classes and Objects" }, { "code": null, "e": 5486, "s": 5465, "text": "Python OOPs Concepts" }, { "code": null, "e": 5509, "s": 5486, "text": "Introduction To PYTHON" }, { "code": null, "e": 5565, "s": 5509, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 5596, "s": 5565, "text": "Python | os.path.join() method" }, { "code": null, "e": 5638, "s": 5596, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5680, "s": 5638, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 5719, "s": 5680, "text": "Python | Get unique values from a list" } ]
HTML | <base> href Attribute
30 Mar, 2022 The HTML | <base> href Attribute is used to specify the base URL for all the relative URL of a page. Syntax: <base href="URL"> Attribute Values: It contains the value i.e URL which specifies the absolute URL that defines the base URL of the page. for eg.”www.geeksforgeeks.org” Example: This Example illustrates the use of href attribute in element. <!DOCTYPE html><html> <head> <!-- Declaring the BASE URL --> <base href="https://media.geeksforgeeks.org/wp-content/uploads/" target="_blank"></head><h1>GeeksForGeeks</h1><h2> HTML | <base>href Attribute </h2> <body> <img src="1-95.jpg" width="400" height="250"></body> </html> Output: Supported Browsers: The browser supported by HTML | <base> href Attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari shubham_singh chhabradhanvi HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Design a web page using HTML and CSS Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Mar, 2022" }, { "code": null, "e": 129, "s": 28, "text": "The HTML | <base> href Attribute is used to specify the base URL for all the relative URL of a page." }, { "code": null, "e": 137, "s": 129, "text": "Syntax:" }, { "code": null, "e": 155, "s": 137, "text": "<base href=\"URL\">" }, { "code": null, "e": 306, "s": 155, "text": "Attribute Values: It contains the value i.e URL which specifies the absolute URL that defines the base URL of the page. for eg.”www.geeksforgeeks.org”" }, { "code": null, "e": 378, "s": 306, "text": "Example: This Example illustrates the use of href attribute in element." }, { "code": "<!DOCTYPE html><html> <head> <!-- Declaring the BASE URL --> <base href=\"https://media.geeksforgeeks.org/wp-content/uploads/\" target=\"_blank\"></head><h1>GeeksForGeeks</h1><h2> HTML | <base>href Attribute </h2> <body> <img src=\"1-95.jpg\" width=\"400\" height=\"250\"></body> </html>", "e": 696, "s": 378, "text": null }, { "code": null, "e": 704, "s": 696, "text": "Output:" }, { "code": null, "e": 796, "s": 704, "text": "Supported Browsers: The browser supported by HTML | <base> href Attribute are listed below:" }, { "code": null, "e": 810, "s": 796, "text": "Google Chrome" }, { "code": null, "e": 828, "s": 810, "text": "Internet Explorer" }, { "code": null, "e": 836, "s": 828, "text": "Firefox" }, { "code": null, "e": 842, "s": 836, "text": "Opera" }, { "code": null, "e": 849, "s": 842, "text": "Safari" }, { "code": null, "e": 863, "s": 849, "text": "shubham_singh" }, { "code": null, "e": 877, "s": 863, "text": "chhabradhanvi" }, { "code": null, "e": 893, "s": 877, "text": "HTML-Attributes" }, { "code": null, "e": 898, "s": 893, "text": "HTML" }, { "code": null, "e": 915, "s": 898, "text": "Web Technologies" }, { "code": null, "e": 920, "s": 915, "text": "HTML" }, { "code": null, "e": 1018, "s": 920, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1042, "s": 1018, "text": "REST API (Introduction)" }, { "code": null, "e": 1081, "s": 1042, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1120, "s": 1081, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 1140, "s": 1120, "text": "Angular File Upload" }, { "code": null, "e": 1177, "s": 1140, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 1210, "s": 1177, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1271, "s": 1210, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1314, "s": 1271, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1386, "s": 1314, "text": "Differences between Functional Components and Class Components in React" } ]
jQuery Effect - Scale Effect
The Scale effect can be used with show/hide/toggle. This shrinks or grows an element by a percentage factor. Here is the simple syntax to use this effect − selector.hide|show|toggle( "scale", {arguments}, speed ); Here is the description of all the arguments − direction − The direction of the effect. Can be "both", "vertical" or "horizontal". Default is both. direction − The direction of the effect. Can be "both", "vertical" or "horizontal". Default is both. from − The state at beginning, usually not needed. This would be an object and would be given in the form of { height: .., width: .. }. from − The state at beginning, usually not needed. This would be an object and would be given in the form of { height: .., width: .. }. origin − The vanishing point. This is an array and by default set to ['middle','center']. origin − The vanishing point. This is an array and by default set to ['middle','center']. percent − The percentage to scale to, number. Default is 0/100. percent − The percentage to scale to, number. Default is 0/100. scale − Which areas of the element will be resized: 'both', 'box', 'content' Box resizes the border and padding of the element Content resizes any content inside of the element. Default is both. scale − Which areas of the element will be resized: 'both', 'box', 'content' Box resizes the border and padding of the element Content resizes any content inside of the element. Default is both. Following is a simple example a simple showing the usage of this effect − <html> <head> <title>The jQuery Example</title> <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 type = "text/javascript" language = "javascript"> $(document).ready(function() { $("#hide").click(function(){ $(".target").hide( "scale", {percent: 200, direction: 'horizontal'}, 2000 ); }); $("#show").click(function(){ $(".target").show( "scale", {percent: 200, direction: 'vertical' }, 2000 ); }); }); </script> <style> p {background-color:#bca; width:200px; border:1px solid green;} div{ width:100px; height:100px; background:red;} </style> </head> <body> <p>Click on any of the buttons</p> <button id = "hide"> Hide </button> <button id = "show"> Show</button> <div class = "target"> </div> </body> </html> This will produce following result − Click on any of the buttons 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": 2431, "s": 2322, "text": "The Scale effect can be used with show/hide/toggle. This shrinks or grows an element by a percentage factor." }, { "code": null, "e": 2478, "s": 2431, "text": "Here is the simple syntax to use this effect −" }, { "code": null, "e": 2537, "s": 2478, "text": "selector.hide|show|toggle( \"scale\", {arguments}, speed );\n" }, { "code": null, "e": 2584, "s": 2537, "text": "Here is the description of all the arguments −" }, { "code": null, "e": 2685, "s": 2584, "text": "direction − The direction of the effect. Can be \"both\", \"vertical\" or \"horizontal\". Default is both." }, { "code": null, "e": 2786, "s": 2685, "text": "direction − The direction of the effect. Can be \"both\", \"vertical\" or \"horizontal\". Default is both." }, { "code": null, "e": 2922, "s": 2786, "text": "from − The state at beginning, usually not needed. This would be an object and would be given in the form of { height: .., width: .. }." }, { "code": null, "e": 3058, "s": 2922, "text": "from − The state at beginning, usually not needed. This would be an object and would be given in the form of { height: .., width: .. }." }, { "code": null, "e": 3148, "s": 3058, "text": "origin − The vanishing point. This is an array and by default set to ['middle','center']." }, { "code": null, "e": 3238, "s": 3148, "text": "origin − The vanishing point. This is an array and by default set to ['middle','center']." }, { "code": null, "e": 3302, "s": 3238, "text": "percent − The percentage to scale to, number. Default is 0/100." }, { "code": null, "e": 3366, "s": 3302, "text": "percent − The percentage to scale to, number. Default is 0/100." }, { "code": null, "e": 3561, "s": 3366, "text": "scale − Which areas of the element will be resized: 'both', 'box', 'content' Box resizes the border and padding of the element Content resizes any content inside of the element. Default is both." }, { "code": null, "e": 3756, "s": 3561, "text": "scale − Which areas of the element will be resized: 'both', 'box', 'content' Box resizes the border and padding of the element Content resizes any content inside of the element. Default is both." }, { "code": null, "e": 3830, "s": 3756, "text": "Following is a simple example a simple showing the usage of this effect −" }, { "code": null, "e": 5000, "s": 3830, "text": "<html>\n <head>\n <title>The jQuery Example</title>\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 <script type = \"text/javascript\" language = \"javascript\">\n \n $(document).ready(function() {\n\n $(\"#hide\").click(function(){\n $(\".target\").hide( \"scale\", {percent: 200, direction: 'horizontal'}, 2000 );\n });\n\n $(\"#show\").click(function(){\n $(\".target\").show( \"scale\", {percent: 200, direction: 'vertical' }, 2000 );\n });\n\t\t\t\t\n });\n\t\t\t\n </script>\n\t\t\n <style>\n p {background-color:#bca; width:200px; border:1px solid green;}\n div{ width:100px; height:100px; background:red;}\n </style>\n </head>\n\t\n <body>\n <p>Click on any of the buttons</p>\n\t\t\n <button id = \"hide\"> Hide </button>\n <button id = \"show\"> Show</button> \n \n <div class = \"target\">\n </div>\n </body>\n</html>" }, { "code": null, "e": 5037, "s": 5000, "text": "This will produce following result −" }, { "code": null, "e": 5065, "s": 5037, "text": "Click on any of the buttons" }, { "code": null, "e": 5098, "s": 5065, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 5112, "s": 5098, "text": " Mahesh Kumar" }, { "code": null, "e": 5147, "s": 5112, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5161, "s": 5147, "text": " Pratik Singh" }, { "code": null, "e": 5196, "s": 5161, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5213, "s": 5196, "text": " Frahaan Hussain" }, { "code": null, "e": 5246, "s": 5213, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 5274, "s": 5246, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5307, "s": 5274, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 5328, "s": 5307, "text": " Sandip Bhattacharya" }, { "code": null, "e": 5360, "s": 5328, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 5377, "s": 5360, "text": " Laurence Svekis" }, { "code": null, "e": 5384, "s": 5377, "text": " Print" }, { "code": null, "e": 5395, "s": 5384, "text": " Add Notes" } ]
Find and display duplicate records in MySQL?
First, a table is created with the help of the CREATE command. This is given as follows − mysql> CREATE table DuplicateFound -> ( -> ID int, -> Name varchar(100), -> Location varchar(200) -> ); Query OK, 0 rows affected (0.45 sec) After creating the table, the records are inserted with the help of the INSERT command as follows − mysql> INSERT into DuplicateFound values(1,'John','US'); Query OK, 1 row affected (0.10 sec) mysql> INSERT into DuplicateFound values(2,'Bob','UK'); Query OK, 1 row affected (0.18 sec) mysql> INSERT into DuplicateFound values(3,'David','US'); Query OK, 1 row affected (0.14 sec) mysql> INSERT into DuplicateFound values(4,'Smith','US'); Query OK, 1 row affected (0.16 sec) mysql> INSERT into DuplicateFound values(5,'Carol','UK'); Query OK, 1 row affected (0.16 sec) The records are displayed with the help of the SELECT statement. This is given below − mysql> SELECT * from DuplicateFound; The following is the output obtained − +------+-------+----------+ | ID | Name | Location | +------+-------+----------+ | 1 | John | US | | 2 | Bob | UK | | 3 | David | US | | 4 | Smith | US | | 5 | Carol | UK | +------+-------+----------+ 5 rows in set (0.00 sec) The query to find and display the duplicate records together is given as follows − mysql> SELECT * from DuplicateFound -> where location in (select location from DuplicateFound group by location having count(location) >1 ) -> order by location; The following is the output obtained +------+-------+----------+ | ID | Name | Location | +------+-------+----------+ | 2 | Bob | UK | | 5 | Carol | UK | | 1 | John | US | | 3 | David | US | | 4 | Smith | US | +------+-------+----------+ 5 rows in set (0.06 sec) We can display those records which belong to a single location. This is given as follows − mysql> select Name,location from DuplicateFound -> group by location -> having count(location) > 1; The following is the output +------+----------+ | Name | Location | +------+----------+ | John | US | | Bob | UK | +------+----------+ 2 rows in set (0.04 sec)
[ { "code": null, "e": 1152, "s": 1062, "text": "First, a table is created with the help of the CREATE command. This is given as follows −" }, { "code": null, "e": 1293, "s": 1152, "text": "mysql> CREATE table DuplicateFound\n-> (\n-> ID int,\n-> Name varchar(100),\n-> Location varchar(200)\n-> );\nQuery OK, 0 rows affected (0.45 sec)" }, { "code": null, "e": 1393, "s": 1293, "text": "After creating the table, the records are inserted with the help of the INSERT command as\nfollows −" }, { "code": null, "e": 1864, "s": 1393, "text": "mysql> INSERT into DuplicateFound values(1,'John','US');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> INSERT into DuplicateFound values(2,'Bob','UK');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> INSERT into DuplicateFound values(3,'David','US');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> INSERT into DuplicateFound values(4,'Smith','US');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> INSERT into DuplicateFound values(5,'Carol','UK');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 1951, "s": 1864, "text": "The records are displayed with the help of the SELECT statement. This is given below −" }, { "code": null, "e": 1989, "s": 1951, "text": "mysql> SELECT * from DuplicateFound;\n" }, { "code": null, "e": 2028, "s": 1989, "text": "The following is the output obtained −" }, { "code": null, "e": 2305, "s": 2028, "text": "+------+-------+----------+\n| ID | Name | Location |\n+------+-------+----------+\n| 1 | John | US |\n| 2 | Bob | UK |\n| 3 | David | US |\n| 4 | Smith | US |\n| 5 | Carol | UK |\n+------+-------+----------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2388, "s": 2305, "text": "The query to find and display the duplicate records together is given as follows −" }, { "code": null, "e": 2550, "s": 2388, "text": "mysql> SELECT * from DuplicateFound\n-> where location in (select location from DuplicateFound group by location having count(location) >1 )\n-> order by location;" }, { "code": null, "e": 2587, "s": 2550, "text": "The following is the output obtained" }, { "code": null, "e": 2864, "s": 2587, "text": "+------+-------+----------+\n| ID | Name | Location |\n+------+-------+----------+\n| 2 | Bob | UK |\n| 5 | Carol | UK |\n| 1 | John | US |\n| 3 | David | US |\n| 4 | Smith | US |\n+------+-------+----------+\n5 rows in set (0.06 sec)" }, { "code": null, "e": 2955, "s": 2864, "text": "We can display those records which belong to a single location. This is given as follows −" }, { "code": null, "e": 3055, "s": 2955, "text": "mysql> select Name,location from DuplicateFound\n-> group by location\n-> having count(location) > 1;" }, { "code": null, "e": 3083, "s": 3055, "text": "The following is the output" }, { "code": null, "e": 3228, "s": 3083, "text": "+------+----------+\n| Name | Location |\n+------+----------+\n| John | US |\n| Bob | UK |\n+------+----------+\n2 rows in set (0.04 sec)" } ]
How to Split Text Using Regex in Golang? - GeeksforGeeks
25 Aug, 2020 What is regex? Is Regex the famous anime character? Oops, if you think so, you’re likely to be disappointed. The Go programming language uses the term regexp to denote Regular expressions. Regular expressions are very important in the field of string processing. The “regexp” package in Go holds all necessary pre-built functions that implement regular expression search and also guarantee a linear-time search in the size of the provided inputs. To know more about what regex is, read What is Regexp in Golang? Regexp package contains the Split function which helps in splitting the input text string. Before we jump into the depths of regexp split function, let us brief you over some basic regular expressions that are worth remembering while using the split function: [ ] [ ] Can be used for including or excluding a given range, or even mention specifically the characters that we want to include or exclude. [ ] means both inclusive in a range. “[b-f]an” ban, can, dan,ean, fan { } The curly brackets are used when one needs to match the frequency of the occurrence of any given expression. “gf{1,}g” gfg, gffg, gfffg,... ( ) “(b-f)an” ban, can, dan,ean, fan * * Matches 0/0+ occurrences of the character that precedes the star (‘*’). “gee*k” + + Matches 1/1+ occurrences of the character that precedes the plus (‘+’). “gee+k” geek, geeek,... ? “gee?k” gek, geek . Anything can replace the dot character, except a newline (\n). “g.g” gfg, gbg, gcg,... ^ Any text that starts with the string mentioned after ‘^’. Also used as a negation in groups or other regular expressions (NOT). “^ge” “[^0-8]*” ge, geek, geeks,... ‘ ‘,9, 99,999,... $ “$de” code, decode,... | \ “\A”“\\n”“\\s” etc.. \s “\\s” ” “, ” “, ” “,... \S “\\S” \d “\\d” 0, 1, 2, 3, 4, 5,6, 7, 8, 9 \D “\\D” Syntax: func Split(s: string, n: int) []string This function accepts a string and an integer and returns a slice of all substrings. The input string ‘s‘ is the string that will be further, split into substrings as per the given regular expression by Split function. ‘n‘ denotes the value that decides the number of substrings to be returned. If n > 0: It means that a maximum of n substrings undergo the regex operation and will be returned. If n = 1 then no regex the operation will be performed and hence, the original string will be returned. If n = 0: It means that no substrings will be returned, a nill shall be returned. If n < 0: It means that all the substrings that was created will be returned by the function. Example 1: Go package main import ( f "fmt" re "regexp" // we import the regexp package // as re) // SPLIT function hacks// In layman terms, whenever the// string (given to split as argument)// occurs, the string is split into// a substring. func main() { // str stores a sample string as shown below str := "I am at GFG!\nYou can call me at 9087651234." // just printing the original string: str f.Println(str) // We shall consider two scenarios // in this example code // Scenario 1: // Store a regex object that // contains digits only // in obj1. obj1 := re.MustCompile("\\d*") // Scenario 2: // Store a regex object that // contains everything except digits // in obj2. obj2 := re.MustCompile("\\D*") // Using obj1 as reference, we // are splitting the string: str // and -1 denotes that all substrings // ever created will be included. first := obj1.Split(str, -1) // "first" holds all the substrings // split from str w.r.t obj1 in a container // A container like, say a list. // Using obj2 as reference, we // are splitting the string: str // and -1 denotes that all substrings // ever created will be included. second := obj2.Split(str, -1) // "second" holds all the substrings // split from str w.r.t obj2 in a container // A container like, say a list. f.Println("Now printing text split by obj1...") for _, p := range first { f.Println(p) } f.Println("Now printing text split by obj2...") for _, q := range second { f.Println(q) }} Command to Execute: > go run (your_file_name).go Output: I am at GFG! You can call me at 9087651234. Now printing text split by obj1... I a m a t G F G ! Y o u c a n c a l l m e a t . Now printing text split by obj2... 9 0 8 7 6 5 1 2 3 4 Visual I/O demo on Visual Studio Code: Code output on-screen upon running the above-written code. Example 2: Go package main import ( f "fmt" re "regexp") // Simple example code to understand// 1. Function of Split function// 2. Parameters of split function// regex-object.Split(string: , n: ) func main() { // Sample string that will be used in this // example "GeeksforGeeks loves bananas" str := "GeeksforGeeks loves bananas" f.Println(str) f.Println("Part-1: Excluding all vowels from given string") // a regexp object (geek) for storing all vowels geek := re.MustCompile("[aeiou]") f.Print("Printing all substring lists = ") // Checking split for n = -1 f.Println(geek.Split(str, -1)) f.Print("For n = 0 substring list = ") // Checking split for n = 0 f.Println(geek.Split(str, 0)) f.Print("For n = 1 substring list = ") // Checking split for n = 1 f.Println(geek.Split(str, 1)) f.Print("For n = 10 substring list = ") // Checking split for n = 10 f.Println(geek.Split(str, 10)) f.Print("For n = 100 substring list = ") // Checking split for n = 100 f.Println(geek.Split(str, 100)) f.Println("\n\nPart-2: Extracting all vowels from given string") // a regexp object (geek) for storing all consonants geek = re.MustCompile("[^aeiou]") f.Print("Printing all substring lists = ") // Checking split for n = -1 f.Println(geek.Split(str, -1)) f.Print("For n = 0 substring list = ") // Checking split for n = 0 f.Println(geek.Split(str, 0)) f.Print("For n = 1 substring list = ") // Checking split for n = 1 f.Println(geek.Split(str, 1)) f.Print("For n = 10 substring list = ") // Checking split for n = 10 f.Println(geek.Split(str, 10)) f.Print("For n = 100 substring list = ") // Checking split for n = 100 f.Println(geek.Split(str, 100)) // Did you notice that split function // does not modify the original regex // matching object?} Command to Execute: > go run (your_file_name).go Output: GeeksforGeeks loves bananas Part-1: Excluding all vowels from given string Printing all substring lists = [G ksf rG ks l v s b n n s] For n = 0 substring list = [] For n = 1 substring list = [GeeksforGeeks loves bananas] For n = 10 substring list = [G ksf rG ks l v s b n nas] For n = 100 substring list = [G ksf rG ks l v s b n n s] Part-2: Extracting all vowels from given string Printing all substring lists = [ ee o ee o e a a a ] For n = 0 substring list = [] For n = 1 substring list = [GeeksforGeeks loves bananas] For n = 10 substring list = [ ee o ee loves bananas] For n = 100 substring list = [ ee o ee o e a a a ] Visual I/O demo on Visual Studio Code: Code output on-screen upon running the above-written code. Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Golang Maps Slices in Golang How to Trim a String in Golang? How to Parse JSON in Golang? Interfaces in Golang Pointers in Golang strings.Join() Function in Golang With Examples Defer Keyword in Golang Time Durations in Golang Data Types in Go
[ { "code": null, "e": 24366, "s": 24338, "text": "\n25 Aug, 2020" }, { "code": null, "e": 24879, "s": 24366, "text": "What is regex? Is Regex the famous anime character? Oops, if you think so, you’re likely to be disappointed. The Go programming language uses the term regexp to denote Regular expressions. Regular expressions are very important in the field of string processing. The “regexp” package in Go holds all necessary pre-built functions that implement regular expression search and also guarantee a linear-time search in the size of the provided inputs. To know more about what regex is, read What is Regexp in Golang? " }, { "code": null, "e": 25139, "s": 24879, "text": "Regexp package contains the Split function which helps in splitting the input text string. Before we jump into the depths of regexp split function, let us brief you over some basic regular expressions that are worth remembering while using the split function:" }, { "code": null, "e": 25143, "s": 25139, "text": "[ ]" }, { "code": null, "e": 25319, "s": 25143, "text": " [ ] Can be used for including or excluding a given range, or even mention specifically the characters that we want to include or exclude. [ ] means both inclusive in a range." }, { "code": null, "e": 25329, "s": 25319, "text": "“[b-f]an”" }, { "code": null, "e": 25352, "s": 25329, "text": "ban, can, dan,ean, fan" }, { "code": null, "e": 25356, "s": 25352, "text": "{ }" }, { "code": null, "e": 25467, "s": 25356, "text": " The curly brackets are used when one needs to match the frequency of the occurrence of any given expression." }, { "code": null, "e": 25477, "s": 25467, "text": "“gf{1,}g”" }, { "code": null, "e": 25498, "s": 25477, "text": "gfg, gffg, gfffg,..." }, { "code": null, "e": 25502, "s": 25498, "text": "( )" }, { "code": null, "e": 25512, "s": 25502, "text": "“(b-f)an”" }, { "code": null, "e": 25535, "s": 25512, "text": "ban, can, dan,ean, fan" }, { "code": null, "e": 25537, "s": 25535, "text": "*" }, { "code": null, "e": 25612, "s": 25537, "text": " * Matches 0/0+ occurrences of the character that precedes the star (‘*’)." }, { "code": null, "e": 25620, "s": 25612, "text": "“gee*k”" }, { "code": null, "e": 25622, "s": 25620, "text": "+" }, { "code": null, "e": 25697, "s": 25622, "text": " + Matches 1/1+ occurrences of the character that precedes the plus (‘+’)." }, { "code": null, "e": 25705, "s": 25697, "text": "“gee+k”" }, { "code": null, "e": 25721, "s": 25705, "text": "geek, geeek,..." }, { "code": null, "e": 25723, "s": 25721, "text": "?" }, { "code": null, "e": 25731, "s": 25723, "text": "“gee?k”" }, { "code": null, "e": 25741, "s": 25731, "text": "gek, geek" }, { "code": null, "e": 25743, "s": 25741, "text": "." }, { "code": null, "e": 25807, "s": 25743, "text": " Anything can replace the dot character, except a newline (\\n)." }, { "code": null, "e": 25813, "s": 25807, "text": "“g.g”" }, { "code": null, "e": 25831, "s": 25813, "text": "gfg, gbg, gcg,..." }, { "code": null, "e": 25833, "s": 25831, "text": "^" }, { "code": null, "e": 25892, "s": 25833, "text": " Any text that starts with the string mentioned after ‘^’." }, { "code": null, "e": 25963, "s": 25892, "text": " Also used as a negation in groups or other regular expressions (NOT)." }, { "code": null, "e": 25969, "s": 25963, "text": "“^ge”" }, { "code": null, "e": 25979, "s": 25969, "text": "“[^0-8]*”" }, { "code": null, "e": 25999, "s": 25979, "text": "ge, geek, geeks,..." }, { "code": null, "e": 26017, "s": 25999, "text": "‘ ‘,9, 99,999,..." }, { "code": null, "e": 26019, "s": 26017, "text": "$" }, { "code": null, "e": 26025, "s": 26019, "text": "“$de”" }, { "code": null, "e": 26042, "s": 26025, "text": "code, decode,..." }, { "code": null, "e": 26044, "s": 26042, "text": "|" }, { "code": null, "e": 26046, "s": 26044, "text": "\\" }, { "code": null, "e": 26067, "s": 26046, "text": "“\\A”“\\\\n”“\\\\s” etc.." }, { "code": null, "e": 26070, "s": 26067, "text": "\\s" }, { "code": null, "e": 26076, "s": 26070, "text": "“\\\\s”" }, { "code": null, "e": 26097, "s": 26076, "text": "” “, ” “, ” “,..." }, { "code": null, "e": 26100, "s": 26097, "text": "\\S" }, { "code": null, "e": 26106, "s": 26100, "text": "“\\\\S”" }, { "code": null, "e": 26111, "s": 26108, "text": "\\d" }, { "code": null, "e": 26117, "s": 26111, "text": "“\\\\d”" }, { "code": null, "e": 26145, "s": 26117, "text": "0, 1, 2, 3, 4, 5,6, 7, 8, 9" }, { "code": null, "e": 26148, "s": 26145, "text": "\\D" }, { "code": null, "e": 26154, "s": 26148, "text": "“\\\\D”" }, { "code": null, "e": 26162, "s": 26154, "text": "Syntax:" }, { "code": null, "e": 26202, "s": 26162, "text": "func Split(s: string, n: int) []string\n" }, { "code": null, "e": 26498, "s": 26202, "text": "This function accepts a string and an integer and returns a slice of all substrings. The input string ‘s‘ is the string that will be further, split into substrings as per the given regular expression by Split function. ‘n‘ denotes the value that decides the number of substrings to be returned. " }, { "code": null, "e": 26598, "s": 26498, "text": "If n > 0: It means that a maximum of n substrings undergo the regex operation and will be returned." }, { "code": null, "e": 26702, "s": 26598, "text": "If n = 1 then no regex the operation will be performed and hence, the original string will be returned." }, { "code": null, "e": 26784, "s": 26702, "text": "If n = 0: It means that no substrings will be returned, a nill shall be returned." }, { "code": null, "e": 26879, "s": 26784, "text": "If n < 0: It means that all the substrings that was created will be returned by the function." }, { "code": null, "e": 26890, "s": 26879, "text": "Example 1:" }, { "code": null, "e": 26893, "s": 26890, "text": "Go" }, { "code": "package main import ( f \"fmt\" re \"regexp\" // we import the regexp package // as re) // SPLIT function hacks// In layman terms, whenever the// string (given to split as argument)// occurs, the string is split into// a substring. func main() { // str stores a sample string as shown below str := \"I am at GFG!\\nYou can call me at 9087651234.\" // just printing the original string: str f.Println(str) // We shall consider two scenarios // in this example code // Scenario 1: // Store a regex object that // contains digits only // in obj1. obj1 := re.MustCompile(\"\\\\d*\") // Scenario 2: // Store a regex object that // contains everything except digits // in obj2. obj2 := re.MustCompile(\"\\\\D*\") // Using obj1 as reference, we // are splitting the string: str // and -1 denotes that all substrings // ever created will be included. first := obj1.Split(str, -1) // \"first\" holds all the substrings // split from str w.r.t obj1 in a container // A container like, say a list. // Using obj2 as reference, we // are splitting the string: str // and -1 denotes that all substrings // ever created will be included. second := obj2.Split(str, -1) // \"second\" holds all the substrings // split from str w.r.t obj2 in a container // A container like, say a list. f.Println(\"Now printing text split by obj1...\") for _, p := range first { f.Println(p) } f.Println(\"Now printing text split by obj2...\") for _, q := range second { f.Println(q) }}", "e": 28494, "s": 26893, "text": null }, { "code": null, "e": 28514, "s": 28494, "text": "Command to Execute:" }, { "code": null, "e": 28544, "s": 28514, "text": "> go run (your_file_name).go\n" }, { "code": null, "e": 28552, "s": 28544, "text": "Output:" }, { "code": null, "e": 28746, "s": 28552, "text": "I am at GFG!\nYou can call me at 9087651234.\nNow printing text split by obj1...\nI\n\na\nm\n\na\nt\n\nG\nF\nG\n!\n\n\nY\no\nu\n\nc\na\nn\n\nc\na\nl\nl\n\nm\ne\n\na\nt\n\n.\nNow printing text split by obj2...\n\n9\n0\n8\n7\n6\n5\n1\n2\n3\n4\n" }, { "code": null, "e": 28785, "s": 28746, "text": "Visual I/O demo on Visual Studio Code:" }, { "code": null, "e": 28844, "s": 28785, "text": "Code output on-screen upon running the above-written code." }, { "code": null, "e": 28855, "s": 28844, "text": "Example 2:" }, { "code": null, "e": 28858, "s": 28855, "text": "Go" }, { "code": "package main import ( f \"fmt\" re \"regexp\") // Simple example code to understand// 1. Function of Split function// 2. Parameters of split function// regex-object.Split(string: , n: ) func main() { // Sample string that will be used in this // example \"GeeksforGeeks loves bananas\" str := \"GeeksforGeeks loves bananas\" f.Println(str) f.Println(\"Part-1: Excluding all vowels from given string\") // a regexp object (geek) for storing all vowels geek := re.MustCompile(\"[aeiou]\") f.Print(\"Printing all substring lists = \") // Checking split for n = -1 f.Println(geek.Split(str, -1)) f.Print(\"For n = 0 substring list = \") // Checking split for n = 0 f.Println(geek.Split(str, 0)) f.Print(\"For n = 1 substring list = \") // Checking split for n = 1 f.Println(geek.Split(str, 1)) f.Print(\"For n = 10 substring list = \") // Checking split for n = 10 f.Println(geek.Split(str, 10)) f.Print(\"For n = 100 substring list = \") // Checking split for n = 100 f.Println(geek.Split(str, 100)) f.Println(\"\\n\\nPart-2: Extracting all vowels from given string\") // a regexp object (geek) for storing all consonants geek = re.MustCompile(\"[^aeiou]\") f.Print(\"Printing all substring lists = \") // Checking split for n = -1 f.Println(geek.Split(str, -1)) f.Print(\"For n = 0 substring list = \") // Checking split for n = 0 f.Println(geek.Split(str, 0)) f.Print(\"For n = 1 substring list = \") // Checking split for n = 1 f.Println(geek.Split(str, 1)) f.Print(\"For n = 10 substring list = \") // Checking split for n = 10 f.Println(geek.Split(str, 10)) f.Print(\"For n = 100 substring list = \") // Checking split for n = 100 f.Println(geek.Split(str, 100)) // Did you notice that split function // does not modify the original regex // matching object?}", "e": 30806, "s": 28858, "text": null }, { "code": null, "e": 30826, "s": 30806, "text": "Command to Execute:" }, { "code": null, "e": 30856, "s": 30826, "text": "> go run (your_file_name).go\n" }, { "code": null, "e": 30864, "s": 30856, "text": "Output:" }, { "code": null, "e": 31520, "s": 30864, "text": "GeeksforGeeks loves bananas\nPart-1: Excluding all vowels from given string\nPrinting all substring lists = [G ksf rG ks l v s b n n s]\nFor n = 0 substring list = []\nFor n = 1 substring list = [GeeksforGeeks loves bananas]\nFor n = 10 substring list = [G ksf rG ks l v s b n nas]\nFor n = 100 substring list = [G ksf rG ks l v s b n n s]\n\n\nPart-2: Extracting all vowels from given string\nPrinting all substring lists = [ ee o ee o e a a a ]\nFor n = 0 substring list = []\nFor n = 1 substring list = [GeeksforGeeks loves bananas]\nFor n = 10 substring list = [ ee o ee loves bananas]\nFor n = 100 substring list = [ ee o ee o e a a a ]\n" }, { "code": null, "e": 31559, "s": 31520, "text": "Visual I/O demo on Visual Studio Code:" }, { "code": null, "e": 31618, "s": 31559, "text": "Code output on-screen upon running the above-written code." }, { "code": null, "e": 31630, "s": 31618, "text": "Go Language" }, { "code": null, "e": 31728, "s": 31630, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31740, "s": 31728, "text": "Golang Maps" }, { "code": null, "e": 31757, "s": 31740, "text": "Slices in Golang" }, { "code": null, "e": 31789, "s": 31757, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 31818, "s": 31789, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 31839, "s": 31818, "text": "Interfaces in Golang" }, { "code": null, "e": 31858, "s": 31839, "text": "Pointers in Golang" }, { "code": null, "e": 31906, "s": 31858, "text": "strings.Join() Function in Golang With Examples" }, { "code": null, "e": 31930, "s": 31906, "text": "Defer Keyword in Golang" }, { "code": null, "e": 31955, "s": 31930, "text": "Time Durations in Golang" } ]
Scala - Options
Scala Option[ T ] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map. Option type is used frequently in Scala programs and you can compare this with the null value available in Java which indicate no value. For example, the get method of java.util.HashMap returns either a value stored in the HashMap, or null if no value was found. Let's say we have a method that retrieves a record from the database based on a primary key. def findPerson(key: Int): Option[Person] The method will return Some[Person] if the record is found but None if the record is not found. Let us follow the following program. object Demo { def main(args: Array[String]) { val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo") println("capitals.get( \"France\" ) : " + capitals.get( "France" )) println("capitals.get( \"India\" ) : " + capitals.get( "India" )) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo capitals.get( "France" ) : Some(Paris) capitals.get( "India" ) : None The most common way to take optional values apart is through a pattern match. For example try the following program. object Demo { def main(args: Array[String]) { val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo") println("show(capitals.get( \"Japan\")) : " + show(capitals.get( "Japan")) ) println("show(capitals.get( \"India\")) : " + show(capitals.get( "India")) ) } def show(x: Option[String]) = x match { case Some(s) => s case None => "?" } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo show(capitals.get( "Japan")) : Tokyo show(capitals.get( "India")) : ? Following is the example program to show how to use getOrElse() method to access a value or a default when no value is present. object Demo { def main(args: Array[String]) { val a:Option[Int] = Some(5) val b:Option[Int] = None println("a.getOrElse(0): " + a.getOrElse(0) ) println("b.getOrElse(10): " + b.getOrElse(10) ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo a.getOrElse(0): 5 b.getOrElse(10): 10 Following is the example program to show how to use isEmpty() method to check if the option is None or not. object Demo { def main(args: Array[String]) { val a:Option[Int] = Some(5) val b:Option[Int] = None println("a.isEmpty: " + a.isEmpty ) println("b.isEmpty: " + b.isEmpty ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo a.isEmpty: false b.isEmpty: true Following are the important methods which you can use while playing with Options. For a complete list of methods available, please check official documentation of Scala. def get: A Returns the option's value. def isEmpty: Boolean Returns true if the option is None, false otherwise. def productArity: Int The size of this product. For a product A(x_1, ..., x_k), returns k def productElement(n: Int): Any The nth element of this product, 0-based. In other words, for a product A(x_1, ..., x_k), returns x_(n+1) where 0 < n < k. def exists(p: (A) => Boolean): Boolean Returns true if this option is nonempty and the predicate p returns true when applied to this Option's value. Otherwise, returns false. def filter(p: (A) => Boolean): Option[A] Returns this Option if it is nonempty and applying the predicate p to this Option's value returns true. Otherwise, return None. def filterNot(p: (A) => Boolean): Option[A] Returns this Option if it is nonempty and applying the predicate p to this Option's value returns false. Otherwise, return None. def flatMap[B](f: (A) => Option[B]): Option[B] Returns the result of applying f to this Option's value if this Option is nonempty. Returns None if this Option is empty. def foreach[U](f: (A) => U): Unit Apply the given procedure f to the option's value, if it is nonempty. Otherwise, do nothing. def getOrElse[B >: A](default: => B): B Returns the option's value if the option is nonempty, otherwise return the result of evaluating default. def isDefined: Boolean Returns true if the option is an instance of Some, false otherwise. def iterator: Iterator[A] Returns a singleton iterator returning the Option's value if it is nonempty, or an empty iterator if the option is empty. def map[B](f: (A) => B): Option[B] Returns a Some containing the result of applying f to this Option's value if this Option is nonempty. Otherwise return None. def orElse[B >: A](alternative: => Option[B]): Option[B] Returns this Option if it is nonempty, otherwise return the result of evaluating alternative. def orNull Returns the option's value if it is nonempty, or null if it is empty. 82 Lectures 7 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 76 Lectures 5.5 hours Bigdata Engineer 69 Lectures 7.5 hours Bigdata Engineer 46 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2330, "s": 1998, "text": "Scala Option[ T ] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map." }, { "code": null, "e": 2594, "s": 2330, "text": "Option type is used frequently in Scala programs and you can compare this with the null value available in Java which indicate no value. For example, the get method of java.util.HashMap returns either a value stored in the HashMap, or null if no value was found." }, { "code": null, "e": 2687, "s": 2594, "text": "Let's say we have a method that retrieves a record from the database based on a primary key." }, { "code": null, "e": 2729, "s": 2687, "text": "def findPerson(key: Int): Option[Person]\n" }, { "code": null, "e": 2862, "s": 2729, "text": "The method will return Some[Person] if the record is found but None if the record is not found. Let us follow the following program." }, { "code": null, "e": 3139, "s": 2862, "text": "object Demo {\n def main(args: Array[String]) {\n val capitals = Map(\"France\" -> \"Paris\", \"Japan\" -> \"Tokyo\")\n \n println(\"capitals.get( \\\"France\\\" ) : \" + capitals.get( \"France\" ))\n println(\"capitals.get( \\\"India\\\" ) : \" + capitals.get( \"India\" ))\n }\n}" }, { "code": null, "e": 3246, "s": 3139, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 3280, "s": 3246, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 3351, "s": 3280, "text": "capitals.get( \"France\" ) : Some(Paris)\ncapitals.get( \"India\" ) : None\n" }, { "code": null, "e": 3468, "s": 3351, "text": "The most common way to take optional values apart is through a pattern match. For example try the following program." }, { "code": null, "e": 3862, "s": 3468, "text": "object Demo {\n def main(args: Array[String]) {\n val capitals = Map(\"France\" -> \"Paris\", \"Japan\" -> \"Tokyo\")\n \n println(\"show(capitals.get( \\\"Japan\\\")) : \" + show(capitals.get( \"Japan\")) )\n println(\"show(capitals.get( \\\"India\\\")) : \" + show(capitals.get( \"India\")) )\n }\n \n def show(x: Option[String]) = x match {\n case Some(s) => s\n case None => \"?\"\n }\n}" }, { "code": null, "e": 3969, "s": 3862, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 4003, "s": 3969, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 4074, "s": 4003, "text": "show(capitals.get( \"Japan\")) : Tokyo\nshow(capitals.get( \"India\")) : ?\n" }, { "code": null, "e": 4202, "s": 4074, "text": "Following is the example program to show how to use getOrElse() method to access a value or a default when no value is present." }, { "code": null, "e": 4437, "s": 4202, "text": "object Demo {\n def main(args: Array[String]) {\n val a:Option[Int] = Some(5)\n val b:Option[Int] = None \n \n println(\"a.getOrElse(0): \" + a.getOrElse(0) )\n println(\"b.getOrElse(10): \" + b.getOrElse(10) )\n }\n}" }, { "code": null, "e": 4544, "s": 4437, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 4578, "s": 4544, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 4617, "s": 4578, "text": "a.getOrElse(0): 5\nb.getOrElse(10): 10\n" }, { "code": null, "e": 4725, "s": 4617, "text": "Following is the example program to show how to use isEmpty() method to check if the option is None or not." }, { "code": null, "e": 4938, "s": 4725, "text": "object Demo {\n def main(args: Array[String]) {\n val a:Option[Int] = Some(5)\n val b:Option[Int] = None \n \n println(\"a.isEmpty: \" + a.isEmpty )\n println(\"b.isEmpty: \" + b.isEmpty )\n }\n}" }, { "code": null, "e": 5045, "s": 4938, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 5079, "s": 5045, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 5113, "s": 5079, "text": "a.isEmpty: false\nb.isEmpty: true\n" }, { "code": null, "e": 5283, "s": 5113, "text": "Following are the important methods which you can use while playing with Options. For a complete list of methods available, please check official documentation of Scala." }, { "code": null, "e": 5294, "s": 5283, "text": "def get: A" }, { "code": null, "e": 5322, "s": 5294, "text": "Returns the option's value." }, { "code": null, "e": 5343, "s": 5322, "text": "def isEmpty: Boolean" }, { "code": null, "e": 5396, "s": 5343, "text": "Returns true if the option is None, false otherwise." }, { "code": null, "e": 5418, "s": 5396, "text": "def productArity: Int" }, { "code": null, "e": 5486, "s": 5418, "text": "The size of this product. For a product A(x_1, ..., x_k), returns k" }, { "code": null, "e": 5518, "s": 5486, "text": "def productElement(n: Int): Any" }, { "code": null, "e": 5641, "s": 5518, "text": "The nth element of this product, 0-based. In other words, for a product A(x_1, ..., x_k), returns x_(n+1) where 0 < n < k." }, { "code": null, "e": 5680, "s": 5641, "text": "def exists(p: (A) => Boolean): Boolean" }, { "code": null, "e": 5816, "s": 5680, "text": "Returns true if this option is nonempty and the predicate p returns true when applied to this Option's value. Otherwise, returns false." }, { "code": null, "e": 5857, "s": 5816, "text": "def filter(p: (A) => Boolean): Option[A]" }, { "code": null, "e": 5985, "s": 5857, "text": "Returns this Option if it is nonempty and applying the predicate p to this Option's value returns true. Otherwise, return None." }, { "code": null, "e": 6029, "s": 5985, "text": "def filterNot(p: (A) => Boolean): Option[A]" }, { "code": null, "e": 6158, "s": 6029, "text": "Returns this Option if it is nonempty and applying the predicate p to this Option's value returns false. Otherwise, return None." }, { "code": null, "e": 6205, "s": 6158, "text": "def flatMap[B](f: (A) => Option[B]): Option[B]" }, { "code": null, "e": 6327, "s": 6205, "text": "Returns the result of applying f to this Option's value if this Option is nonempty. Returns None if this Option is empty." }, { "code": null, "e": 6361, "s": 6327, "text": "def foreach[U](f: (A) => U): Unit" }, { "code": null, "e": 6454, "s": 6361, "text": "Apply the given procedure f to the option's value, if it is nonempty. Otherwise, do nothing." }, { "code": null, "e": 6494, "s": 6454, "text": "def getOrElse[B >: A](default: => B): B" }, { "code": null, "e": 6599, "s": 6494, "text": "Returns the option's value if the option is nonempty, otherwise return the result of evaluating default." }, { "code": null, "e": 6622, "s": 6599, "text": "def isDefined: Boolean" }, { "code": null, "e": 6690, "s": 6622, "text": "Returns true if the option is an instance of Some, false otherwise." }, { "code": null, "e": 6716, "s": 6690, "text": "def iterator: Iterator[A]" }, { "code": null, "e": 6838, "s": 6716, "text": "Returns a singleton iterator returning the Option's value if it is nonempty, or an empty iterator if the option is empty." }, { "code": null, "e": 6873, "s": 6838, "text": "def map[B](f: (A) => B): Option[B]" }, { "code": null, "e": 6998, "s": 6873, "text": "Returns a Some containing the result of applying f to this Option's value if this Option is nonempty. Otherwise return None." }, { "code": null, "e": 7055, "s": 6998, "text": "def orElse[B >: A](alternative: => Option[B]): Option[B]" }, { "code": null, "e": 7149, "s": 7055, "text": "Returns this Option if it is nonempty, otherwise return the result of evaluating alternative." }, { "code": null, "e": 7160, "s": 7149, "text": "def orNull" }, { "code": null, "e": 7230, "s": 7160, "text": "Returns the option's value if it is nonempty, or null if it is empty." }, { "code": null, "e": 7263, "s": 7230, "text": "\n 82 Lectures \n 7 hours \n" }, { "code": null, "e": 7282, "s": 7263, "text": " Arnab Chakraborty" }, { "code": null, "e": 7317, "s": 7282, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7338, "s": 7317, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 7373, "s": 7338, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7391, "s": 7373, "text": " Bigdata Engineer" }, { "code": null, "e": 7426, "s": 7391, "text": "\n 76 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7444, "s": 7426, "text": " Bigdata Engineer" }, { "code": null, "e": 7479, "s": 7444, "text": "\n 69 Lectures \n 7.5 hours \n" }, { "code": null, "e": 7497, "s": 7479, "text": " Bigdata Engineer" }, { "code": null, "e": 7532, "s": 7497, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7555, "s": 7532, "text": " Stone River ELearning" }, { "code": null, "e": 7562, "s": 7555, "text": " Print" }, { "code": null, "e": 7573, "s": 7562, "text": " Add Notes" } ]
Print common characters of two Strings in alphabetical order in C++
In this programming problem, we are given two strings. And we have to find all the characters of the string that are common in both the string and we have to print these common characters in alphabetical order. And print ‘NO COMMON CHARACTERS ’ found if no common letters arise. Given that the string does not contain all lower case alphabets. Let’s take an example − Input : string1 : adsfhslf string2 : fsrakf Output : affs Explanation − Between the two strings there are a, f, s. Hence the lexicographical output is ‘afs’. Input : string1 : abcde string2 : glhyte Output : No common characters Explanation − There are no characters are in common. To solve this problem, we need to find common characters in the string. And the output will be the lexicographical order of these string. Algorithm to solve this problem is − Step 1 : Create two arrays a1[] and a2[] of size 26 each for counting the number of alphabets in the strings string1 and string2. Step 2 : traverse a1[] and a2[]. and in sequence print all those numbers that have values in the array. Let's create a program based on this algorithm to illustrate the working − Live Demo #include<bits/stdc++.h> using namespace std; int main(){ string string1 = "adjfrdggs"; string string2 = "gktressd"; cout<<"The strings are "<<string1<<" and "<<string2; cout<<"\nThe common characters are : "; int a1[26] = {0}; int a2[26] = {0}; int i , j; char ch; char ch1 = 'a'; int k = (int)ch1, m; for(i = 0 ; i < string1.length() ; i++){ a1[(int)string1[i] - k]++; } for(i = 0 ; i < string2.length() ; i++){ a2[(int)string2[i] - k]++; } for(i = 0 ; i < 26 ; i++){ if (a1[i] != 0 and a2[i] != 0){ for(j = 0 ; j < min(a1[i] , a2[i]) ; j++){ m = k + i; ch = (char)(k + i); cout << ch; } } } return 0; } The strings are adjfrdggs and gktressd The common characters are : dgrs
[ { "code": null, "e": 1406, "s": 1062, "text": "In this programming problem, we are given two strings. And we have to find all the characters of the string that are common in both the string and we have to print these common characters in alphabetical order. And print ‘NO COMMON CHARACTERS ’ found if no common letters arise. Given that the string does not contain all lower case alphabets." }, { "code": null, "e": 1430, "s": 1406, "text": "Let’s take an example −" }, { "code": null, "e": 1491, "s": 1430, "text": "Input : string1 : adsfhslf\n string2 : fsrakf\nOutput : affs" }, { "code": null, "e": 1591, "s": 1491, "text": "Explanation − Between the two strings there are a, f, s. Hence the lexicographical output is ‘afs’." }, { "code": null, "e": 1665, "s": 1591, "text": "Input : string1 : abcde\n string2 : glhyte\nOutput : No common characters" }, { "code": null, "e": 1718, "s": 1665, "text": "Explanation − There are no characters are in common." }, { "code": null, "e": 1856, "s": 1718, "text": "To solve this problem, we need to find common characters in the string. And the output will be the lexicographical order of these string." }, { "code": null, "e": 1893, "s": 1856, "text": "Algorithm to solve this problem is −" }, { "code": null, "e": 2127, "s": 1893, "text": "Step 1 : Create two arrays a1[] and a2[] of size 26 each for counting the number of alphabets in the strings string1 and string2.\nStep 2 : traverse a1[] and a2[]. and in sequence print all those numbers that have values in the array." }, { "code": null, "e": 2202, "s": 2127, "text": "Let's create a program based on this algorithm to illustrate the working −" }, { "code": null, "e": 2213, "s": 2202, "text": " Live Demo" }, { "code": null, "e": 2947, "s": 2213, "text": "#include<bits/stdc++.h>\nusing namespace std;\nint main(){\n string string1 = \"adjfrdggs\";\n string string2 = \"gktressd\";\n cout<<\"The strings are \"<<string1<<\" and \"<<string2;\n cout<<\"\\nThe common characters are : \";\n int a1[26] = {0};\n int a2[26] = {0};\n int i , j;\n char ch;\n char ch1 = 'a';\n int k = (int)ch1, m;\n for(i = 0 ; i < string1.length() ; i++){\n a1[(int)string1[i] - k]++;\n }\n for(i = 0 ; i < string2.length() ; i++){\n a2[(int)string2[i] - k]++;\n }\n for(i = 0 ; i < 26 ; i++){\n if (a1[i] != 0 and a2[i] != 0){\n for(j = 0 ; j < min(a1[i] , a2[i]) ; j++){\n m = k + i;\n ch = (char)(k + i);\n cout << ch;\n }\n }\n }\n return 0;\n}" }, { "code": null, "e": 3019, "s": 2947, "text": "The strings are adjfrdggs and gktressd\nThe common characters are : dgrs" } ]
DSL - ADSL Fundamentals
In this chapter, we will discuss the fundamentals and standards of Asymmetric Digital Subscriber Line. To begin with, let us understand the following points. Discrete Multi-Tone (DMT) modulation used by all ADSL standards for a physical layer. Discrete Multi-Tone (DMT) modulation used by all ADSL standards for a physical layer. Divide the frequency band into many small channels. Divide the frequency band into many small channels. QAM modulation on each channel. QAM modulation on each channel. Different bits assigned to each channel in terms of SNR. Different bits assigned to each channel in terms of SNR. Following is the ADSL Fundamentals System Block Diagram for PHY. The following table describes the ADSL Standards. G.992.1 Annex A − Full rate ADSL over POTs Overlapped Spectrum PSD Masks Non-overlapped Spectrum PSD Masks G.992.1 Annex B − Full rate ADSL over ISDN Overlapped Spectrum PSD Masks only, however, overlap is optional G.992.1 Annex C − Full rate ADSL in TCM-ISDN binder PSD Mask as for G.992.1 Annex A The following illustration describes G.DMT PSDs. The G.Dmt Performance can be understood by the following description. NSC = number of sub carriers Sub carrier spacing = Δ f = 4.3125 KHz Data symbol rate = 4.0 KHz Data rate = N * 4 * 8 Kbps (multiples of 32 Kbps) Bandwidth = NSC * Δ f Sample rate = 2* NSC *Δ f NSC 256 Total bandwidth 1.1 MHz Sample rate 2.2 MHz Maximum Date Rate ~12Mbps(down)/1.2Mbps (up) Maximum Reach 20kf While DMT was chosen as the official standard, systems based on the CAP have been used worldwide to implement many ADSL and a line of video sounds trials and commercial deployments, determine effectively the CAP as a de facto standard ADSL competition. Meanwhile, the threat of offering telephony services in the industry of cable television in the United States largely subsided. Globally, the tone video applications have increased, but continues to maintain interest. In many markets, they were difficult to justify the cost in relation to the widespread availability of cable TV and satellite TV. As a result, the video dial tone initiatives have largely disappeared in North America. The final standard for ADSL - approved by the International Telecommunication Union (ITU) (G.dmt or G.992) and ANSI (T1.413 Issue 2) – was, as mentioned earlier, a DMT-based system and is the basis of most new ADSL deployments today. Some vendors, however, continued to deploy PAC-based systems in their networks. Throughout these long tone trial video dialing, the industry has come to recognize that many data applications were made asymmetrical. The best example of this is the internet. Typically, users send a small stream of data to a remote server, which requests the download of a data file, graphic, audio and video in particular. In response, the server starts sending the file data rate that can be supported over the network to the remote workstation. This transaction is extremely asymmetrical in nature. During this same time, the Internet has evolved into a completely new phenomenon, which is unheard of, when compared to the rate of the new subscribers to the Internet growth services. The biggest complaint of all users is that it took too long to upload files to the modem dial or even ISDN data rates. Therefore, a new need of services and new technology were soon married, and ADSL has been reoriented to support Internet access. Video has not completely disappeared as a request for DSL. However, video delivery over IP − using systems such as RealMedia or Windows Media – has become increasingly popular and sophisticated. Using compression systems such as MPEG-2 or new industry standard systems that allow even compression of the video, IP video delivery continues to be a viable application for DSL. When the application was a bit synchronous video, the DSL line had to run at a specified line speed. However, the data can be operated at a wide range of speeds. The only effect is that slower speeds take longer to transport large files. Therefore, with data applications, we have the possibility of reducing the line speed to allow the service to be provisioned over longer lines. Both CAP and DMT transceivers have been modified to optimize the service on a loop basis and its implementation was called Adaptive Rate Digital Subscriber Line, or RADSL. RADSL technology supports the ability to allow the transceiver to automatically-increase the line speed to the highest achievable data rate, which can be achieved reliably over a given loop. Although this feature was designed primarily to simplify the service facility, it also gives service providers the possibility of a graceful degradation of service in case of degrading loop conditions. Today, there are other DSL technologies, which support the adaptation of rates. The service providers interested in this feature should examine the extent to which it is supported in different technologies. As it can be seen, industry and technology have changed dramatically since the tone Video ADSL standards decision in March 1993. In recognition of this Working Group, T1E1 ANSI has established a standard known as ANSI TR59 RADSL. The FCC has specifically cited RADSL as a technology that is spectrally compatible with voice and other DSL technologies in the local loop. In some cases, DSL concepts have been applied to existing technologies. For example, ISDN DSL or IDSL, first emerged as a new spin technology of the 1980's just IDSL ISDN CPE (customer premises equipment) talking to ISDN-compatible line cards that located on the other end of the copper wire loop and terminate the ISDN signal independent of the telephone switch. In this scenario, as with all DSL variants, the data service is directed to an extended data service, rather than of a switched network. While IDSL is based on proven technology, it is functionally an ISDN subset in that it waives any possibility to support the switched telephone service and connectivity in general. A key advantage of IDSL is the service provider seeking to move long-term ISDN data connections to Internet servers or remote LAN access off the switched network. Another key benefit is that because IDSL uses ISDN signaling methods, it is capable of transmitting over copper pairs that are served by digital loop carriers. These devices, which are remote terminals designed to extend the reach of POTS and ISDN services beyond the usual scope of central office on completion of the copper lines, are often connected to the central office by the fiber optical private line and, as such, cannot carry any type of ADSL and SDSL DSL signals. Beyond the bandwidth of 144 Kbps provided by IDSL, there are new technologies that have emerged that can be better-classified office / small office and residential home (SOHO) possibilities. These technologies offer operating ranges between 128 Kbps and 2.048 Mbps. For symmetric applications, Multirate SDSL (M / SDSL) has emerged as a valuable technology to meet the requirements of carriers to deliver Time Division Multiplex (TDM) services on an almost ubiquitous base. Based on the single pair SDSL technology, M / SDSL supports changing rate of command line transceiver and thus the operating distance of the transceiver. This version of CAP supports eight separate rates for a service 64 Kbps / 128 Kbps to 29 kft (8.9 km) 24-gauge wire (5mm) and 15 kft (4.5 km) at a speed of 2 Mbps in full. With a capacity of AutoRate (similar to RADSL), symmetric applications can now be universally deployed. In January 1998, the Universal ADSL Working Group (UAWG) was announced. It composed of large organizations in the telecommunications, networks and personal computers. This group was formed to develop low speed and the alternative cost of ADSL that could be installed, while the consumers were rapidly deployed by service providers. The result of the work of this group is a new subset of ADSL G.lite based standards. G.lite was approved as a standard by the ITU (G.992.2) in June 1999 and can offer speeds up to 1.5 Mbps downstream and 512 Kbps upstream. Significantly, G.lite was designed to provide this service on existing telephone lines without the POTS splitter usually required by ADSL solutions at the full rate. A part of the G.lite, standard is as "fast retrain" known technique which limits the input power of the G.lite signal, when a telephone handset is in use. This helps to minimize interference and restore power, when the phone is back on the hook. Following are the benefits of ReachDSL. Splitterless installation − No POTS splitter is required at the customer premises, simplifying installation and allowing customer self-installation. Splitterless installation − No POTS splitter is required at the customer premises, simplifying installation and allowing customer self-installation. Greater loop reach − In addition to ADSL systems, which can generally reach distances below 18,000 feet from the central office, the ReachDSL systems extend well beyond services 20,000 feet, with some power plants above 30,000 feet as well. Greater loop reach − In addition to ADSL systems, which can generally reach distances below 18,000 feet from the central office, the ReachDSL systems extend well beyond services 20,000 feet, with some power plants above 30,000 feet as well. Spectral compatibility − ReachDSL solutions offer superior spectral compatibility. A member of the family ReachDSL, MVL® (multiple virtual lines), was the first DSL system recognized by the FCC in section 68 approval, which means that it is "friendly" to other services over the telephone network and not a jammer. ReachDSL also operates in spectrum management class to offer better range and higher speed. Spectral compatibility − ReachDSL solutions offer superior spectral compatibility. A member of the family ReachDSL, MVL® (multiple virtual lines), was the first DSL system recognized by the FCC in section 68 approval, which means that it is "friendly" to other services over the telephone network and not a jammer. ReachDSL also operates in spectrum management class to offer better range and higher speed. Lower product cost − ReachDSL products utilize "off the shelf" rather than customized Digital Signal Processors (DSPs). Lower product cost − ReachDSL products utilize "off the shelf" rather than customized Digital Signal Processors (DSPs). Dynamic bandwidth allocation − Allows the service to be customized for different applications. Dynamic bandwidth allocation − Allows the service to be customized for different applications. There are new variants that are emerging like – VDSL, DSL, or DSL high speed. VDSL systems are still being developed, so that the final capacity is not yet well established, but the proposed standards require downstream bandwidths up to 52 Mbps symmetrical bandwidth up to 26 Mbps. The compromise in these bandwidths is a shorter loop section, often as short as 1000 feet for higher bandwidths possible bands, with adaptation of speed at lower speeds than the length of the loop increases. Given these limitations, VDSL deployments are planned to use a slightly different model than the traditional DSL, DSLAM with the move out of the central office of the telephone company and the neighborhood, with lines of optical fibers supplying local cabinets containing DSLAM. The high speeds offered by VDSL bring opportunities for service providers to deliver the next generation of DSL services, with the video being considered as a first application. At 52 Mbps, a VDSL line can offer a customer complete multi-channel MPEG-2 video stream quality and even offer one or more television channels in high definition full quality (HDTV). Some service providers have started VDSL systems deployment tests that provide these services with the endpoint VDSL appearing in the residence as a set-top box such as cable TV with an Ethernet or other data interface for connection to a PC for simultaneous data services. The basic principle of DSL is a local loop technology in which compatible devices reside on each end of a single copper wire loop ensures that new DSL technologies continue to emerge over time. A strategic point for the service provider is to ensure that the selection of a specific technology or DSL network model for the deployment of services today will not limit options to adopt new technologies in the future. The following points describe why ADSL2 is so favorable ADSL provides up to 8Mbps/800Kbps data rate (possibly 12M/1.2M). ADSL provides up to 8Mbps/800Kbps data rate (possibly 12M/1.2M). Reach of 18-20kf 26AWG (about 6000m). Reach of 18-20kf 26AWG (about 6000m). No seamless rate change. No seamless rate change. No power saving mode when there is no user activity. No power saving mode when there is no user activity. No 1-bit per bin and partial byte per symbol. No 1-bit per bin and partial byte per symbol. Fixed 64Kbps overhead channel rate (Framing Structure3). Fixed 64Kbps overhead channel rate (Framing Structure3). The following points describe the various features of ADSL2/ADSL2+. ADSL2+ provides up to 24Mbps/1Mbps data rate. ADSL2+ provides up to 24Mbps/1Mbps data rate. Seamless rate adaptation when SNR change. Seamless rate adaptation when SNR change. Power Management greatly reduce power consumption. Power Management greatly reduce power consumption. 1-bit per bin and partial byte per symbol improves reach. 1-bit per bin and partial byte per symbol improves reach. Reach of 20-22kf 26AWG (about 7000m). Reach of 20-22kf 26AWG (about 7000m). Variable overhead channel rate meets user need. Variable overhead channel rate meets user need. Loop diagnostic function during training. Loop diagnostic function during training. ADSL2 and ADSL2+ Delivers next generation features to improve the DSL deployment business case. Following are some of its benefits − Higher Rates Extended Reach Improved Stability Power Management Enhanced Spectral Compatibilit ADSL2 enables service providers to extend existing rates plans at longer loop lengths using rate enhancement technologies − Rate Enhancement Technology − Reduced framing Overhead Mandatory Trellis Coding 1-bit constellations Data on pilot tone Long Reach DSL (LDSL) − RE-ADSL2 Boosted PSD for North America Overlapped Mode The following features help in framing enhancement. More flexible framing structure More flexible framing structure Replaced Framing Structure types 0, 1, 2 and 3 in G.DMT Replaced Framing Structure types 0, 1, 2 and 3 in G.DMT Receiver selects configuration parameters Receiver selects configuration parameters Optimal Reed-Solomon coding possible Optimal Reed-Solomon coding possible Configurable overhead channel from 4Kbps to 64Kbps Configurable overhead channel from 4Kbps to 64Kbps HDLC based OAM protocol to retrieve detailed performance monitoring information. HDLC based OAM protocol to retrieve detailed performance monitoring information. The following features help in PMD enhancement − training. New line diagnostic procedures. New line diagnostic procedures. Receiver selects pilot tone. Receiver selects pilot tone. Improved SNR measurement during channel analysis. Improved SNR measurement during channel analysis. Improved exchange of detailed transmit signal characteristics. Improved exchange of detailed transmit signal characteristics. Tone blackout to allow RFI measurement during initialization. Tone blackout to allow RFI measurement during initialization. The following features help in PMD enhancement − performance. Mandatory support of trellis coding. Mandatory support of trellis coding. Mandatory support of one-bit constellation. Mandatory support of one-bit constellation. Data modulated on pilot tone. Data modulated on pilot tone. Improved RFI robustness with receiver determined tone ordering. Improved RFI robustness with receiver determined tone ordering. The following features help in PMD enhancement − power. Transmit power cutback. Transmit power cutback. Mandatory transmit power reduction. Mandatory transmit power reduction. Power saving feature for ATU-C with new L2 low power state. Power saving feature for ATU-C with new L2 low power state. Power saving feature with new L3 idle state. Power saving feature with new L3 idle state. The following features help in PMD enhancement – dynamic. Bit-swapping Bit-swapping Seamless Rate Adaptation (SRA) Seamless Rate Adaptation (SRA) Dynamic Rate Repartitioning (DDR) Dynamic Rate Repartitioning (DDR) The following points describe why OLR is required. DSL line condition changes all the time crosstalk, weather, radio, environment, etc. DSL line condition changes all the time crosstalk, weather, radio, environment, etc. User activity changes all the time on/off hook, peak/normal usage. User activity changes all the time on/off hook, peak/normal usage. Operator bandwidth re-allocation. Operator bandwidth re-allocation. The following points tell us regarding OLR Maintain seamless operation when line or environment are slowly changing. Maintain seamless operation when line or environment are slowly changing. Optimize rate setting (6dB margin could be reduced). Optimize rate setting (6dB margin could be reduced). Upper layer provisioning provided. Upper layer provisioning provided. All channels can operate independently. All channels can operate independently. Following are the types of OLR. Bit Swapping (BS) − Relocates data and power among sub-carriers Adapt varying line condition Seamless Rate Adaptation (SRA) − Reconfigure the total data rate Background SNR monitoring can find optimal setting Dynamic Rate Repartitioning (DRR) − Reconfigure the data rate allocation between multiple latency paths. Following are the control parameters for Framer Configuration and PMD Function. Framer Configuration − Bpn − The number of octets from frame bearer #n in latency path #p. Bpn − The number of octets from frame bearer #n in latency path #p. Lp − The number of bits per symbol from latency path #p. Lp − The number of bits per symbol from latency path #p. PMD Function − bi, gi L − Total data rate Seamless Rate Adaptation (SRA) enables the modem to change rates and bit loading to maintain a minimum per bin margin without re-training. GlobespanVirata Inc.’s ADSL2 compliant SRA can change individual bins or all bins at once. It enables rate changes & noise adaptation in seconds instead of minutes. The following table describes the summary of OLR. Receiver Transmitter Receiver Transmitter The following points describe the power management in OLR DSLAM power consumption at KW level and 24/7. DSLAM power consumption at KW level and 24/7. Lot of power can be saved. Lot of power can be saved. Around -40 dB TX power cut back saves 100mW per port. Around -40 dB TX power cut back saves 100mW per port. The 2000 port DSLAM can save 200W! The 2000 port DSLAM can save 200W! The benefits of maximum margin algorithm of OLR are as follows − Eliminates excess margin on the line. Eliminates excess margin on the line. Estimates line conditions and backs off Tx power during handshake. Estimates line conditions and backs off Tx power during handshake. Compatible with Legacy CPEs. Compatible with Legacy CPEs. Cuts Line driver power up to 60% on typical loops. Cuts Line driver power up to 60% on typical loops. It reduces overall power up to 50% during customer idle periods. The main objectives are Power Saving and cross-talk minimization. There are three Power Management states − L0 − full power data mode (as we have today) L0 − full power data mode (as we have today) L3 − idle mode (not attempting to start) L3 − idle mode (not attempting to start) L2 − low power mode by − L2 − low power mode by − Increasing power cutback value (<40dB) Increasing power cutback value (<40dB) Low bit rate Low bit rate The higher rated ADSL2+ technology enables the following − Enables higher rates for premium data, voice and video deployment. Enables higher rates for premium data, voice and video deployment. Enables data rates up to 26 Mb/s. Enables data rates up to 26 Mb/s. Extends reach of 10-12Mb/s by up to 2x over ADSL S=1/2 Extends reach of 10-12Mb/s by up to 2x over ADSL S=1/2 Optional remote bandplan enables deployment from Remote Cabinets without degradation of services from the CO. Optional remote bandplan enables deployment from Remote Cabinets without degradation of services from the CO. Individual bin disabling provides full compatibility with legacy services. Individual bin disabling provides full compatibility with legacy services. Auto-Detection of CPE capability enables compatibility with legacy CPEs Auto-Detection of CPE capability enables compatibility with legacy CPEs The following illustration depicts the ADSL/ADSL2 ATU-C TX Spectrum. The following illustration depicts the ADSL2+ ATU-C TX Spectrum. Following are the features of ADSL2+. Doubles downstream spectrum from 1.1MHz to 2.2 MHz with downstream bin number increased from 256 to 512. Doubles downstream spectrum from 1.1MHz to 2.2 MHz with downstream bin number increased from 256 to 512. Maximum downstream data rate increase from 8Mbps to 24Mbps. Maximum downstream data rate increase from 8Mbps to 24Mbps. Improved performance at short loop length. Improved performance at short loop length. Wider range for SRA and Power Management from 32Kbps to 24 Mbps. Wider range for SRA and Power Management from 32Kbps to 24 Mbps. The following points describe the performance of ADSL2+. ADSL+ and ADSL2+ enable high-speed asymmetric DSL applications as well as the traditional long reach DSL services. ADSL+ and ADSL2+ enable high-speed asymmetric DSL applications as well as the traditional long reach DSL services. Auto-Detection enables fallback to ADSL2 and legacy ADSL. Auto-Detection enables fallback to ADSL2 and legacy ADSL. ADSL2+/ G.Span enable 22/3 service without VDSL 1.5km reach limitations. ADSL2+/ G.Span enable 22/3 service without VDSL 1.5km reach limitations. Interoperable with legacy ADSL CPEs. Interoperable with legacy ADSL CPEs. Range Extended ADSL (RE-ADSL) is Annex L of G.992.3 Range Extended ADSL (RE-ADSL) is Annex L of G.992.3 Reach extended by 1- 2 kft Reach extended by 1- 2 kft The foundation of the specification has a mandatory non-overlapped PSD definition together with an optional overlapped PSD definition. The foundation of the specification has a mandatory non-overlapped PSD definition together with an optional overlapped PSD definition. Introduce to improve upstream rate Maximally double the upstream bins At cost of downstream if non-overlapping Up to 3Mbps upstream data rate The following table describes the various aspects of ADSL. 32 Lectures 7 hours Dean Arnett 21 Lectures 1 hours Joey Bettenbroek 23 Lectures 1 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 1863, "s": 1760, "text": "In this chapter, we will discuss the fundamentals and standards of Asymmetric Digital Subscriber Line." }, { "code": null, "e": 1918, "s": 1863, "text": "To begin with, let us understand the following points." }, { "code": null, "e": 2004, "s": 1918, "text": "Discrete Multi-Tone (DMT) modulation used by all ADSL standards for a physical layer." }, { "code": null, "e": 2090, "s": 2004, "text": "Discrete Multi-Tone (DMT) modulation used by all ADSL standards for a physical layer." }, { "code": null, "e": 2142, "s": 2090, "text": "Divide the frequency band into many small channels." }, { "code": null, "e": 2194, "s": 2142, "text": "Divide the frequency band into many small channels." }, { "code": null, "e": 2226, "s": 2194, "text": "QAM modulation on each channel." }, { "code": null, "e": 2258, "s": 2226, "text": "QAM modulation on each channel." }, { "code": null, "e": 2315, "s": 2258, "text": "Different bits assigned to each channel in terms of SNR." }, { "code": null, "e": 2372, "s": 2315, "text": "Different bits assigned to each channel in terms of SNR." }, { "code": null, "e": 2437, "s": 2372, "text": "Following is the ADSL Fundamentals System Block Diagram for PHY." }, { "code": null, "e": 2487, "s": 2437, "text": "The following table describes the ADSL Standards." }, { "code": null, "e": 2530, "s": 2487, "text": "G.992.1 Annex A − Full rate ADSL over POTs" }, { "code": null, "e": 2560, "s": 2530, "text": "Overlapped Spectrum PSD Masks" }, { "code": null, "e": 2596, "s": 2560, "text": "Non-overlapped Spectrum PSD Masks \n" }, { "code": null, "e": 2639, "s": 2596, "text": "G.992.1 Annex B − Full rate ADSL over ISDN" }, { "code": null, "e": 2704, "s": 2639, "text": "Overlapped Spectrum PSD Masks only, however, overlap is optional" }, { "code": null, "e": 2756, "s": 2704, "text": "G.992.1 Annex C − Full rate ADSL in TCM-ISDN binder" }, { "code": null, "e": 2788, "s": 2756, "text": "PSD Mask as for G.992.1 Annex A" }, { "code": null, "e": 2837, "s": 2788, "text": "The following illustration describes G.DMT PSDs." }, { "code": null, "e": 2907, "s": 2837, "text": "The G.Dmt Performance can be understood by the following description." }, { "code": null, "e": 2936, "s": 2907, "text": "NSC = number of sub carriers" }, { "code": null, "e": 2977, "s": 2936, "text": "Sub carrier spacing = Δ f = 4.3125 KHz \n" }, { "code": null, "e": 3004, "s": 2977, "text": "Data symbol rate = 4.0 KHz" }, { "code": null, "e": 3054, "s": 3004, "text": "Data rate = N * 4 * 8 Kbps (multiples of 32 Kbps)" }, { "code": null, "e": 3076, "s": 3054, "text": "Bandwidth = NSC * Δ f" }, { "code": null, "e": 3102, "s": 3076, "text": "Sample rate = 2* NSC *Δ f" }, { "code": null, "e": 3347, "s": 3102, "text": "NSC 256 \nTotal bandwidth 1.1 MHz \nSample rate 2.2 MHz \nMaximum Date Rate ~12Mbps(down)/1.2Mbps (up) \nMaximum Reach 20kf \n" }, { "code": null, "e": 3728, "s": 3347, "text": "While DMT was chosen as the official standard, systems based on the CAP have been used worldwide to implement many ADSL and a line of video sounds trials and commercial deployments, determine effectively the CAP as a de facto standard ADSL competition. Meanwhile, the threat of offering telephony services in the industry of cable television in the United States largely subsided." }, { "code": null, "e": 3948, "s": 3728, "text": "Globally, the tone video applications have increased, but continues to maintain interest. In many markets, they were difficult to justify the cost in relation to the widespread availability of cable TV and satellite TV." }, { "code": null, "e": 4350, "s": 3948, "text": "As a result, the video dial tone initiatives have largely disappeared in North America. The final standard for ADSL - approved by the International Telecommunication Union (ITU) (G.dmt or G.992) and ANSI (T1.413 Issue 2) – was, as mentioned earlier, a DMT-based system and is the basis of most new ADSL deployments today. Some vendors, however, continued to deploy PAC-based systems in their networks." }, { "code": null, "e": 4854, "s": 4350, "text": "Throughout these long tone trial video dialing, the industry has come to recognize that many data applications were made asymmetrical. The best example of this is the internet. Typically, users send a small stream of data to a remote server, which requests the download of a data file, graphic, audio and video in particular. In response, the server starts sending the file data rate that can be supported over the network to the remote workstation. This transaction is extremely asymmetrical in nature." }, { "code": null, "e": 5287, "s": 4854, "text": "During this same time, the Internet has evolved into a completely new phenomenon, which is unheard of, when compared to the rate of the new subscribers to the Internet growth services. The biggest complaint of all users is that it took too long to upload files to the modem dial or even ISDN data rates. Therefore, a new need of services and new technology were soon married, and ADSL has been reoriented to support Internet access." }, { "code": null, "e": 5662, "s": 5287, "text": "Video has not completely disappeared as a request for DSL. However, video delivery over IP − using systems such as RealMedia or Windows Media – has become increasingly popular and sophisticated. Using compression systems such as MPEG-2 or new industry standard systems that allow even compression of the video, IP video delivery continues to be a viable application for DSL." }, { "code": null, "e": 6216, "s": 5662, "text": "When the application was a bit synchronous video, the DSL line had to run at a specified line speed. However, the data can be operated at a wide range of speeds. The only effect is that slower speeds take longer to transport large files. Therefore, with data applications, we have the possibility of reducing the line speed to allow the service to be provisioned over longer lines. Both CAP and DMT transceivers have been modified to optimize the service on a loop basis and its implementation was called Adaptive Rate Digital Subscriber Line, or RADSL." }, { "code": null, "e": 6816, "s": 6216, "text": "RADSL technology supports the ability to allow the transceiver to automatically-increase the line speed to the highest achievable data rate, which can be achieved reliably over a given loop. Although this feature was designed primarily to simplify the service facility, it also gives service providers the possibility of a graceful degradation of service in case of degrading loop conditions. Today, there are other DSL technologies, which support the adaptation of rates. The service providers interested in this feature should examine the extent to which it is supported in different technologies." }, { "code": null, "e": 7186, "s": 6816, "text": "As it can be seen, industry and technology have changed dramatically since the tone Video ADSL standards decision in March 1993. In recognition of this Working Group, T1E1 ANSI has established a standard known as ANSI TR59 RADSL. The FCC has specifically cited RADSL as a technology that is spectrally compatible with voice and other DSL technologies in the local loop." }, { "code": null, "e": 7550, "s": 7186, "text": "In some cases, DSL concepts have been applied to existing technologies. For example, ISDN DSL or IDSL, first emerged as a new spin technology of the 1980's just IDSL ISDN CPE (customer premises equipment) talking to ISDN-compatible line cards that located on the other end of the copper wire loop and terminate the ISDN signal independent of the telephone switch." }, { "code": null, "e": 8191, "s": 7550, "text": "In this scenario, as with all DSL variants, the data service is directed to an extended data service, rather than of a switched network. While IDSL is based on proven technology, it is functionally an ISDN subset in that it waives any possibility to support the switched telephone service and connectivity in general. A key advantage of IDSL is the service provider seeking to move long-term ISDN data connections to Internet servers or remote LAN access off the switched network. Another key benefit is that because IDSL uses ISDN signaling methods, it is capable of transmitting over copper pairs that are served by digital loop carriers." }, { "code": null, "e": 8506, "s": 8191, "text": "These devices, which are remote terminals designed to extend the reach of POTS and ISDN services beyond the usual scope of central office on completion of the copper lines, are often connected to the central office by the fiber optical private line and, as such, cannot carry any type of ADSL and SDSL DSL signals." }, { "code": null, "e": 8772, "s": 8506, "text": "Beyond the bandwidth of 144 Kbps provided by IDSL, there are new technologies that have emerged that can be better-classified office / small office and residential home (SOHO) possibilities. These technologies offer operating ranges between 128 Kbps and 2.048 Mbps." }, { "code": null, "e": 9410, "s": 8772, "text": "For symmetric applications, Multirate SDSL (M / SDSL) has emerged as a valuable technology to meet the requirements of carriers to deliver Time Division Multiplex (TDM) services on an almost ubiquitous base. Based on the single pair SDSL technology, M / SDSL supports changing rate of command line transceiver and thus the operating distance of the transceiver. This version of CAP supports eight separate rates for a service 64 Kbps / 128 Kbps to 29 kft (8.9 km) 24-gauge wire (5mm) and 15 kft (4.5 km) at a speed of 2 Mbps in full. With a capacity of AutoRate (similar to RADSL), symmetric applications can now be universally deployed." }, { "code": null, "e": 9827, "s": 9410, "text": "In January 1998, the Universal ADSL Working Group (UAWG) was announced. It composed of large organizations in the telecommunications, networks and personal computers. This group was formed to develop low speed and the alternative cost of ADSL that could be installed, while the consumers were rapidly deployed by service providers. The result of the work of this group is a new subset of ADSL G.lite based standards." }, { "code": null, "e": 10377, "s": 9827, "text": "G.lite was approved as a standard by the ITU (G.992.2) in June 1999 and can offer speeds up to 1.5 Mbps downstream and 512 Kbps upstream. Significantly, G.lite was designed to provide this service on existing telephone lines without the POTS splitter usually required by ADSL solutions at the full rate. A part of the G.lite, standard is as \"fast retrain\" known technique which limits the input power of the G.lite signal, when a telephone handset is in use. This helps to minimize interference and restore power, when the phone is back on the hook." }, { "code": null, "e": 10417, "s": 10377, "text": "Following are the benefits of ReachDSL." }, { "code": null, "e": 10566, "s": 10417, "text": "Splitterless installation − No POTS splitter is required at the customer premises, simplifying installation and allowing customer self-installation." }, { "code": null, "e": 10715, "s": 10566, "text": "Splitterless installation − No POTS splitter is required at the customer premises, simplifying installation and allowing customer self-installation." }, { "code": null, "e": 10956, "s": 10715, "text": "Greater loop reach − In addition to ADSL systems, which can generally reach distances below 18,000 feet from the central office, the ReachDSL systems extend well beyond services 20,000 feet, with some power plants above 30,000 feet as well." }, { "code": null, "e": 11197, "s": 10956, "text": "Greater loop reach − In addition to ADSL systems, which can generally reach distances below 18,000 feet from the central office, the ReachDSL systems extend well beyond services 20,000 feet, with some power plants above 30,000 feet as well." }, { "code": null, "e": 11604, "s": 11197, "text": "Spectral compatibility − ReachDSL solutions offer superior spectral compatibility. A member of the family ReachDSL, MVL® (multiple virtual lines), was the first DSL system recognized by the FCC in section 68 approval, which means that it is \"friendly\" to other services over the telephone network and not a jammer. ReachDSL also operates in spectrum management class to offer better range and higher speed." }, { "code": null, "e": 12011, "s": 11604, "text": "Spectral compatibility − ReachDSL solutions offer superior spectral compatibility. A member of the family ReachDSL, MVL® (multiple virtual lines), was the first DSL system recognized by the FCC in section 68 approval, which means that it is \"friendly\" to other services over the telephone network and not a jammer. ReachDSL also operates in spectrum management class to offer better range and higher speed." }, { "code": null, "e": 12131, "s": 12011, "text": "Lower product cost − ReachDSL products utilize \"off the shelf\" rather than customized Digital Signal Processors (DSPs)." }, { "code": null, "e": 12251, "s": 12131, "text": "Lower product cost − ReachDSL products utilize \"off the shelf\" rather than customized Digital Signal Processors (DSPs)." }, { "code": null, "e": 12346, "s": 12251, "text": "Dynamic bandwidth allocation − Allows the service to be customized for different applications." }, { "code": null, "e": 12441, "s": 12346, "text": "Dynamic bandwidth allocation − Allows the service to be customized for different applications." }, { "code": null, "e": 12931, "s": 12441, "text": "There are new variants that are emerging like – VDSL, DSL, or DSL high speed. VDSL systems are still being developed, so that the final capacity is not yet well established, but the proposed standards require downstream bandwidths up to 52 Mbps symmetrical bandwidth up to 26 Mbps. The compromise in these bandwidths is a shorter loop section, often as short as 1000 feet for higher bandwidths possible bands, with adaptation of speed at lower speeds than the length of the loop increases." }, { "code": null, "e": 13210, "s": 12931, "text": "Given these limitations, VDSL deployments are planned to use a slightly different model than the traditional DSL, DSLAM with the move out of the central office of the telephone company and the neighborhood, with lines of optical fibers supplying local cabinets containing DSLAM." }, { "code": null, "e": 13571, "s": 13210, "text": "The high speeds offered by VDSL bring opportunities for service providers to deliver the next generation of DSL services, with the video being considered as a first application. At 52 Mbps, a VDSL line can offer a customer complete multi-channel MPEG-2 video stream quality and even offer one or more television channels in high definition full quality (HDTV)." }, { "code": null, "e": 13845, "s": 13571, "text": "Some service providers have started VDSL systems deployment tests that provide these services with the endpoint VDSL appearing in the residence as a set-top box such as cable TV with an Ethernet or other data interface for connection to a PC for simultaneous data services." }, { "code": null, "e": 14261, "s": 13845, "text": "The basic principle of DSL is a local loop technology in which compatible devices reside on each end of a single copper wire loop ensures that new DSL technologies continue to emerge over time. A strategic point for the service provider is to ensure that the selection of a specific technology or DSL network model for the deployment of services today will not limit options to adopt new technologies in the future." }, { "code": null, "e": 14317, "s": 14261, "text": "The following points describe why ADSL2 is so favorable" }, { "code": null, "e": 14382, "s": 14317, "text": "ADSL provides up to 8Mbps/800Kbps data rate (possibly 12M/1.2M)." }, { "code": null, "e": 14447, "s": 14382, "text": "ADSL provides up to 8Mbps/800Kbps data rate (possibly 12M/1.2M)." }, { "code": null, "e": 14485, "s": 14447, "text": "Reach of 18-20kf 26AWG (about 6000m)." }, { "code": null, "e": 14523, "s": 14485, "text": "Reach of 18-20kf 26AWG (about 6000m)." }, { "code": null, "e": 14548, "s": 14523, "text": "No seamless rate change." }, { "code": null, "e": 14573, "s": 14548, "text": "No seamless rate change." }, { "code": null, "e": 14626, "s": 14573, "text": "No power saving mode when there is no user activity." }, { "code": null, "e": 14679, "s": 14626, "text": "No power saving mode when there is no user activity." }, { "code": null, "e": 14725, "s": 14679, "text": "No 1-bit per bin and partial byte per symbol." }, { "code": null, "e": 14771, "s": 14725, "text": "No 1-bit per bin and partial byte per symbol." }, { "code": null, "e": 14828, "s": 14771, "text": "Fixed 64Kbps overhead channel rate (Framing Structure3)." }, { "code": null, "e": 14885, "s": 14828, "text": "Fixed 64Kbps overhead channel rate (Framing Structure3)." }, { "code": null, "e": 14953, "s": 14885, "text": "The following points describe the various features of ADSL2/ADSL2+." }, { "code": null, "e": 14999, "s": 14953, "text": "ADSL2+ provides up to 24Mbps/1Mbps data rate." }, { "code": null, "e": 15045, "s": 14999, "text": "ADSL2+ provides up to 24Mbps/1Mbps data rate." }, { "code": null, "e": 15087, "s": 15045, "text": "Seamless rate adaptation when SNR change." }, { "code": null, "e": 15129, "s": 15087, "text": "Seamless rate adaptation when SNR change." }, { "code": null, "e": 15180, "s": 15129, "text": "Power Management greatly reduce power consumption." }, { "code": null, "e": 15231, "s": 15180, "text": "Power Management greatly reduce power consumption." }, { "code": null, "e": 15289, "s": 15231, "text": "1-bit per bin and partial byte per symbol improves reach." }, { "code": null, "e": 15347, "s": 15289, "text": "1-bit per bin and partial byte per symbol improves reach." }, { "code": null, "e": 15385, "s": 15347, "text": "Reach of 20-22kf 26AWG (about 7000m)." }, { "code": null, "e": 15423, "s": 15385, "text": "Reach of 20-22kf 26AWG (about 7000m)." }, { "code": null, "e": 15471, "s": 15423, "text": "Variable overhead channel rate meets user need." }, { "code": null, "e": 15519, "s": 15471, "text": "Variable overhead channel rate meets user need." }, { "code": null, "e": 15561, "s": 15519, "text": "Loop diagnostic function during training." }, { "code": null, "e": 15603, "s": 15561, "text": "Loop diagnostic function during training." }, { "code": null, "e": 15736, "s": 15603, "text": "ADSL2 and ADSL2+ Delivers next generation features to improve the DSL deployment business case. Following are some of its benefits −" }, { "code": null, "e": 15749, "s": 15736, "text": "Higher Rates" }, { "code": null, "e": 15764, "s": 15749, "text": "Extended Reach" }, { "code": null, "e": 15783, "s": 15764, "text": "Improved Stability" }, { "code": null, "e": 15800, "s": 15783, "text": "Power Management" }, { "code": null, "e": 15831, "s": 15800, "text": "Enhanced Spectral Compatibilit" }, { "code": null, "e": 15955, "s": 15831, "text": "ADSL2 enables service providers to extend existing rates plans at longer loop lengths using rate enhancement technologies −" }, { "code": null, "e": 15985, "s": 15955, "text": "Rate Enhancement Technology −" }, { "code": null, "e": 16010, "s": 15985, "text": "Reduced framing Overhead" }, { "code": null, "e": 16035, "s": 16010, "text": "Mandatory Trellis Coding" }, { "code": null, "e": 16056, "s": 16035, "text": "1-bit constellations" }, { "code": null, "e": 16076, "s": 16056, "text": "Data on pilot tone " }, { "code": null, "e": 16100, "s": 16076, "text": "Long Reach DSL (LDSL) −" }, { "code": null, "e": 16139, "s": 16100, "text": "RE-ADSL2 Boosted PSD for North America" }, { "code": null, "e": 16155, "s": 16139, "text": "Overlapped Mode" }, { "code": null, "e": 16207, "s": 16155, "text": "The following features help in framing enhancement." }, { "code": null, "e": 16239, "s": 16207, "text": "More flexible framing structure" }, { "code": null, "e": 16271, "s": 16239, "text": "More flexible framing structure" }, { "code": null, "e": 16327, "s": 16271, "text": "Replaced Framing Structure types 0, 1, 2 and 3 in G.DMT" }, { "code": null, "e": 16383, "s": 16327, "text": "Replaced Framing Structure types 0, 1, 2 and 3 in G.DMT" }, { "code": null, "e": 16425, "s": 16383, "text": "Receiver selects configuration parameters" }, { "code": null, "e": 16467, "s": 16425, "text": "Receiver selects configuration parameters" }, { "code": null, "e": 16504, "s": 16467, "text": "Optimal Reed-Solomon coding possible" }, { "code": null, "e": 16541, "s": 16504, "text": "Optimal Reed-Solomon coding possible" }, { "code": null, "e": 16592, "s": 16541, "text": "Configurable overhead channel from 4Kbps to 64Kbps" }, { "code": null, "e": 16643, "s": 16592, "text": "Configurable overhead channel from 4Kbps to 64Kbps" }, { "code": null, "e": 16724, "s": 16643, "text": "HDLC based OAM protocol to retrieve detailed performance monitoring information." }, { "code": null, "e": 16805, "s": 16724, "text": "HDLC based OAM protocol to retrieve detailed performance monitoring information." }, { "code": null, "e": 16864, "s": 16805, "text": "The following features help in PMD enhancement − training." }, { "code": null, "e": 16896, "s": 16864, "text": "New line diagnostic procedures." }, { "code": null, "e": 16928, "s": 16896, "text": "New line diagnostic procedures." }, { "code": null, "e": 16957, "s": 16928, "text": "Receiver selects pilot tone." }, { "code": null, "e": 16986, "s": 16957, "text": "Receiver selects pilot tone." }, { "code": null, "e": 17036, "s": 16986, "text": "Improved SNR measurement during channel analysis." }, { "code": null, "e": 17086, "s": 17036, "text": "Improved SNR measurement during channel analysis." }, { "code": null, "e": 17149, "s": 17086, "text": "Improved exchange of detailed transmit signal characteristics." }, { "code": null, "e": 17212, "s": 17149, "text": "Improved exchange of detailed transmit signal characteristics." }, { "code": null, "e": 17274, "s": 17212, "text": "Tone blackout to allow RFI measurement during initialization." }, { "code": null, "e": 17336, "s": 17274, "text": "Tone blackout to allow RFI measurement during initialization." }, { "code": null, "e": 17398, "s": 17336, "text": "The following features help in PMD enhancement − performance." }, { "code": null, "e": 17435, "s": 17398, "text": "Mandatory support of trellis coding." }, { "code": null, "e": 17472, "s": 17435, "text": "Mandatory support of trellis coding." }, { "code": null, "e": 17516, "s": 17472, "text": "Mandatory support of one-bit constellation." }, { "code": null, "e": 17560, "s": 17516, "text": "Mandatory support of one-bit constellation." }, { "code": null, "e": 17590, "s": 17560, "text": "Data modulated on pilot tone." }, { "code": null, "e": 17620, "s": 17590, "text": "Data modulated on pilot tone." }, { "code": null, "e": 17684, "s": 17620, "text": "Improved RFI robustness with receiver determined tone ordering." }, { "code": null, "e": 17748, "s": 17684, "text": "Improved RFI robustness with receiver determined tone ordering." }, { "code": null, "e": 17804, "s": 17748, "text": "The following features help in PMD enhancement − power." }, { "code": null, "e": 17828, "s": 17804, "text": "Transmit power cutback." }, { "code": null, "e": 17852, "s": 17828, "text": "Transmit power cutback." }, { "code": null, "e": 17888, "s": 17852, "text": "Mandatory transmit power reduction." }, { "code": null, "e": 17924, "s": 17888, "text": "Mandatory transmit power reduction." }, { "code": null, "e": 17984, "s": 17924, "text": "Power saving feature for ATU-C with new L2 low power state." }, { "code": null, "e": 18044, "s": 17984, "text": "Power saving feature for ATU-C with new L2 low power state." }, { "code": null, "e": 18089, "s": 18044, "text": "Power saving feature with new L3 idle state." }, { "code": null, "e": 18134, "s": 18089, "text": "Power saving feature with new L3 idle state." }, { "code": null, "e": 18192, "s": 18134, "text": "The following features help in PMD enhancement – dynamic." }, { "code": null, "e": 18205, "s": 18192, "text": "Bit-swapping" }, { "code": null, "e": 18218, "s": 18205, "text": "Bit-swapping" }, { "code": null, "e": 18249, "s": 18218, "text": "Seamless Rate Adaptation (SRA)" }, { "code": null, "e": 18280, "s": 18249, "text": "Seamless Rate Adaptation (SRA)" }, { "code": null, "e": 18314, "s": 18280, "text": "Dynamic Rate Repartitioning (DDR)" }, { "code": null, "e": 18348, "s": 18314, "text": "Dynamic Rate Repartitioning (DDR)" }, { "code": null, "e": 18399, "s": 18348, "text": "The following points describe why OLR is required." }, { "code": null, "e": 18484, "s": 18399, "text": "DSL line condition changes all the time crosstalk, weather, radio, environment, etc." }, { "code": null, "e": 18569, "s": 18484, "text": "DSL line condition changes all the time crosstalk, weather, radio, environment, etc." }, { "code": null, "e": 18636, "s": 18569, "text": "User activity changes all the time on/off hook, peak/normal usage." }, { "code": null, "e": 18703, "s": 18636, "text": "User activity changes all the time on/off hook, peak/normal usage." }, { "code": null, "e": 18737, "s": 18703, "text": "Operator bandwidth re-allocation." }, { "code": null, "e": 18771, "s": 18737, "text": "Operator bandwidth re-allocation." }, { "code": null, "e": 18814, "s": 18771, "text": "The following points tell us regarding OLR" }, { "code": null, "e": 18888, "s": 18814, "text": "Maintain seamless operation when line or environment are slowly changing." }, { "code": null, "e": 18962, "s": 18888, "text": "Maintain seamless operation when line or environment are slowly changing." }, { "code": null, "e": 19015, "s": 18962, "text": "Optimize rate setting (6dB margin could be reduced)." }, { "code": null, "e": 19068, "s": 19015, "text": "Optimize rate setting (6dB margin could be reduced)." }, { "code": null, "e": 19103, "s": 19068, "text": "Upper layer provisioning provided." }, { "code": null, "e": 19138, "s": 19103, "text": "Upper layer provisioning provided." }, { "code": null, "e": 19178, "s": 19138, "text": "All channels can operate independently." }, { "code": null, "e": 19218, "s": 19178, "text": "All channels can operate independently." }, { "code": null, "e": 19250, "s": 19218, "text": "Following are the types of OLR." }, { "code": null, "e": 19270, "s": 19250, "text": "Bit Swapping (BS) −" }, { "code": null, "e": 19314, "s": 19270, "text": "Relocates data and power among sub-carriers" }, { "code": null, "e": 19343, "s": 19314, "text": "Adapt varying line condition" }, { "code": null, "e": 19376, "s": 19343, "text": "Seamless Rate Adaptation (SRA) −" }, { "code": null, "e": 19408, "s": 19376, "text": "Reconfigure the total data rate" }, { "code": null, "e": 19459, "s": 19408, "text": "Background SNR monitoring can find optimal setting" }, { "code": null, "e": 19495, "s": 19459, "text": "Dynamic Rate Repartitioning (DRR) −" }, { "code": null, "e": 19564, "s": 19495, "text": "Reconfigure the data rate allocation between multiple latency paths." }, { "code": null, "e": 19644, "s": 19564, "text": "Following are the control parameters for Framer Configuration and PMD Function." }, { "code": null, "e": 19667, "s": 19644, "text": "Framer Configuration −" }, { "code": null, "e": 19735, "s": 19667, "text": "Bpn − The number of octets from frame bearer #n in latency path #p." }, { "code": null, "e": 19803, "s": 19735, "text": "Bpn − The number of octets from frame bearer #n in latency path #p." }, { "code": null, "e": 19860, "s": 19803, "text": "Lp − The number of bits per symbol from latency path #p." }, { "code": null, "e": 19917, "s": 19860, "text": "Lp − The number of bits per symbol from latency path #p." }, { "code": null, "e": 19932, "s": 19917, "text": "PMD Function −" }, { "code": null, "e": 19941, "s": 19932, "text": "bi, gi " }, { "code": null, "e": 19963, "s": 19941, "text": "L − Total data rate \n" }, { "code": null, "e": 20102, "s": 19963, "text": "Seamless Rate Adaptation (SRA) enables the modem to change rates and bit loading to maintain a minimum per bin margin without re-training." }, { "code": null, "e": 20267, "s": 20102, "text": "GlobespanVirata Inc.’s ADSL2 compliant SRA can change individual bins or all bins at once. It enables rate changes & noise adaptation in seconds instead of minutes." }, { "code": null, "e": 20317, "s": 20267, "text": "The following table describes the summary of OLR." }, { "code": null, "e": 20326, "s": 20317, "text": "Receiver" }, { "code": null, "e": 20338, "s": 20326, "text": "Transmitter" }, { "code": null, "e": 20347, "s": 20338, "text": "Receiver" }, { "code": null, "e": 20359, "s": 20347, "text": "Transmitter" }, { "code": null, "e": 20417, "s": 20359, "text": "The following points describe the power management in OLR" }, { "code": null, "e": 20463, "s": 20417, "text": "DSLAM power consumption at KW level and 24/7." }, { "code": null, "e": 20509, "s": 20463, "text": "DSLAM power consumption at KW level and 24/7." }, { "code": null, "e": 20536, "s": 20509, "text": "Lot of power can be saved." }, { "code": null, "e": 20563, "s": 20536, "text": "Lot of power can be saved." }, { "code": null, "e": 20617, "s": 20563, "text": "Around -40 dB TX power cut back saves 100mW per port." }, { "code": null, "e": 20671, "s": 20617, "text": "Around -40 dB TX power cut back saves 100mW per port." }, { "code": null, "e": 20706, "s": 20671, "text": "The 2000 port DSLAM can save 200W!" }, { "code": null, "e": 20741, "s": 20706, "text": "The 2000 port DSLAM can save 200W!" }, { "code": null, "e": 20806, "s": 20741, "text": "The benefits of maximum margin algorithm of OLR are as follows −" }, { "code": null, "e": 20844, "s": 20806, "text": "Eliminates excess margin on the line." }, { "code": null, "e": 20882, "s": 20844, "text": "Eliminates excess margin on the line." }, { "code": null, "e": 20949, "s": 20882, "text": "Estimates line conditions and backs off Tx power during handshake." }, { "code": null, "e": 21016, "s": 20949, "text": "Estimates line conditions and backs off Tx power during handshake." }, { "code": null, "e": 21045, "s": 21016, "text": "Compatible with Legacy CPEs." }, { "code": null, "e": 21074, "s": 21045, "text": "Compatible with Legacy CPEs." }, { "code": null, "e": 21125, "s": 21074, "text": "Cuts Line driver power up to 60% on typical loops." }, { "code": null, "e": 21176, "s": 21125, "text": "Cuts Line driver power up to 60% on typical loops." }, { "code": null, "e": 21241, "s": 21176, "text": "It reduces overall power up to 50% during customer idle periods." }, { "code": null, "e": 21349, "s": 21241, "text": "The main objectives are Power Saving and cross-talk minimization. There are three Power Management states −" }, { "code": null, "e": 21394, "s": 21349, "text": "L0 − full power data mode (as we have today)" }, { "code": null, "e": 21439, "s": 21394, "text": "L0 − full power data mode (as we have today)" }, { "code": null, "e": 21480, "s": 21439, "text": "L3 − idle mode (not attempting to start)" }, { "code": null, "e": 21521, "s": 21480, "text": "L3 − idle mode (not attempting to start)" }, { "code": null, "e": 21546, "s": 21521, "text": "L2 − low power mode by −" }, { "code": null, "e": 21571, "s": 21546, "text": "L2 − low power mode by −" }, { "code": null, "e": 21610, "s": 21571, "text": "Increasing power cutback value (<40dB)" }, { "code": null, "e": 21649, "s": 21610, "text": "Increasing power cutback value (<40dB)" }, { "code": null, "e": 21662, "s": 21649, "text": "Low bit rate" }, { "code": null, "e": 21675, "s": 21662, "text": "Low bit rate" }, { "code": null, "e": 21734, "s": 21675, "text": "The higher rated ADSL2+ technology enables the following −" }, { "code": null, "e": 21801, "s": 21734, "text": "Enables higher rates for premium data, voice and video deployment." }, { "code": null, "e": 21868, "s": 21801, "text": "Enables higher rates for premium data, voice and video deployment." }, { "code": null, "e": 21902, "s": 21868, "text": "Enables data rates up to 26 Mb/s." }, { "code": null, "e": 21936, "s": 21902, "text": "Enables data rates up to 26 Mb/s." }, { "code": null, "e": 21991, "s": 21936, "text": "Extends reach of 10-12Mb/s by up to 2x over ADSL S=1/2" }, { "code": null, "e": 22046, "s": 21991, "text": "Extends reach of 10-12Mb/s by up to 2x over ADSL S=1/2" }, { "code": null, "e": 22156, "s": 22046, "text": "Optional remote bandplan enables deployment from Remote Cabinets without degradation of services from the CO." }, { "code": null, "e": 22266, "s": 22156, "text": "Optional remote bandplan enables deployment from Remote Cabinets without degradation of services from the CO." }, { "code": null, "e": 22341, "s": 22266, "text": "Individual bin disabling provides full compatibility with legacy services." }, { "code": null, "e": 22416, "s": 22341, "text": "Individual bin disabling provides full compatibility with legacy services." }, { "code": null, "e": 22488, "s": 22416, "text": "Auto-Detection of CPE capability enables compatibility with legacy CPEs" }, { "code": null, "e": 22560, "s": 22488, "text": "Auto-Detection of CPE capability enables compatibility with legacy CPEs" }, { "code": null, "e": 22629, "s": 22560, "text": "The following illustration depicts the ADSL/ADSL2 ATU-C TX Spectrum." }, { "code": null, "e": 22694, "s": 22629, "text": "The following illustration depicts the ADSL2+ ATU-C TX Spectrum." }, { "code": null, "e": 22732, "s": 22694, "text": "Following are the features of ADSL2+." }, { "code": null, "e": 22837, "s": 22732, "text": "Doubles downstream spectrum from 1.1MHz to 2.2 MHz with downstream bin number increased from 256 to 512." }, { "code": null, "e": 22942, "s": 22837, "text": "Doubles downstream spectrum from 1.1MHz to 2.2 MHz with downstream bin number increased from 256 to 512." }, { "code": null, "e": 23002, "s": 22942, "text": "Maximum downstream data rate increase from 8Mbps to 24Mbps." }, { "code": null, "e": 23062, "s": 23002, "text": "Maximum downstream data rate increase from 8Mbps to 24Mbps." }, { "code": null, "e": 23105, "s": 23062, "text": "Improved performance at short loop length." }, { "code": null, "e": 23148, "s": 23105, "text": "Improved performance at short loop length." }, { "code": null, "e": 23213, "s": 23148, "text": "Wider range for SRA and Power Management from 32Kbps to 24 Mbps." }, { "code": null, "e": 23278, "s": 23213, "text": "Wider range for SRA and Power Management from 32Kbps to 24 Mbps." }, { "code": null, "e": 23335, "s": 23278, "text": "The following points describe the performance of ADSL2+." }, { "code": null, "e": 23450, "s": 23335, "text": "ADSL+ and ADSL2+ enable high-speed asymmetric DSL applications as well as the traditional long reach DSL services." }, { "code": null, "e": 23565, "s": 23450, "text": "ADSL+ and ADSL2+ enable high-speed asymmetric DSL applications as well as the traditional long reach DSL services." }, { "code": null, "e": 23623, "s": 23565, "text": "Auto-Detection enables fallback to ADSL2 and legacy ADSL." }, { "code": null, "e": 23681, "s": 23623, "text": "Auto-Detection enables fallback to ADSL2 and legacy ADSL." }, { "code": null, "e": 23754, "s": 23681, "text": "ADSL2+/ G.Span enable 22/3 service without VDSL 1.5km reach limitations." }, { "code": null, "e": 23827, "s": 23754, "text": "ADSL2+/ G.Span enable 22/3 service without VDSL 1.5km reach limitations." }, { "code": null, "e": 23864, "s": 23827, "text": "Interoperable with legacy ADSL CPEs." }, { "code": null, "e": 23901, "s": 23864, "text": "Interoperable with legacy ADSL CPEs." }, { "code": null, "e": 23953, "s": 23901, "text": "Range Extended ADSL (RE-ADSL) is Annex L of G.992.3" }, { "code": null, "e": 24005, "s": 23953, "text": "Range Extended ADSL (RE-ADSL) is Annex L of G.992.3" }, { "code": null, "e": 24032, "s": 24005, "text": "Reach extended by 1- 2 kft" }, { "code": null, "e": 24059, "s": 24032, "text": "Reach extended by 1- 2 kft" }, { "code": null, "e": 24194, "s": 24059, "text": "The foundation of the specification has a mandatory non-overlapped PSD definition together with an optional overlapped PSD definition." }, { "code": null, "e": 24329, "s": 24194, "text": "The foundation of the specification has a mandatory non-overlapped PSD definition together with an optional overlapped PSD definition." }, { "code": null, "e": 24365, "s": 24329, "text": "Introduce to improve upstream rate " }, { "code": null, "e": 24401, "s": 24365, "text": "Maximally double the upstream bins " }, { "code": null, "e": 24443, "s": 24401, "text": "At cost of downstream if non-overlapping " }, { "code": null, "e": 24475, "s": 24443, "text": "Up to 3Mbps upstream data rate " }, { "code": null, "e": 24534, "s": 24475, "text": "The following table describes the various aspects of ADSL." }, { "code": null, "e": 24567, "s": 24534, "text": "\n 32 Lectures \n 7 hours \n" }, { "code": null, "e": 24580, "s": 24567, "text": " Dean Arnett" }, { "code": null, "e": 24613, "s": 24580, "text": "\n 21 Lectures \n 1 hours \n" }, { "code": null, "e": 24631, "s": 24613, "text": " Joey Bettenbroek" }, { "code": null, "e": 24664, "s": 24631, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 24687, "s": 24664, "text": " Stone River ELearning" }, { "code": null, "e": 24694, "s": 24687, "text": " Print" }, { "code": null, "e": 24705, "s": 24694, "text": " Add Notes" } ]
JSTL - SQL <sql:update> Tag
The <sql:update> tag executes an SQL statement that does not return data; for example, SQL INSERT, UPDATE, or DELETE statements. The <sql:update> tag has the following attributes − To start with basic concept, let us create a simple table Employees table in the TEST database and create few records in that table as follows − Open a Command Prompt and change to the installation directory as follows − C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Login to the database as follows − C:\Program Files\MySQL\bin>mysql -u root -p Enter password: ******** mysql> Create the table Employee in the TEST database as follows − mysql> use TEST; mysql> create table Employees ( id int not null, age int not null, first varchar (255), last varchar (255) ); Query OK, 0 rows affected (0.08 sec) mysql> We will now create few records in the Employee table as follows − mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali'); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal'); Query OK, 1 row affected (0.00 sec) mysql> Let us now write a JSP which will make use of the <sql:update> tag to execute an SQL INSERT statement to create one record in the table as follows − <%@ page import = "java.io.*,java.util.*,java.sql.*"%> <%@ page import = "javax.servlet.http.*,javax.servlet.*" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%> <%@ taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%> <html> <head> <title>JSTL sql:update Tag</title> </head> <body> <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver" url = "jdbc:mysql://localhost/TEST" user = "root" password = "pass123"/> <sql:update dataSource = "${snapshot}" var = "count"> INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali'); </sql:update> <sql:query dataSource = "${snapshot}" var = "result"> SELECT * from Employees; </sql:query> <table border = "1" width = "100%"> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> <c:forEach var = "row" items = "${result.rows}"> <tr> <td> <c:out value = "${row.id}"/></td> <td> <c:out value = "${row.first}"/></td> <td> <c:out value = "${row.last}"/></td> <td> <c:out value = "${row.age}"/></td> </tr> </c:forEach> </table> </body> </html> Access the above JSP, the following result will be displayed − +-------------+----------------+-----------------+-----------------+ | Emp ID | First Name | Last Name | Age | +-------------+----------------+-----------------+-----------------+ | 100 | Zara | Ali | 18 | | 101 | Mahnaz | Fatma | 25 | | 102 | Zaid | Khan | 30 | | 103 | Sumit | Mittal | 28 | | 104 | Nula | Ali | 2 | +-------------+----------------+-----------------+-----------------+ Similar way, you can try SQL UPDATE and DELETE statements on the same table. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2368, "s": 2239, "text": "The <sql:update> tag executes an SQL statement that does not return data; for example, SQL INSERT, UPDATE, or DELETE statements." }, { "code": null, "e": 2420, "s": 2368, "text": "The <sql:update> tag has the following attributes −" }, { "code": null, "e": 2565, "s": 2420, "text": "To start with basic concept, let us create a simple table Employees table in the TEST database and create few records in that table as follows −" }, { "code": null, "e": 2641, "s": 2565, "text": "Open a Command Prompt and change to the installation directory as follows −" }, { "code": null, "e": 2706, "s": 2641, "text": "C:\\>\nC:\\>cd Program Files\\MySQL\\bin\nC:\\Program Files\\MySQL\\bin>\n" }, { "code": null, "e": 2741, "s": 2706, "text": "Login to the database as follows −" }, { "code": null, "e": 2818, "s": 2741, "text": "C:\\Program Files\\MySQL\\bin>mysql -u root -p\nEnter password: ********\nmysql>\n" }, { "code": null, "e": 2878, "s": 2818, "text": "Create the table Employee in the TEST database as follows −" }, { "code": null, "e": 3080, "s": 2878, "text": "mysql> use TEST;\nmysql> create table Employees\n (\n id int not null,\n age int not null,\n first varchar (255),\n last varchar (255)\n );\nQuery OK, 0 rows affected (0.08 sec)\nmysql>\n" }, { "code": null, "e": 3146, "s": 3080, "text": "We will now create few records in the Employee table as follows −" }, { "code": null, "e": 3563, "s": 3146, "text": "mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');\nQuery OK, 1 row affected (0.05 sec)\n \nmysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');\nQuery OK, 1 row affected (0.00 sec)\n \nmysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');\nQuery OK, 1 row affected (0.00 sec)\n \nmysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');\nQuery OK, 1 row affected (0.00 sec)\n \nmysql>\n" }, { "code": null, "e": 3712, "s": 3563, "text": "Let us now write a JSP which will make use of the <sql:update> tag to execute an SQL INSERT statement to create one record in the table as follows −" }, { "code": null, "e": 5041, "s": 3712, "text": "<%@ page import = \"java.io.*,java.util.*,java.sql.*\"%>\n<%@ page import = \"javax.servlet.http.*,javax.servlet.*\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\"%>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/sql\" prefix = \"sql\"%>\n\n<html>\n <head>\n <title>JSTL sql:update Tag</title>\n </head>\n\n <body>\n <sql:setDataSource var = \"snapshot\" driver = \"com.mysql.jdbc.Driver\"\n url = \"jdbc:mysql://localhost/TEST\"\n user = \"root\" password = \"pass123\"/>\n\n <sql:update dataSource = \"${snapshot}\" var = \"count\">\n INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali');\n </sql:update>\n\n <sql:query dataSource = \"${snapshot}\" var = \"result\">\n SELECT * from Employees;\n </sql:query>\n \n <table border = \"1\" width = \"100%\">\n <tr>\n <th>Emp ID</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>Age</th>\n </tr>\n \n <c:forEach var = \"row\" items = \"${result.rows}\">\n <tr>\n <td> <c:out value = \"${row.id}\"/></td>\n <td> <c:out value = \"${row.first}\"/></td>\n <td> <c:out value = \"${row.last}\"/></td>\n <td> <c:out value = \"${row.age}\"/></td>\n </tr>\n </c:forEach>\n </table>\n\n </body>\n</html>" }, { "code": null, "e": 5104, "s": 5041, "text": "Access the above JSP, the following result will be displayed −" }, { "code": null, "e": 5726, "s": 5104, "text": "+-------------+----------------+-----------------+-----------------+\n| Emp ID | First Name | Last Name | Age |\n+-------------+----------------+-----------------+-----------------+\n| 100 | Zara | Ali | 18 |\n| 101 | Mahnaz | Fatma | 25 |\n| 102 | Zaid | Khan | 30 |\n| 103 | Sumit | Mittal | 28 |\n| 104 | Nula | Ali | 2 |\n+-------------+----------------+-----------------+-----------------+\n" }, { "code": null, "e": 5803, "s": 5726, "text": "Similar way, you can try SQL UPDATE and DELETE statements on the same table." }, { "code": null, "e": 5838, "s": 5803, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 5853, "s": 5838, "text": " Chaand Sheikh" }, { "code": null, "e": 5888, "s": 5853, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 5903, "s": 5888, "text": " Chaand Sheikh" }, { "code": null, "e": 5938, "s": 5903, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5952, "s": 5938, "text": " Karthikeya T" }, { "code": null, "e": 5987, "s": 5952, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6003, "s": 5987, "text": " TELCOMA Global" }, { "code": null, "e": 6036, "s": 6003, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 6052, "s": 6036, "text": " TELCOMA Global" }, { "code": null, "e": 6086, "s": 6052, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 6094, "s": 6086, "text": " Uplatz" }, { "code": null, "e": 6101, "s": 6094, "text": " Print" }, { "code": null, "e": 6112, "s": 6101, "text": " Add Notes" } ]
Training Self Driving Cars using Reinforcement Learning | by Jerry Qu | Towards Data Science
By 2040, 95% of new vehicles sold will be fully autonomous. Wow. 😮 Two reasons why this is revolutionary: It will save 1.25 MILLION lives every year from traffic accidents It will give you the equivalence of 3 extra years in a lifetime, currently spent in transit Self driving cars will become a multi-trillion dollar industry because of this impact. What could you do with 3 extra years? This is the question driving innovation from tech-leaders like Elon Musk and Google. But before we can get there, we need to understand the technology making this all possible, Reinforcement Learning. Imagine a robot (Also known as an agent) is trying to pick up a pen, and it fails. It tries again, fails. After repeating this process 1000 times, it finally succeeds. The agent has now learned how to pick up a pen. This is Reinforcement Learning in a nutshell, it’s a lot like how living creatures learn. There are 3 key terms in Reinforcement Learning State: Describes the current situation. (eg. Position in a maze) Action: What the agent can do in its situation (eg. Move right) Reward: Feedback for whether a particular action in a given state was good or bad In this image, there is a robot at position (1, 1), in a maze. That position is the state. The robot has a set of actions that it can perform, move up or move right. The last thing to note is that, the robot will receive a reward whenever it takes an action. The rewards are defined by the programmer, and we’ll define the rewards as such. Enter open square: +1 Bump into wall square: -1 Enter exit square: +100 Every time the robot takes an action (a), in state (s), it receives a reward (r). In its head, it constantly updates its memory of rewards for taking certain actions in those states. This is called the policy. The policy is essentially how the agent makes decisions. All decisions are based around predicted rewards. Let’s pretend the robot has a huge table in its head. The table stores all of the states, with all possible actions, and predicted rewards for that state-action pair. At the beginning of training, all predicted rewards are set to 0. +------------------+--------------------------+| State | 1, 1 |+------------------+--------------------------+| Action | Up | Down | Left | Right |+------------------+----+------+------+-------+| Predicted Reward | 0 | 0 | 0 | 0 |+------------------+----+------+------+-------+ The robot starts by taking random actions, since it has no experience yet. However, after taking random actions over many iterations, it slowly learns to accurately predict rewards for each action. It does this by adjusting its predicted reward for specific state-action pairs towards the received reward every time. These predicted rewards, are formally known as Q-Values. Q-Values essentially define how ‘good’ a certain state is and how much the agent wants to move into that state. +----------------------------+--------------------------+| State | 1, 1 |+----------------------------+--------------------------+| Action | Up | Down | Left | Right |+----------------------------+----+------+------+-------+| Q-Value (Predicted Reward) | 1 | -1 | -1 | 1 |+----------------------------+----+------+------+-------+ Now, the robot can simply look for the highest Q-Value, and take that action. It has learned! We have two problems with our model right now. One big, and one small. We’ll start with the small one. Let’s imagine the agent has just started learning so all q-values are zero. The agent is trying to get to the end, meaning it is aiming to choose actions with the highest q-values. Since all start at 0, each has a 25% chance of being picked. Say the agent ends up choosing to move right. The policy now looks like this: +---------+--------------------------+| State | 1, 1 |+---------+--------------------------+| Action | Up | Down | Left | Right |+---------+----+------+------+-------+| Q-Value | 0 | 0 | 0 | 1 |+---------+----+------+------+-------+ But there’s a problem. The next time the agent resets to state (1, 1), it will always pick the action, right. The agent never had a chance to explore the other actions. This is called a Greedy Policy, where the agent always picks the highest q-value. The agent is “Exploiting” it’s prior knowledge, hence exploitation. The other potential policy is to choose an action randomly, hence exploration. In practice, many factors affect our policy (How we choose which action to take). Is your agent running in a simulation where it can make mistakes without repercussions? Or is the agent running in real time? The former would benefit from a higher exploration, to learn faster, while the latter would benefit from a higher exploitation, as to reduce loss. A combination of both exploitation and exploration is normally used, depending on the problem. (Ex. Exploit 70% of the time, and explore 30% of the time) A bigger problem with our agent right now, is that we can only look one step ahead. For example, at state (1, 1) the agent has learned that both actions will result in a +1 reward. We can look at the maze, and see that moving up would not be an ideal action, since it would lead to a dead end. We need a way to correlate future rewards with the current reward. The equation above is known as the Future Cumulative Discounted Reward. It is part of the Bellman Equation and it allows us to account for future rewards past state t+1. In this equation: These are what the variables represent: (t): The current state (R t): The cumulative discounted reward at state t (To update our q-value) (r): The reward (γ): The discount rate (Between 0 and 1) (k): The number of steps into the future that the reward was received For all of you out there who don’t love a bunch of math equations. ✋ This equation essentially takes the sum of the current reward, plus all future rewards, discounted by a number γ that is exponentially decreased by a factor of k (The number of steps into the future the reward was received). Using this allows us to update our q-values based on not only the next action, but all the actions following. Applying this with a γ = 0.9, we get: At the final state, there’s only the current reward (100). But for the state before that we take a discount of the next reward plus the current reward (100 * 0.9 + 1 = 91). Then for the state before that we take a larger discount of the final reward plus a discount of the next reward in addition to the current reward (100 * 0.9 * 0.9 + 1 * 0.9 + 1 = 82.9). And so on and so forth. Rewards farther into the future, logically should be discounted greater since the current action has less of a role in generating that reward. Our agent is now fully equipped to learn! It will explore the maze thousands of times. Each time slightly adjusting its q-values towards R t (The cumulative discounted reward). Only by small amounts because large changes will make the learn too chaotic. After thousands of iterations, the agent will have learned approximate q-values, which it can then utilize with the greedy policy to take the action with the highest q-value, and make it to the end of the maze! Oh no, not again... This is the last one, I promise. 😃 Imagine trying to use this form of Reinforcement Learning in a real world scenario. A self driving car for example. The problem we face is that our world is WAY too complex to store q-values for every single state. Imagine storing a value for every single coordinate point on Earth. Now add in other factors like weather conditions, the direction the agent is facing, and an ever changing Earth, and the problem becomes IMPOSSIBLE! “Persistence is very important. You should not give up unless you are forced to give up.” — Elon Musk The solution we’ve been using before can be compared to a brute force method where our agent stores q-values for every single state. But what if we used Machine Learning (Neural Networks), to predict q-values for each action, given your state as input. This would completely change the game. In many real world problems, there are patterns in our states that correspond to q-values. For example, if a self driving car senses a car stopped in front of it, the self driving car must stop! This applies no matter where the self driving car is, what the weather is, or any other factor. The car would crash if it were to continue driving, leading to a VERY negative reward (As defined by the Machine Learning Engineers). So, instead of creating a table of every single possible condition (weather, location, etc), a neural network could simply learn that if a car is stopped in front of the agent, take the action named ‘slow down’. Neural Networks are amazing at one thing, Learning PATTERNS! Deep Q-Learning uses Neural Networks to learn the patterns between state and q-value, using the reward as the expected output. These are called Deep Q-Networks. In a traditional Neural Network, we’d be required to label all of our inputs. That is how neural networks learn. (Check out my last article on Neural Networks if you need a refresher.) However, in the scenario of self driving cars, how are we supposed to define our expected values at every time interval? We’d need to say, turn the wheel 0.5 degrees to the left, increase speed to 50kph. And in a fraction of a second, we’d need new labels for our new input! This would take years to label! In Deep Q-Networks, instead of defining every single value (Steering wheel angle, speed), we correlate actions to q-values. For example, turn steering wheel 5 degrees to the left is a potential action. So is 4 degrees to the right, and change to 50kph, and change to 30kph. We then define rewards. This is completely up to the engineer, and there is definitely a bit of play here as we try out different values. Crashing is obviously bad, and must be avoided. So, maybe we give it a reward of -1000000. On the other hand, we’ll give the agent a reward of 1 for each second it doesn’t crash, and a reward of 10 for getting closer to its destination. In this method, there is feedback (reward), intrinsic to our environment. We are now simply mapping that feedback, to the actions that caused that feedback. That is the beauty of Reinforcement Learning. We no longer have to label our data! We aren’t completely done with Reinforcement Learning at this point. There are many advancements being made as we speak! Machine Learning is a new and fluid field. Some of the largest advancements made include: Experience Replay Distributional Reinforcement Learning Separate Target Network (Double Deep Q-Learning) I’ll quickly skip over these, as they aren’t essential to the understanding of reinforcement learning in general. Experience replay takes the approach of not training our neural network in real time. Instead, it performs many actions, receives a batch of action-state-reward trios, and randomly samples those trios to train the neural network. This allows for a more generalized model as the order of data is randomized. Distributional Reinforcement Learning is a more recent development where instead of optimizing our neural network to a single q-value for each action, we train it on a distribution of the probabilities of q-value ranges for each action. For example, the outputs of our neural network would become: Probability of Q-Value of action a being 1–5 Probability of Q-Value of action a being 6–10 Probability of Q-Value of action b being 1–5 Probability of Q-Value of action b being 6–10 This solves problems that arise when q-values have multiple peaks. These multiple peaks would normally be averaged together after numerous iterations, but this new method allows the agent to consider each peak individually. In practice, researchers demonstrated that this model doubled the speed of training for agents playing Atari games! Yeah. I had to do something with my new found knowledge. Stay tuned to find out how I applied Reinforcement Learning to a virtual self driving car in my next article! (It’s now been published) Reinforcement Learning, abstracts the need to label data. However, as a result we lose a bit of accuracy. Imagine the difference between being told how to drive a car, versus driving, crashing, and learning on your own. “It turns out that reinforcement learning is a type of machine learning whose hunger for data is even greater than supervised learning. It is really difficult to get enough data for reinforcement learning algorithms.” — Andrew Ng Nonetheless, Reinforcement Learning is a stepping stone to a new world. Its drawn us one step closer to General AI, by taking feedback directly from the environment. (Learn more about how I think we could create a General AI). We’ve already proven the value of reinforcement learning in areas such as Machine Trading, and Self Driving Cars. But this is still a new field, constantly being improved and disrupted upon. So stick around. Reinforcement Learning and Machine Learning in general are here to stay! If you want to take anything away from this article: Reinforcement Learning abstracts the need to label data in Neural Networks Deep Q-Learning is a method of Reinforcement Learning Machine Learning is a dynamic field, constantly being improved and disrupted If you enjoyed this article: follow my Medium, LinkedIn, and Twitter to stay updated with my progress! shoot me an email ([email protected]) I’ll reply 😉
[ { "code": null, "e": 232, "s": 172, "text": "By 2040, 95% of new vehicles sold will be fully autonomous." }, { "code": null, "e": 239, "s": 232, "text": "Wow. 😮" }, { "code": null, "e": 278, "s": 239, "text": "Two reasons why this is revolutionary:" }, { "code": null, "e": 344, "s": 278, "text": "It will save 1.25 MILLION lives every year from traffic accidents" }, { "code": null, "e": 436, "s": 344, "text": "It will give you the equivalence of 3 extra years in a lifetime, currently spent in transit" }, { "code": null, "e": 762, "s": 436, "text": "Self driving cars will become a multi-trillion dollar industry because of this impact. What could you do with 3 extra years? This is the question driving innovation from tech-leaders like Elon Musk and Google. But before we can get there, we need to understand the technology making this all possible, Reinforcement Learning." }, { "code": null, "e": 1068, "s": 762, "text": "Imagine a robot (Also known as an agent) is trying to pick up a pen, and it fails. It tries again, fails. After repeating this process 1000 times, it finally succeeds. The agent has now learned how to pick up a pen. This is Reinforcement Learning in a nutshell, it’s a lot like how living creatures learn." }, { "code": null, "e": 1116, "s": 1068, "text": "There are 3 key terms in Reinforcement Learning" }, { "code": null, "e": 1181, "s": 1116, "text": "State: Describes the current situation. (eg. Position in a maze)" }, { "code": null, "e": 1245, "s": 1181, "text": "Action: What the agent can do in its situation (eg. Move right)" }, { "code": null, "e": 1327, "s": 1245, "text": "Reward: Feedback for whether a particular action in a given state was good or bad" }, { "code": null, "e": 1667, "s": 1327, "text": "In this image, there is a robot at position (1, 1), in a maze. That position is the state. The robot has a set of actions that it can perform, move up or move right. The last thing to note is that, the robot will receive a reward whenever it takes an action. The rewards are defined by the programmer, and we’ll define the rewards as such." }, { "code": null, "e": 1689, "s": 1667, "text": "Enter open square: +1" }, { "code": null, "e": 1715, "s": 1689, "text": "Bump into wall square: -1" }, { "code": null, "e": 1739, "s": 1715, "text": "Enter exit square: +100" }, { "code": null, "e": 2289, "s": 1739, "text": "Every time the robot takes an action (a), in state (s), it receives a reward (r). In its head, it constantly updates its memory of rewards for taking certain actions in those states. This is called the policy. The policy is essentially how the agent makes decisions. All decisions are based around predicted rewards. Let’s pretend the robot has a huge table in its head. The table stores all of the states, with all possible actions, and predicted rewards for that state-action pair. At the beginning of training, all predicted rewards are set to 0." }, { "code": null, "e": 2619, "s": 2289, "text": "+------------------+--------------------------+| State | 1, 1 |+------------------+--------------------------+| Action | Up | Down | Left | Right |+------------------+----+------+------+-------+| Predicted Reward | 0 | 0 | 0 | 0 |+------------------+----+------+------+-------+" }, { "code": null, "e": 3105, "s": 2619, "text": "The robot starts by taking random actions, since it has no experience yet. However, after taking random actions over many iterations, it slowly learns to accurately predict rewards for each action. It does this by adjusting its predicted reward for specific state-action pairs towards the received reward every time. These predicted rewards, are formally known as Q-Values. Q-Values essentially define how ‘good’ a certain state is and how much the agent wants to move into that state." }, { "code": null, "e": 3505, "s": 3105, "text": "+----------------------------+--------------------------+| State | 1, 1 |+----------------------------+--------------------------+| Action | Up | Down | Left | Right |+----------------------------+----+------+------+-------+| Q-Value (Predicted Reward) | 1 | -1 | -1 | 1 |+----------------------------+----+------+------+-------+" }, { "code": null, "e": 3599, "s": 3505, "text": "Now, the robot can simply look for the highest Q-Value, and take that action. It has learned!" }, { "code": null, "e": 3702, "s": 3599, "text": "We have two problems with our model right now. One big, and one small. We’ll start with the small one." }, { "code": null, "e": 4022, "s": 3702, "text": "Let’s imagine the agent has just started learning so all q-values are zero. The agent is trying to get to the end, meaning it is aiming to choose actions with the highest q-values. Since all start at 0, each has a 25% chance of being picked. Say the agent ends up choosing to move right. The policy now looks like this:" }, { "code": null, "e": 4289, "s": 4022, "text": "+---------+--------------------------+| State | 1, 1 |+---------+--------------------------+| Action | Up | Down | Left | Right |+---------+----+------+------+-------+| Q-Value | 0 | 0 | 0 | 1 |+---------+----+------+------+-------+" }, { "code": null, "e": 4769, "s": 4289, "text": "But there’s a problem. The next time the agent resets to state (1, 1), it will always pick the action, right. The agent never had a chance to explore the other actions. This is called a Greedy Policy, where the agent always picks the highest q-value. The agent is “Exploiting” it’s prior knowledge, hence exploitation. The other potential policy is to choose an action randomly, hence exploration. In practice, many factors affect our policy (How we choose which action to take)." }, { "code": null, "e": 4895, "s": 4769, "text": "Is your agent running in a simulation where it can make mistakes without repercussions? Or is the agent running in real time?" }, { "code": null, "e": 5196, "s": 4895, "text": "The former would benefit from a higher exploration, to learn faster, while the latter would benefit from a higher exploitation, as to reduce loss. A combination of both exploitation and exploration is normally used, depending on the problem. (Ex. Exploit 70% of the time, and explore 30% of the time)" }, { "code": null, "e": 5557, "s": 5196, "text": "A bigger problem with our agent right now, is that we can only look one step ahead. For example, at state (1, 1) the agent has learned that both actions will result in a +1 reward. We can look at the maze, and see that moving up would not be an ideal action, since it would lead to a dead end. We need a way to correlate future rewards with the current reward." }, { "code": null, "e": 5745, "s": 5557, "text": "The equation above is known as the Future Cumulative Discounted Reward. It is part of the Bellman Equation and it allows us to account for future rewards past state t+1. In this equation:" }, { "code": null, "e": 5785, "s": 5745, "text": "These are what the variables represent:" }, { "code": null, "e": 5808, "s": 5785, "text": "(t): The current state" }, { "code": null, "e": 5883, "s": 5808, "text": "(R t): The cumulative discounted reward at state t (To update our q-value)" }, { "code": null, "e": 5899, "s": 5883, "text": "(r): The reward" }, { "code": null, "e": 5940, "s": 5899, "text": "(γ): The discount rate (Between 0 and 1)" }, { "code": null, "e": 6010, "s": 5940, "text": "(k): The number of steps into the future that the reward was received" }, { "code": null, "e": 6414, "s": 6010, "text": "For all of you out there who don’t love a bunch of math equations. ✋ This equation essentially takes the sum of the current reward, plus all future rewards, discounted by a number γ that is exponentially decreased by a factor of k (The number of steps into the future the reward was received). Using this allows us to update our q-values based on not only the next action, but all the actions following." }, { "code": null, "e": 6452, "s": 6414, "text": "Applying this with a γ = 0.9, we get:" }, { "code": null, "e": 6978, "s": 6452, "text": "At the final state, there’s only the current reward (100). But for the state before that we take a discount of the next reward plus the current reward (100 * 0.9 + 1 = 91). Then for the state before that we take a larger discount of the final reward plus a discount of the next reward in addition to the current reward (100 * 0.9 * 0.9 + 1 * 0.9 + 1 = 82.9). And so on and so forth. Rewards farther into the future, logically should be discounted greater since the current action has less of a role in generating that reward." }, { "code": null, "e": 7443, "s": 6978, "text": "Our agent is now fully equipped to learn! It will explore the maze thousands of times. Each time slightly adjusting its q-values towards R t (The cumulative discounted reward). Only by small amounts because large changes will make the learn too chaotic. After thousands of iterations, the agent will have learned approximate q-values, which it can then utilize with the greedy policy to take the action with the highest q-value, and make it to the end of the maze!" }, { "code": null, "e": 7463, "s": 7443, "text": "Oh no, not again..." }, { "code": null, "e": 7498, "s": 7463, "text": "This is the last one, I promise. 😃" }, { "code": null, "e": 7930, "s": 7498, "text": "Imagine trying to use this form of Reinforcement Learning in a real world scenario. A self driving car for example. The problem we face is that our world is WAY too complex to store q-values for every single state. Imagine storing a value for every single coordinate point on Earth. Now add in other factors like weather conditions, the direction the agent is facing, and an ever changing Earth, and the problem becomes IMPOSSIBLE!" }, { "code": null, "e": 8032, "s": 7930, "text": "“Persistence is very important. You should not give up unless you are forced to give up.” — Elon Musk" }, { "code": null, "e": 8324, "s": 8032, "text": "The solution we’ve been using before can be compared to a brute force method where our agent stores q-values for every single state. But what if we used Machine Learning (Neural Networks), to predict q-values for each action, given your state as input. This would completely change the game." }, { "code": null, "e": 8961, "s": 8324, "text": "In many real world problems, there are patterns in our states that correspond to q-values. For example, if a self driving car senses a car stopped in front of it, the self driving car must stop! This applies no matter where the self driving car is, what the weather is, or any other factor. The car would crash if it were to continue driving, leading to a VERY negative reward (As defined by the Machine Learning Engineers). So, instead of creating a table of every single possible condition (weather, location, etc), a neural network could simply learn that if a car is stopped in front of the agent, take the action named ‘slow down’." }, { "code": null, "e": 9022, "s": 8961, "text": "Neural Networks are amazing at one thing, Learning PATTERNS!" }, { "code": null, "e": 9183, "s": 9022, "text": "Deep Q-Learning uses Neural Networks to learn the patterns between state and q-value, using the reward as the expected output. These are called Deep Q-Networks." }, { "code": null, "e": 9675, "s": 9183, "text": "In a traditional Neural Network, we’d be required to label all of our inputs. That is how neural networks learn. (Check out my last article on Neural Networks if you need a refresher.) However, in the scenario of self driving cars, how are we supposed to define our expected values at every time interval? We’d need to say, turn the wheel 0.5 degrees to the left, increase speed to 50kph. And in a fraction of a second, we’d need new labels for our new input! This would take years to label!" }, { "code": null, "e": 10564, "s": 9675, "text": "In Deep Q-Networks, instead of defining every single value (Steering wheel angle, speed), we correlate actions to q-values. For example, turn steering wheel 5 degrees to the left is a potential action. So is 4 degrees to the right, and change to 50kph, and change to 30kph. We then define rewards. This is completely up to the engineer, and there is definitely a bit of play here as we try out different values. Crashing is obviously bad, and must be avoided. So, maybe we give it a reward of -1000000. On the other hand, we’ll give the agent a reward of 1 for each second it doesn’t crash, and a reward of 10 for getting closer to its destination. In this method, there is feedback (reward), intrinsic to our environment. We are now simply mapping that feedback, to the actions that caused that feedback. That is the beauty of Reinforcement Learning. We no longer have to label our data!" }, { "code": null, "e": 10775, "s": 10564, "text": "We aren’t completely done with Reinforcement Learning at this point. There are many advancements being made as we speak! Machine Learning is a new and fluid field. Some of the largest advancements made include:" }, { "code": null, "e": 10793, "s": 10775, "text": "Experience Replay" }, { "code": null, "e": 10831, "s": 10793, "text": "Distributional Reinforcement Learning" }, { "code": null, "e": 10880, "s": 10831, "text": "Separate Target Network (Double Deep Q-Learning)" }, { "code": null, "e": 11301, "s": 10880, "text": "I’ll quickly skip over these, as they aren’t essential to the understanding of reinforcement learning in general. Experience replay takes the approach of not training our neural network in real time. Instead, it performs many actions, receives a batch of action-state-reward trios, and randomly samples those trios to train the neural network. This allows for a more generalized model as the order of data is randomized." }, { "code": null, "e": 11599, "s": 11301, "text": "Distributional Reinforcement Learning is a more recent development where instead of optimizing our neural network to a single q-value for each action, we train it on a distribution of the probabilities of q-value ranges for each action. For example, the outputs of our neural network would become:" }, { "code": null, "e": 11644, "s": 11599, "text": "Probability of Q-Value of action a being 1–5" }, { "code": null, "e": 11690, "s": 11644, "text": "Probability of Q-Value of action a being 6–10" }, { "code": null, "e": 11735, "s": 11690, "text": "Probability of Q-Value of action b being 1–5" }, { "code": null, "e": 11781, "s": 11735, "text": "Probability of Q-Value of action b being 6–10" }, { "code": null, "e": 12121, "s": 11781, "text": "This solves problems that arise when q-values have multiple peaks. These multiple peaks would normally be averaged together after numerous iterations, but this new method allows the agent to consider each peak individually. In practice, researchers demonstrated that this model doubled the speed of training for agents playing Atari games!" }, { "code": null, "e": 12314, "s": 12121, "text": "Yeah. I had to do something with my new found knowledge. Stay tuned to find out how I applied Reinforcement Learning to a virtual self driving car in my next article! (It’s now been published)" }, { "code": null, "e": 12534, "s": 12314, "text": "Reinforcement Learning, abstracts the need to label data. However, as a result we lose a bit of accuracy. Imagine the difference between being told how to drive a car, versus driving, crashing, and learning on your own." }, { "code": null, "e": 12764, "s": 12534, "text": "“It turns out that reinforcement learning is a type of machine learning whose hunger for data is even greater than supervised learning. It is really difficult to get enough data for reinforcement learning algorithms.” — Andrew Ng" }, { "code": null, "e": 13272, "s": 12764, "text": "Nonetheless, Reinforcement Learning is a stepping stone to a new world. Its drawn us one step closer to General AI, by taking feedback directly from the environment. (Learn more about how I think we could create a General AI). We’ve already proven the value of reinforcement learning in areas such as Machine Trading, and Self Driving Cars. But this is still a new field, constantly being improved and disrupted upon. So stick around. Reinforcement Learning and Machine Learning in general are here to stay!" }, { "code": null, "e": 13325, "s": 13272, "text": "If you want to take anything away from this article:" }, { "code": null, "e": 13400, "s": 13325, "text": "Reinforcement Learning abstracts the need to label data in Neural Networks" }, { "code": null, "e": 13454, "s": 13400, "text": "Deep Q-Learning is a method of Reinforcement Learning" }, { "code": null, "e": 13531, "s": 13454, "text": "Machine Learning is a dynamic field, constantly being improved and disrupted" }, { "code": null, "e": 13560, "s": 13531, "text": "If you enjoyed this article:" }, { "code": null, "e": 13634, "s": 13560, "text": "follow my Medium, LinkedIn, and Twitter to stay updated with my progress!" } ]
Chef - Testing Cookbook with Test Kitchen
Test kitchen is Chef’s integration testing framework. It enables writing tests, which run after VM is instantiated and converged using the cookbook. The tests run on VM and can verify that everything works as expected. This is node contract to ChefSpec, which only simulates a Chef run. Test Kitchen boots up a real node and runs Chef on it. In order to do this, we need to have Vagrant installed on the machine which helps in managing a virtual machine. Then we need to have bookshelf installed and hooked with Vagrant in order to manage cookbook dependencies. Step 1 − Edit default recipe in the cookbook. vipin@laptop:~/chef-repo $ subl cookbooks/<Cookbook Name>/recipes/default.rb file "/tmp/greeting.txt" do content node['my_cookbook']['greeting'] end Step 2 − Edit cookbook attributes. vipin@laptop:~/chef-repo $ subl cookbooks/<Cookbook Name>/attributes/default.rb default['my_cookbook']['greeting'] = "Ohai, Chefs!" Step 3 − Edit gem file to install the necessary Ruby gems. vipin@laptop:~/chef-repo $ subl Gemfile gem 'test-kitchen', '~> 2.0.0.alpha.7' gem 'kitchen-vagrant' Step 4 − Install the necessary Ruby gem. vipin@laptop:~/chef-repo $ bundle install ...TRUNCATED OUTPUT... Installing test-kitchen (1.0.0.alpha.7) Installing kitchen-vagrant (0.10.0) ...TRUNCATED OUTPUT... Step 5 − Create .kitchen.yml file in the cookbook. vipin@laptop:~/chef-repo/cookbooks/my_cookbook $ subl .kitchen.yml --- driver_plugin: vagrant driver_config: require_chef_omnibus: true platforms: - name: ubuntu-12.04 driver_config: box: opscode-ubuntu-12.04 box_url: https://opscode-vm.s3.amazonaws.com/vagrant/ opscode_ubuntu12.04_provisionerless.box suites: - name: default run_list: - recipe[minitest-handler] - recipe[my_cookbook_test] attributes: { my_cookbook: { greeting: 'Ohai, Minitest!'} } Step 6 − Create a test directory inside the cookbook. vipin@laptop:~/chef-repo/cookbooks/<Cookbook Name>$ mkdir test Step 7 − Create a test cookbook for integration testing. vipin@laptop:~/chef-repo/cookbooks/<Cookbook Name>/test $ knife cookbook create my_cookbook_test ** Creating cookbook my_cookbook_test ** Creating README for cookbook: my_cookbook_test ** Creating CHANGELOG for cookbook: my_cookbook_test ** Creating metadata for cookbook: my_cookbook_test Step 8 − Edit test cookbooks default recipe. vipin@laptop:~/chef-repo/cookbooks/my_cookbook $ subl test/cookbooks/my_cookbook_test/recipes/default.rb include_recipe 'my_cookbook::default' Step 9 − Create Minitest Spec inside the cookbook. vipin@laptop:~/chef-repo/cookbooks/my_cookbook $ mkdir -p test/cookbooks/my_cookbook_test/files/default/tests/minitest vipin@laptop:~/chef-repo/cookbooks/my_cookbook $ subl test/cookbooks/my_cookbook_test/files/default/tests/minitest/default_test.rb require 'minitest/spec' describe_recipe 'my_cookbook::default' do describe "greeting file" do it "creates the greeting file" do file("/tmp/greeting.txt").must_exist end it "contains what's stored in the 'greeting' node attribute" do file('/tmp/greeting.txt').must_include 'Ohai, Minitest!' end end Step 10 − Edit your main cookbook's Berksfile. vipin@laptop:~/chef-repo/cookbooks/my_cookbook $ subl Berksfile site :opscode metadata cookbook "apt" cookbook "minitest-handler" cookbook "my_cookbook_test", path: "./test/cookbooks/my_cookbook_test" vipin@laptop:~/chef-repo/cookbooks/my_cookbook $ kitchen test -----> Starting Kitchen (v1.0.0.alpha.7) ...TRUNCATED OUTPUT... -----> Converging <default-ubuntu-1204> -----> Installing Chef Omnibus (true) ...TRUNCATED OUTPUT... Starting Chef Client, version 11.4.4 [2013-06-29T18:33:57+00:00] INFO: *** Chef 11.4.4 *** [2013-06-29T18:33:58+00:00] INFO: Setting the run_list to ["recipe[minitest-handler]", "recipe[my_cookbook_test]"] from JSON ...TRUNCATED OUTPUT... # Running tests: recipe::my_cookbook::default::greeting file#test_0001_creates the greeting file = 0.00 s = . recipe::my_cookbook::default::greeting file#test_0002_contains what's stored in the 'greeting' node attribute = 0.00 s = . Finished tests in 0.011190s, 178.7277 tests/s, 178.7277 assertions/s. 2 tests, 2 assertions, 0 failures, 0 errors, 0 skips ...TRUNCATED OUTPUT... -----> Kitchen is finished. (2m5.69s) Print Add Notes Bookmark this page
[ { "code": null, "e": 2599, "s": 2380, "text": "Test kitchen is Chef’s integration testing framework. It enables writing tests, which run after VM is instantiated and converged using the cookbook. The tests run on VM and can verify that everything works as expected." }, { "code": null, "e": 2722, "s": 2599, "text": "This is node contract to ChefSpec, which only simulates a Chef run. Test Kitchen boots up a real node and runs Chef on it." }, { "code": null, "e": 2942, "s": 2722, "text": "In order to do this, we need to have Vagrant installed on the machine which helps in managing a virtual machine. Then we need to have bookshelf installed and hooked with Vagrant in order to manage cookbook dependencies." }, { "code": null, "e": 2988, "s": 2942, "text": "Step 1 − Edit default recipe in the cookbook." }, { "code": null, "e": 3143, "s": 2988, "text": "vipin@laptop:~/chef-repo $ subl cookbooks/<Cookbook Name>/recipes/default.rb \nfile \"/tmp/greeting.txt\" do \n content node['my_cookbook']['greeting'] \nend" }, { "code": null, "e": 3178, "s": 3143, "text": "Step 2 − Edit cookbook attributes." }, { "code": null, "e": 3311, "s": 3178, "text": "vipin@laptop:~/chef-repo $ subl cookbooks/<Cookbook Name>/attributes/default.rb \ndefault['my_cookbook']['greeting'] = \"Ohai, Chefs!\"" }, { "code": null, "e": 3370, "s": 3311, "text": "Step 3 − Edit gem file to install the necessary Ruby gems." }, { "code": null, "e": 3475, "s": 3370, "text": "vipin@laptop:~/chef-repo $ subl Gemfile \ngem 'test-kitchen', '~> 2.0.0.alpha.7' \ngem 'kitchen-vagrant' \n" }, { "code": null, "e": 3516, "s": 3475, "text": "Step 4 − Install the necessary Ruby gem." }, { "code": null, "e": 3685, "s": 3516, "text": "vipin@laptop:~/chef-repo $ bundle install \n...TRUNCATED OUTPUT... \nInstalling test-kitchen (1.0.0.alpha.7) \nInstalling kitchen-vagrant (0.10.0) ...TRUNCATED OUTPUT... \n" }, { "code": null, "e": 3736, "s": 3685, "text": "Step 5 − Create .kitchen.yml file in the cookbook." }, { "code": null, "e": 4265, "s": 3736, "text": "vipin@laptop:~/chef-repo/cookbooks/my_cookbook $ subl .kitchen.yml \n--- \ndriver_plugin: vagrant \ndriver_config: \n require_chef_omnibus: true \nplatforms: \n - name: ubuntu-12.04 \n driver_config: \n box: opscode-ubuntu-12.04 \n box_url: \n https://opscode-vm.s3.amazonaws.com/vagrant/\n opscode_ubuntu12.04_provisionerless.box \nsuites: \n - name: default \n run_list: \n - recipe[minitest-handler] \n - recipe[my_cookbook_test] \nattributes: { my_cookbook: { greeting: 'Ohai, Minitest!'} } " }, { "code": null, "e": 4319, "s": 4265, "text": "Step 6 − Create a test directory inside the cookbook." }, { "code": null, "e": 4384, "s": 4319, "text": "vipin@laptop:~/chef-repo/cookbooks/<Cookbook Name>$ mkdir test \n" }, { "code": null, "e": 4441, "s": 4384, "text": "Step 7 − Create a test cookbook for integration testing." }, { "code": null, "e": 4738, "s": 4441, "text": "vipin@laptop:~/chef-repo/cookbooks/<Cookbook Name>/test $ knife \ncookbook create my_cookbook_test \n** Creating cookbook my_cookbook_test \n** Creating README for cookbook: my_cookbook_test \n** Creating CHANGELOG for cookbook: my_cookbook_test \n** Creating metadata for cookbook: my_cookbook_test \n" }, { "code": null, "e": 4783, "s": 4738, "text": "Step 8 − Edit test cookbooks default recipe." }, { "code": null, "e": 4929, "s": 4783, "text": "vipin@laptop:~/chef-repo/cookbooks/my_cookbook $ subl \ntest/cookbooks/my_cookbook_test/recipes/default.rb \ninclude_recipe 'my_cookbook::default'\n" }, { "code": null, "e": 4980, "s": 4929, "text": "Step 9 − Create Minitest Spec inside the cookbook." }, { "code": null, "e": 5615, "s": 4980, "text": "vipin@laptop:~/chef-repo/cookbooks/my_cookbook $ mkdir -p \n test/cookbooks/my_cookbook_test/files/default/tests/minitest \n\nvipin@laptop:~/chef-repo/cookbooks/my_cookbook $ subl \n test/cookbooks/my_cookbook_test/files/default/tests/minitest/default_test.rb \n\nrequire 'minitest/spec' \ndescribe_recipe 'my_cookbook::default' do \n describe \"greeting file\" do \n it \"creates the greeting file\" do \n file(\"/tmp/greeting.txt\").must_exist \n end \n \n it \"contains what's stored in the 'greeting' node \n attribute\" do \n file('/tmp/greeting.txt').must_include 'Ohai, Minitest!' \n end \nend" }, { "code": null, "e": 5662, "s": 5615, "text": "Step 10 − Edit your main cookbook's Berksfile." }, { "code": null, "e": 5871, "s": 5662, "text": "vipin@laptop:~/chef-repo/cookbooks/my_cookbook $ subl Berksfile \nsite :opscode \nmetadata \ncookbook \"apt\" \ncookbook \"minitest-handler\" \ncookbook \"my_cookbook_test\", path: \n\"./test/cookbooks/my_cookbook_test\" \n" }, { "code": null, "e": 6779, "s": 5871, "text": "vipin@laptop:~/chef-repo/cookbooks/my_cookbook $ kitchen test \n-----> Starting Kitchen (v1.0.0.alpha.7) \n...TRUNCATED OUTPUT... \n-----> Converging <default-ubuntu-1204> \n-----> Installing Chef Omnibus (true) \n...TRUNCATED OUTPUT... \nStarting Chef Client, version 11.4.4 \n[2013-06-29T18:33:57+00:00] INFO: *** Chef 11.4.4 *** \n[2013-06-29T18:33:58+00:00] INFO: Setting the run_list to \n[\"recipe[minitest-handler]\", \"recipe[my_cookbook_test]\"] \nfrom JSON \n...TRUNCATED OUTPUT... \n# Running tests: \nrecipe::my_cookbook::default::greeting \nfile#test_0001_creates the greeting file = 0.00 s = . \nrecipe::my_cookbook::default::greeting \nfile#test_0002_contains what's stored in the 'greeting' \nnode attribute = 0.00 s = . \nFinished tests in 0.011190s, 178.7277 tests/s, 178.7277 \nassertions/s. \n2 tests, 2 assertions, 0 failures, 0 errors, 0 skips \n...TRUNCATED OUTPUT... \n-----> Kitchen is finished. (2m5.69s) \n" }, { "code": null, "e": 6786, "s": 6779, "text": " Print" }, { "code": null, "e": 6797, "s": 6786, "text": " Add Notes" } ]
How to get this nodes’s parent in a JTree with Java?
Let’s say we want the parent of a node, then use the getParent() method - node3.getFirstChild() You can also get the parent of child node. Here, “nine” is the child node − nine.getParent() The output is as follows displaying this node’s parent on Console − package my; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; public class SwingDemo { public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Demo"); DefaultMutableTreeNode node = new DefaultMutableTreeNode("Products"); DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Clothing (Product1 - P66778)"); DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Accessories (Product2 - P66779)"); DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("Home Decor (Product3 - P66780)"); DefaultMutableTreeNode node4 = new DefaultMutableTreeNode("Electronics (Product4 - P66781)"); node.add(node1); node.add(node2); node.add(node3); node.add(node4); DefaultMutableTreeNode one = new DefaultMutableTreeNode("Shirt"); DefaultMutableTreeNode two = new DefaultMutableTreeNode("T-shirt"); DefaultMutableTreeNode three = new DefaultMutableTreeNode("Hoodie"); DefaultMutableTreeNode four = new DefaultMutableTreeNode("Sunglasses"); DefaultMutableTreeNode five = new DefaultMutableTreeNode("Frames"); DefaultMutableTreeNode six = new DefaultMutableTreeNode("Belts"); DefaultMutableTreeNode seven = new DefaultMutableTreeNode("Showpieces & Figurines"); DefaultMutableTreeNode eight = new DefaultMutableTreeNode("Clocks"); DefaultMutableTreeNode nine = new DefaultMutableTreeNode("Wall Shelves"); DefaultMutableTreeNode ten = new DefaultMutableTreeNode("Mobile Accessories"); DefaultMutableTreeNode eleven = new DefaultMutableTreeNode("Smart Wearable Tech"); DefaultMutableTreeNode twelve = new DefaultMutableTreeNode("Health Care Applicances"); DefaultMutableTreeNode thirteen = new DefaultMutableTreeNode("Smart Home Automation"); node1.add(one); node1.add(two); node1.add(three); node2.add(four); node2.add(five); node2.add(six); node3.add(seven); node3.add(eight); node3.add(nine); node4.add(ten); node4.add(eleven); node4.add(twelve); node4.add(thirteen); JTree tree = new JTree(node); for (int i = 0; i < tree.getRowCount(); i++) { tree.expandRow(i); } tree.putClientProperty("JTree.lineStyle", "Angled"); System.out.println("Node 3 = "+node.getChildAt(2)); System.out.println("The last child of node 3 = "+node3.getLastChild()); System.out.println("Parent of node3 = "+node3.getParent()); System.out.println("Parent of child node nine = "+nine.getParent()); tree.setRowHeight(25); frame.add(tree); frame.setSize(600,450); frame.setVisible(true); } } The output is as follows displaying this node’s parent − The following is our JTree −
[ { "code": null, "e": 1136, "s": 1062, "text": "Let’s say we want the parent of a node, then use the getParent() method -" }, { "code": null, "e": 1158, "s": 1136, "text": "node3.getFirstChild()" }, { "code": null, "e": 1234, "s": 1158, "text": "You can also get the parent of child node. Here, “nine” is the child node −" }, { "code": null, "e": 1251, "s": 1234, "text": "nine.getParent()" }, { "code": null, "e": 1319, "s": 1251, "text": "The output is as follows displaying this node’s parent on Console −" }, { "code": null, "e": 4060, "s": 1319, "text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JTree;\nimport javax.swing.tree.DefaultMutableTreeNode;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame(\"Demo\");\n DefaultMutableTreeNode node = new DefaultMutableTreeNode(\"Products\");\n DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(\"Clothing (Product1 - P66778)\");\n DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(\"Accessories (Product2 - P66779)\");\n DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(\"Home Decor (Product3 - P66780)\");\n DefaultMutableTreeNode node4 = new DefaultMutableTreeNode(\"Electronics (Product4 - P66781)\");\n node.add(node1);\n node.add(node2);\n node.add(node3);\n node.add(node4);\n DefaultMutableTreeNode one = new DefaultMutableTreeNode(\"Shirt\");\n DefaultMutableTreeNode two = new DefaultMutableTreeNode(\"T-shirt\");\n DefaultMutableTreeNode three = new DefaultMutableTreeNode(\"Hoodie\");\n DefaultMutableTreeNode four = new DefaultMutableTreeNode(\"Sunglasses\");\n DefaultMutableTreeNode five = new DefaultMutableTreeNode(\"Frames\");\n DefaultMutableTreeNode six = new DefaultMutableTreeNode(\"Belts\");\n DefaultMutableTreeNode seven = new DefaultMutableTreeNode(\"Showpieces & Figurines\");\n DefaultMutableTreeNode eight = new DefaultMutableTreeNode(\"Clocks\");\n DefaultMutableTreeNode nine = new DefaultMutableTreeNode(\"Wall Shelves\");\n DefaultMutableTreeNode ten = new DefaultMutableTreeNode(\"Mobile Accessories\");\n DefaultMutableTreeNode eleven = new DefaultMutableTreeNode(\"Smart Wearable Tech\");\n DefaultMutableTreeNode twelve = new DefaultMutableTreeNode(\"Health Care Applicances\");\n DefaultMutableTreeNode thirteen = new DefaultMutableTreeNode(\"Smart Home Automation\");\n node1.add(one);\n node1.add(two);\n node1.add(three);\n node2.add(four);\n node2.add(five);\n node2.add(six);\n node3.add(seven);\n node3.add(eight);\n node3.add(nine);\n node4.add(ten);\n node4.add(eleven);\n node4.add(twelve);\n node4.add(thirteen);\n JTree tree = new JTree(node);\n for (int i = 0; i < tree.getRowCount(); i++) {\n tree.expandRow(i);\n }\n tree.putClientProperty(\"JTree.lineStyle\", \"Angled\");\n System.out.println(\"Node 3 = \"+node.getChildAt(2));\n System.out.println(\"The last child of node 3 = \"+node3.getLastChild());\n System.out.println(\"Parent of node3 = \"+node3.getParent());\n System.out.println(\"Parent of child node nine = \"+nine.getParent());\n tree.setRowHeight(25);\n frame.add(tree);\n frame.setSize(600,450);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 4117, "s": 4060, "text": "The output is as follows displaying this node’s parent −" }, { "code": null, "e": 4146, "s": 4117, "text": "The following is our JTree −" } ]
How to read the data from a properties file in Java?
The Properties is a subclass of Hashtable class and it represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string. The Properties file can be used in Java to externalize the configuration and to store the key-value pairs. The Properties.load() method of Properties class is convenient to load .properties file in the form of key-value pairs. public class Properties extends Hashtable import java.io.*; import java.util.*; public class ReadPropertiesFileTest { public static void main(String args[]) throws IOException { Properties prop = readPropertiesFile("credentials.properties"); System.out.println("username: "+ prop.getProperty("username")); System.out.println("password: "+ prop.getProperty("password")); } public static Properties readPropertiesFile(String fileName) throws IOException { FileInputStream fis = null; Properties prop = null; try { fis = new FileInputStream(fileName); prop = new Properties(); prop.load(fis); } catch(FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch(IOException ioe) { ioe.printStackTrace(); } finally { fis.close(); } return prop; } } username: admin password: admin@123
[ { "code": null, "e": 1297, "s": 1062, "text": "The Properties is a subclass of Hashtable class and it represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string. " }, { "code": null, "e": 1524, "s": 1297, "text": "The Properties file can be used in Java to externalize the configuration and to store the key-value pairs. The Properties.load() method of Properties class is convenient to load .properties file in the form of key-value\npairs." }, { "code": null, "e": 1566, "s": 1524, "text": "public class Properties extends Hashtable" }, { "code": null, "e": 2402, "s": 1566, "text": "import java.io.*;\nimport java.util.*;\npublic class ReadPropertiesFileTest {\n public static void main(String args[]) throws IOException {\n Properties prop = readPropertiesFile(\"credentials.properties\");\n System.out.println(\"username: \"+ prop.getProperty(\"username\"));\n System.out.println(\"password: \"+ prop.getProperty(\"password\"));\n }\n public static Properties readPropertiesFile(String fileName) throws IOException {\n FileInputStream fis = null;\n Properties prop = null;\n try {\n fis = new FileInputStream(fileName);\n prop = new Properties();\n prop.load(fis);\n } catch(FileNotFoundException fnfe) {\n fnfe.printStackTrace();\n } catch(IOException ioe) {\n ioe.printStackTrace();\n } finally {\n fis.close();\n }\n return prop;\n }\n}" }, { "code": null, "e": 2438, "s": 2402, "text": "username: admin\npassword: admin@123" } ]
Redis - Sorted Set Zrank Command
Redis ZRANK command returns the rank of member in the sorted set stored at the key, with the scores ordered from low to high. The rank (or index) is 0-based, which means that the member with the lowest score has rank 0. If the member exists in the sorted set, Integer reply: the rank of member. If the member exists in the sorted set, Integer reply: the rank of member. If the member does not exist in the sorted set or the key does not exist, Bulk string reply − nil. If the member does not exist in the sorted set or the key does not exist, Bulk string reply − nil. Following is the basic syntax of Redis ZRANK command. redis 127.0.0.1:6379> ZRANK key member redis 127.0.0.1:6379> ZADD myzset 0 a 1 b 2 c 3 d 4 e (integer) 5 redis 127.0.0.1:6379> ZADD myzset 5 f 6 g (integer) 2 redis 127.0.0.1:6379> ZRANK myzset b (integer) 1 redis 127.0.0.1:6379> ZRANK myzset t nil 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2265, "s": 2045, "text": "Redis ZRANK command returns the rank of member in the sorted set stored at the key, with the scores ordered from low to high. The rank (or index) is 0-based, which means that the member with the lowest score has rank 0." }, { "code": null, "e": 2340, "s": 2265, "text": "If the member exists in the sorted set, Integer reply: the rank of member." }, { "code": null, "e": 2415, "s": 2340, "text": "If the member exists in the sorted set, Integer reply: the rank of member." }, { "code": null, "e": 2514, "s": 2415, "text": "If the member does not exist in the sorted set or the key does not exist, Bulk string reply − nil." }, { "code": null, "e": 2613, "s": 2514, "text": "If the member does not exist in the sorted set or the key does not exist, Bulk string reply − nil." }, { "code": null, "e": 2667, "s": 2613, "text": "Following is the basic syntax of Redis ZRANK command." }, { "code": null, "e": 2707, "s": 2667, "text": "redis 127.0.0.1:6379> ZRANK key member\n" }, { "code": null, "e": 2926, "s": 2707, "text": "redis 127.0.0.1:6379> ZADD myzset 0 a 1 b 2 c 3 d 4 e \n(integer) 5 \nredis 127.0.0.1:6379> ZADD myzset 5 f 6 g \n(integer) 2 \nredis 127.0.0.1:6379> ZRANK myzset b \n(integer) 1 \nredis 127.0.0.1:6379> ZRANK myzset t \nnil \n" }, { "code": null, "e": 2958, "s": 2926, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 2978, "s": 2958, "text": " Skillbakerystudios" }, { "code": null, "e": 2985, "s": 2978, "text": " Print" }, { "code": null, "e": 2996, "s": 2985, "text": " Add Notes" } ]
Finding the Word Analogy from given words using Word2Vec embeddings - GeeksforGeeks
22 Jan, 2021 In many placement exam rounds, we often encounter a basic question to find word analogies. In the word analogy task, we complete the sentence “a is to b as c is to ___ “, which is often represented as a : b :: c : d and we have to find the word ‘d’. A sample question can be like: ‘man is to woman as king is to ___‘. The human brain can recognize that the blank must be filled with the word ‘queen‘. But for a machine to understand this pattern and fill the blank with the most appropriate word requires a lot of training to be done. What if we can use a Machine Learning algorithm to automate this task of finding the word analogy. In this tutorial, we will be using Word2Vec model and a pre-trained model named ‘GoogleNews-vectors-negative300.bin‘ which is trained on over 50 Billion words by Google. Each word inside the pre-trained dataset is embedded in a 300-dimensional space and the words which are similar in context/meaning are placed closer to each other in the space. Methodology to find out the analogous word: In this problem, our goal is to find a word d, such that the associated word vectors va, vb, vc, vd are related to each other in the following relationship: ‘vb – va = vd – vc‘. We will measure the similarity between vb-va and vd-vc using cosine similarity. Importing important libraries: We need to install an additional gensim library, to use word2vec model, to install gensim use the command ‘pip install gensim‘ on your terminal/command prompt. Python3 import numpy as npimport gensimfrom gensim.models import word2vec,KeyedVectorsfrom sklearn.metrics.pairwise import cosine_similarity Loading the word vectors using the pre-trained model: Python3 vector_word_notations = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin',binary=True) Defining a function to predict analogous word: Python3 def analogous_word(word_1,word_2,word_3,vector_word_notations): ''' The function accepts a triad of words, word_1, word_2, word_3 and returns word_4 such that word_1:word_2::word_3:word_4 ''' # converting each word to its lowercase word_1,word_2,word_3 = word_1.lower(),word_2.lower(),word_3.lower() # Similarity between |word_2-word_1| = |word_4-word_3| should be maximum maximum_similarity = -99999 word_4 = None words = vector_word_notations.vocab.keys() va,vb,vc = vector_word_notations[word_1],\ vector_word_notations[word_2],vector_word_notations[word_3] # to find word_4 such that similarity # (|word_2 - word_1|, |word_4 - word_3|) should be maximum for i in words: if i in [word_1,word_2,word_3]: continue wvec = vector_word_notations[i] similarity = cosine_similarity(,[wvec-vc]) if similarity > maximum_similarity: maximum_similarity = similarity word_4 = i return word_4 Testing our model: Python3 triad_1 = ("Man","Woman","King")# *triad_1 is written to unpack the elements in the tupleoutput = analogous_word(*triad_1,word_vectors) print(output) # The output will be shown as queen Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Support Vector Machine Algorithm k-nearest neighbor algorithm in Python Intuition of Adam Optimizer Singular Value Decomposition (SVD) ML | Logistic Regression using Python 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": 24344, "s": 24316, "text": "\n22 Jan, 2021" }, { "code": null, "e": 24664, "s": 24344, "text": "In many placement exam rounds, we often encounter a basic question to find word analogies. In the word analogy task, we complete the sentence “a is to b as c is to ___ “, which is often represented as a : b :: c : d and we have to find the word ‘d’. A sample question can be like: ‘man is to woman as king is to ___‘. " }, { "code": null, "e": 25327, "s": 24664, "text": "The human brain can recognize that the blank must be filled with the word ‘queen‘. But for a machine to understand this pattern and fill the blank with the most appropriate word requires a lot of training to be done. What if we can use a Machine Learning algorithm to automate this task of finding the word analogy. In this tutorial, we will be using Word2Vec model and a pre-trained model named ‘GoogleNews-vectors-negative300.bin‘ which is trained on over 50 Billion words by Google. Each word inside the pre-trained dataset is embedded in a 300-dimensional space and the words which are similar in context/meaning are placed closer to each other in the space." }, { "code": null, "e": 25371, "s": 25327, "text": "Methodology to find out the analogous word:" }, { "code": null, "e": 25629, "s": 25371, "text": "In this problem, our goal is to find a word d, such that the associated word vectors va, vb, vc, vd are related to each other in the following relationship: ‘vb – va = vd – vc‘. We will measure the similarity between vb-va and vd-vc using cosine similarity." }, { "code": null, "e": 25660, "s": 25629, "text": "Importing important libraries:" }, { "code": null, "e": 25820, "s": 25660, "text": "We need to install an additional gensim library, to use word2vec model, to install gensim use the command ‘pip install gensim‘ on your terminal/command prompt." }, { "code": null, "e": 25828, "s": 25820, "text": "Python3" }, { "code": "import numpy as npimport gensimfrom gensim.models import word2vec,KeyedVectorsfrom sklearn.metrics.pairwise import cosine_similarity", "e": 25961, "s": 25828, "text": null }, { "code": null, "e": 26015, "s": 25961, "text": "Loading the word vectors using the pre-trained model:" }, { "code": null, "e": 26023, "s": 26015, "text": "Python3" }, { "code": "vector_word_notations = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin',binary=True)", "e": 26131, "s": 26023, "text": null }, { "code": null, "e": 26178, "s": 26131, "text": "Defining a function to predict analogous word:" }, { "code": null, "e": 26186, "s": 26178, "text": "Python3" }, { "code": "def analogous_word(word_1,word_2,word_3,vector_word_notations): ''' The function accepts a triad of words, word_1, word_2, word_3 and returns word_4 such that word_1:word_2::word_3:word_4 ''' # converting each word to its lowercase word_1,word_2,word_3 = word_1.lower(),word_2.lower(),word_3.lower() # Similarity between |word_2-word_1| = |word_4-word_3| should be maximum maximum_similarity = -99999 word_4 = None words = vector_word_notations.vocab.keys() va,vb,vc = vector_word_notations[word_1],\\ vector_word_notations[word_2],vector_word_notations[word_3] # to find word_4 such that similarity # (|word_2 - word_1|, |word_4 - word_3|) should be maximum for i in words: if i in [word_1,word_2,word_3]: continue wvec = vector_word_notations[i] similarity = cosine_similarity(,[wvec-vc]) if similarity > maximum_similarity: maximum_similarity = similarity word_4 = i return word_4", "e": 27238, "s": 26186, "text": null }, { "code": null, "e": 27257, "s": 27238, "text": "Testing our model:" }, { "code": null, "e": 27265, "s": 27257, "text": "Python3" }, { "code": "triad_1 = (\"Man\",\"Woman\",\"King\")# *triad_1 is written to unpack the elements in the tupleoutput = analogous_word(*triad_1,word_vectors) print(output) # The output will be shown as queen", "e": 27452, "s": 27265, "text": null }, { "code": null, "e": 27469, "s": 27452, "text": "Machine Learning" }, { "code": null, "e": 27476, "s": 27469, "text": "Python" }, { "code": null, "e": 27493, "s": 27476, "text": "Machine Learning" }, { "code": null, "e": 27591, "s": 27493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27624, "s": 27591, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 27663, "s": 27624, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 27691, "s": 27663, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 27726, "s": 27691, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 27764, "s": 27726, "text": "ML | Logistic Regression using Python" }, { "code": null, "e": 27792, "s": 27764, "text": "Read JSON file using Python" }, { "code": null, "e": 27842, "s": 27792, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27864, "s": 27842, "text": "Python map() function" } ]
How can we use a MySQL subquery with INSERT statement?
It can be understood with the help of an example in which we would copy the values of a table into other table. We are using the data from table ‘cars’ and copy its data to table ‘copy_cars’ − mysql> CREATE TABLE copy_cars LIKE cars; Query OK, 0 rows affected (0.86 sec) mysql> SELECT * from copy_cars; Empty set (0.08 sec) The following query using the subquery will insert the values same as ‘cars’ to table ‘copy_cars’ − mysql> INSERT INTO Copy_cars Select * from Cars; Query OK, 8 rows affected (0.07 sec) mysql> SELECT * from copy_cars; +------+--------------+---------+ | ID | Name | Price | +------+--------------+---------+ | 1 | Nexa | 750000 | | 2 | Maruti Swift | 450000 | | 3 | BMW | 4450000 | | 4 | VOLVO | 2250000 | | 5 | Alto | 250000 | | 6 | Skoda | 1250000 | | 7 | Toyota | 2400000 | | 8 | Ford | 1100000 | +------+--------------+---------+ 8 rows in set (0.00 sec)
[ { "code": null, "e": 1255, "s": 1062, "text": "It can be understood with the help of an example in which we would copy the values of a table into other table. We are using the data from table ‘cars’ and copy its data to table ‘copy_cars’ −" }, { "code": null, "e": 1387, "s": 1255, "text": "mysql> CREATE TABLE copy_cars LIKE cars;\nQuery OK, 0 rows affected (0.86 sec)\n\nmysql> SELECT * from copy_cars;\nEmpty set (0.08 sec)" }, { "code": null, "e": 1487, "s": 1387, "text": "The following query using the subquery will insert the values same as ‘cars’ to table ‘copy_cars’ −" }, { "code": null, "e": 2039, "s": 1487, "text": "mysql> INSERT INTO Copy_cars Select * from Cars;\nQuery OK, 8 rows affected (0.07 sec)\n\nmysql> SELECT * from copy_cars;\n+------+--------------+---------+\n| ID | Name | Price |\n+------+--------------+---------+\n| 1 | Nexa | 750000 |\n| 2 | Maruti Swift | 450000 |\n| 3 | BMW | 4450000 |\n| 4 | VOLVO | 2250000 |\n| 5 | Alto | 250000 |\n| 6 | Skoda | 1250000 |\n| 7 | Toyota | 2400000 |\n| 8 | Ford | 1100000 |\n+------+--------------+---------+\n8 rows in set (0.00 sec)" } ]
Binarization of Digital Images Using Otsu Method in MATLAB - GeeksforGeeks
23 Nov, 2021 Binarization is important in digital image processing, mainly in computer vision applications. Thresholding is an efficient technique in binarization. The choice of thresholding technique is crucial in binarization. There are various thresholding algorithms have been proposed to define the optimal threshold value. Binarization can be used in recognising text and symbols, e.g. document processing. Identifying objects with distinctive silhouettes, e.g. components on a conveyor in a manufacturing plant, and determining the orientation of objects are some other examples of binarization applications. Binarization generally involves two steps including the determination of a gray threshold according to some objective criteria and assigning each pixel to one class of background or foreground. If the intensity of the pixel is greater than the determined threshold then it belongs to the foreground class and otherwise to the background. The main problem in binarization is the choice of thresholding technique. The thresholding algorithms can be categorized into different classes: Histogram shape-based methods Clustering-based methods Entropy-based methods Object attribute-based methods Spatial methods and local methods are based on the local characteristics of each pixel. Grayscale image: A grayscale image is the one that has the same value for each channel. Grayscale images have only colours of gray shades, Gray shades are not only black and white. If the image has 8-bit depth. It can have 255 shades of gray between dark and white. Sometimes grayscale images are also called black and white images. Binary image: Binary images are useful in many image processing applications due to their features. A binary image is produced by quantization of the image gray levels to two values, usually 0 and 1. A binary image has only two shades of colour. All the pixels have either dark or white as colour. The dark shade is represented by 0 and the white shade is represented by 1. The image matrix consists of 0 and 1 only. Otsu’s method: Otsu’s thresholding technique is a classification-based method which searches for the threshold that minimizes the intra-class variance, defined as a weighted sum of variances of the two classes. It is the most popular method of binarizing a grayscale image. Otsu’s algorithms simply assume that a grayscale image consists of two types of pixels. Foreground and background pixels. It divides all the pixels into two clusters. It minimises the intra-cluster variation by maximising the inter-cluster variance. Finally, it returns a single intensity value which is called a threshold value. This threshold value divides the two clusters of pixels. All pixels of one cluster are assigned intensity value 0 and pixels of the second cluster are assigned value 1. Thus, it binarises the grayscale image. Steps: Read the coloured image. Convert it into a grayscale image. Apply Otsu’s thresholding function. Convert grayscale image into a binary image using a threshold. Display the binary image. Binarize the grayscale image using the local otsu’s method. Display the image. Function Used: imread ( ) inbuilt function is used to read the image. imtool( ) inbuilt function is used to display image. rgb2gray( ) inbuilt function is used to convert RGB image into grayscale. graythresh( ) inbuilt function is used to find Otsu’s threshold. im2bw( ) inbuilt function is used to convert grayscale into binary image. nlfilter( ) inbuilt function is used to iterate the function over distinct blocks of [m n] size. Example: Matlab % MATLAB code for% OTSU binarisation%read the colored image.k=imread("apple.jpeg"); %display the image.imtool(k,[]); %convert into grayscale image.k=rgb2gray(k); %calculate threshold using Otsu's method.level=graythresh(k); %convert into binary image using level.k1=imbinarize(k,level); %display the binarized image.imtool(k1); %find the local thresholds for windows.k2=nlfilter(k,[100 100], @ibimage); %display the binary image.imtool(k2); %find the local thresholds for smaller window.k3=nlfilter(k,[50 50], @ibimage); %display the binary image.imtool(k3); %ibimage function.%this function finds the%threshold for patches of image.function f=ibimage(k)[x, y]=size(k);level=graythresh(k);bw=imbinarize(k,level);x1=round(x/2);y1=round(y/2);f=bw(x1, y1);end Output: figure 1: Binary image using Global Otsu figure 2: Binary image using Local Otsu with window size [100 100] figure 3: Binary image using Local Otsu with window size [50 50] figure 4: Results on GeeksforGeeks logo The global otsu method is not good always. A smaller window size results in a low-quality binary image. Optimum window size results in a high-quality binary image. MATLAB image-processing MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Remove Noise from Digital Image in Frequency Domain Using MATLAB? Boundary Extraction of image using MATLAB Forward and Inverse Fourier Transform of an Image in MATLAB Laplacian of Gaussian Filter in MATLAB Differential or Derivatives in MATLAB How to Solve Histogram Equalization Numerical Problem in MATLAB? Laplace Transform in MATLAB MATLAB Syntax What is Upsampling in MATLAB? How to Normalize a Histogram in MATLAB?
[ { "code": null, "e": 24670, "s": 24642, "text": "\n23 Nov, 2021" }, { "code": null, "e": 24986, "s": 24670, "text": "Binarization is important in digital image processing, mainly in computer vision applications. Thresholding is an efficient technique in binarization. The choice of thresholding technique is crucial in binarization. There are various thresholding algorithms have been proposed to define the optimal threshold value." }, { "code": null, "e": 25685, "s": 24986, "text": "Binarization can be used in recognising text and symbols, e.g. document processing. Identifying objects with distinctive silhouettes, e.g. components on a conveyor in a manufacturing plant, and determining the orientation of objects are some other examples of binarization applications. Binarization generally involves two steps including the determination of a gray threshold according to some objective criteria and assigning each pixel to one class of background or foreground. If the intensity of the pixel is greater than the determined threshold then it belongs to the foreground class and otherwise to the background. The main problem in binarization is the choice of thresholding technique." }, { "code": null, "e": 25757, "s": 25685, "text": "The thresholding algorithms can be categorized into different classes: " }, { "code": null, "e": 25788, "s": 25757, "text": "Histogram shape-based methods " }, { "code": null, "e": 25814, "s": 25788, "text": "Clustering-based methods " }, { "code": null, "e": 25836, "s": 25814, "text": "Entropy-based methods" }, { "code": null, "e": 25868, "s": 25836, "text": " Object attribute-based methods" }, { "code": null, "e": 25957, "s": 25868, "text": " Spatial methods and local methods are based on the local characteristics of each pixel." }, { "code": null, "e": 26290, "s": 25957, "text": "Grayscale image: A grayscale image is the one that has the same value for each channel. Grayscale images have only colours of gray shades, Gray shades are not only black and white. If the image has 8-bit depth. It can have 255 shades of gray between dark and white. Sometimes grayscale images are also called black and white images." }, { "code": null, "e": 26707, "s": 26290, "text": "Binary image: Binary images are useful in many image processing applications due to their features. A binary image is produced by quantization of the image gray levels to two values, usually 0 and 1. A binary image has only two shades of colour. All the pixels have either dark or white as colour. The dark shade is represented by 0 and the white shade is represented by 1. The image matrix consists of 0 and 1 only." }, { "code": null, "e": 27520, "s": 26707, "text": "Otsu’s method: Otsu’s thresholding technique is a classification-based method which searches for the threshold that minimizes the intra-class variance, defined as a weighted sum of variances of the two classes. It is the most popular method of binarizing a grayscale image. Otsu’s algorithms simply assume that a grayscale image consists of two types of pixels. Foreground and background pixels. It divides all the pixels into two clusters. It minimises the intra-cluster variation by maximising the inter-cluster variance. Finally, it returns a single intensity value which is called a threshold value. This threshold value divides the two clusters of pixels. All pixels of one cluster are assigned intensity value 0 and pixels of the second cluster are assigned value 1. Thus, it binarises the grayscale image." }, { "code": null, "e": 27527, "s": 27520, "text": "Steps:" }, { "code": null, "e": 27552, "s": 27527, "text": "Read the coloured image." }, { "code": null, "e": 27587, "s": 27552, "text": "Convert it into a grayscale image." }, { "code": null, "e": 27623, "s": 27587, "text": "Apply Otsu’s thresholding function." }, { "code": null, "e": 27686, "s": 27623, "text": "Convert grayscale image into a binary image using a threshold." }, { "code": null, "e": 27712, "s": 27686, "text": "Display the binary image." }, { "code": null, "e": 27772, "s": 27712, "text": "Binarize the grayscale image using the local otsu’s method." }, { "code": null, "e": 27791, "s": 27772, "text": "Display the image." }, { "code": null, "e": 27806, "s": 27791, "text": "Function Used:" }, { "code": null, "e": 27861, "s": 27806, "text": "imread ( ) inbuilt function is used to read the image." }, { "code": null, "e": 27914, "s": 27861, "text": "imtool( ) inbuilt function is used to display image." }, { "code": null, "e": 27988, "s": 27914, "text": "rgb2gray( ) inbuilt function is used to convert RGB image into grayscale." }, { "code": null, "e": 28053, "s": 27988, "text": "graythresh( ) inbuilt function is used to find Otsu’s threshold." }, { "code": null, "e": 28127, "s": 28053, "text": "im2bw( ) inbuilt function is used to convert grayscale into binary image." }, { "code": null, "e": 28224, "s": 28127, "text": "nlfilter( ) inbuilt function is used to iterate the function over distinct blocks of [m n] size." }, { "code": null, "e": 28233, "s": 28224, "text": "Example:" }, { "code": null, "e": 28240, "s": 28233, "text": "Matlab" }, { "code": "% MATLAB code for% OTSU binarisation%read the colored image.k=imread(\"apple.jpeg\"); %display the image.imtool(k,[]); %convert into grayscale image.k=rgb2gray(k); %calculate threshold using Otsu's method.level=graythresh(k); %convert into binary image using level.k1=imbinarize(k,level); %display the binarized image.imtool(k1); %find the local thresholds for windows.k2=nlfilter(k,[100 100], @ibimage); %display the binary image.imtool(k2); %find the local thresholds for smaller window.k3=nlfilter(k,[50 50], @ibimage); %display the binary image.imtool(k3); %ibimage function.%this function finds the%threshold for patches of image.function f=ibimage(k)[x, y]=size(k);level=graythresh(k);bw=imbinarize(k,level);x1=round(x/2);y1=round(y/2);f=bw(x1, y1);end", "e": 29007, "s": 28240, "text": null }, { "code": null, "e": 29015, "s": 29007, "text": "Output:" }, { "code": null, "e": 29058, "s": 29017, "text": "figure 1: Binary image using Global Otsu" }, { "code": null, "e": 29125, "s": 29058, "text": "figure 2: Binary image using Local Otsu with window size [100 100]" }, { "code": null, "e": 29191, "s": 29125, "text": " figure 3: Binary image using Local Otsu with window size [50 50]" }, { "code": null, "e": 29233, "s": 29193, "text": "figure 4: Results on GeeksforGeeks logo" }, { "code": null, "e": 29276, "s": 29233, "text": "The global otsu method is not good always." }, { "code": null, "e": 29337, "s": 29276, "text": "A smaller window size results in a low-quality binary image." }, { "code": null, "e": 29397, "s": 29337, "text": "Optimum window size results in a high-quality binary image." }, { "code": null, "e": 29421, "s": 29397, "text": "MATLAB image-processing" }, { "code": null, "e": 29428, "s": 29421, "text": "MATLAB" }, { "code": null, "e": 29526, "s": 29428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29535, "s": 29526, "text": "Comments" }, { "code": null, "e": 29548, "s": 29535, "text": "Old Comments" }, { "code": null, "e": 29621, "s": 29548, "text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?" }, { "code": null, "e": 29663, "s": 29621, "text": "Boundary Extraction of image using MATLAB" }, { "code": null, "e": 29723, "s": 29663, "text": "Forward and Inverse Fourier Transform of an Image in MATLAB" }, { "code": null, "e": 29762, "s": 29723, "text": "Laplacian of Gaussian Filter in MATLAB" }, { "code": null, "e": 29800, "s": 29762, "text": "Differential or Derivatives in MATLAB" }, { "code": null, "e": 29865, "s": 29800, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 29893, "s": 29865, "text": "Laplace Transform in MATLAB" }, { "code": null, "e": 29907, "s": 29893, "text": "MATLAB Syntax" }, { "code": null, "e": 29937, "s": 29907, "text": "What is Upsampling in MATLAB?" } ]
Objective-C - if...else statement
An if statement can be followed by an optional else statement, which executes when the boolean expression is false. The syntax of an if...else statement in Objective-C programming language is − if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ } If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed. Objective-C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value. #import <Foundation/Foundation.h> int main () { /* local variable definition */ int a = 100; /* check the boolean condition */ if( a < 20 ) { /* if condition is true then print the following */ NSLog(@"a is less than 20\n" ); } else { /* if condition is false then print the following */ NSLog(@"a is not less than 20\n" ); } NSLog(@"value of a is : %d\n", a); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-07 22:04:10.199 demo[3537] a is not less than 20 2013-09-07 22:04:10.200 demo[3537] value of a is : 100 An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. When using if , else if , else statements there are few points to keep in mind − An if can have zero or one else's and it must come after any else if's. An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested. Once an else if succeeds, none of the remaining else if's or else's will be tested. The syntax of an if...else if...else statement in Objective-C programming language is − if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */ } else if( boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } else if( boolean_expression 3) { /* Executes when the boolean expression 3 is true */ } else { /* executes when the none of the above condition is true */ } #import <Foundation/Foundation.h> int main () { /* local variable definition */ int a = 100; /* check the boolean condition */ if( a == 10 ) { /* if condition is true then print the following */ NSLog(@"Value of a is 10\n" ); } else if( a == 20 ) { /* if else if condition is true */ NSLog(@"Value of a is 20\n" ); } else if( a == 30 ) { /* if else if condition is true */ NSLog(@"Value of a is 30\n" ); } else { /* if none of the conditions is true */ NSLog(@"None of the values is matching\n" ); } NSLog(@"Exact value of a is: %d\n", a ); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-07 22:05:34.168 demo[8465] None of the values is matching 2013-09-07 22:05:34.168 demo[8465] Exact value of a is: 100 18 Lectures 1 hours PARTHA MAJUMDAR 6 Lectures 25 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2676, "s": 2560, "text": "An if statement can be followed by an optional else statement, which executes when the boolean expression is false." }, { "code": null, "e": 2754, "s": 2676, "text": "The syntax of an if...else statement in Objective-C programming language is −" }, { "code": null, "e": 2928, "s": 2754, "text": "if(boolean_expression) {\n /* statement(s) will execute if the boolean expression is true */\n} else {\n /* statement(s) will execute if the boolean expression is false */\n}" }, { "code": null, "e": 3064, "s": 2928, "text": "If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed." }, { "code": null, "e": 3216, "s": 3064, "text": "Objective-C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value." }, { "code": null, "e": 3645, "s": 3216, "text": "#import <Foundation/Foundation.h>\n \nint main () {\n /* local variable definition */\n int a = 100;\n \n /* check the boolean condition */\n if( a < 20 ) {\n /* if condition is true then print the following */\n NSLog(@\"a is less than 20\\n\" );\n } else {\n /* if condition is false then print the following */\n NSLog(@\"a is not less than 20\\n\" );\n }\n \n NSLog(@\"value of a is : %d\\n\", a);\n return 0;\n}" }, { "code": null, "e": 3726, "s": 3645, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3839, "s": 3726, "text": "2013-09-07 22:04:10.199 demo[3537] a is not less than 20\n2013-09-07 22:04:10.200 demo[3537] value of a is : 100\n" }, { "code": null, "e": 3997, "s": 3839, "text": "An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement." }, { "code": null, "e": 4078, "s": 3997, "text": "When using if , else if , else statements there are few points to keep in mind −" }, { "code": null, "e": 4150, "s": 4078, "text": "An if can have zero or one else's and it must come after any else if's." }, { "code": null, "e": 4222, "s": 4150, "text": "An if can have zero or one else's and it must come after any else if's." }, { "code": null, "e": 4296, "s": 4222, "text": "An if can have zero to many else if's and they must come before the else." }, { "code": null, "e": 4370, "s": 4296, "text": "An if can have zero to many else if's and they must come before the else." }, { "code": null, "e": 4454, "s": 4370, "text": "Once an else if succeeds, none of the remaining else if's or else's will be tested." }, { "code": null, "e": 4538, "s": 4454, "text": "Once an else if succeeds, none of the remaining else if's or else's will be tested." }, { "code": null, "e": 4626, "s": 4538, "text": "The syntax of an if...else if...else statement in Objective-C programming language is −" }, { "code": null, "e": 4965, "s": 4626, "text": "if(boolean_expression 1) {\n /* Executes when the boolean expression 1 is true */\n} else if( boolean_expression 2) {\n /* Executes when the boolean expression 2 is true */\n} else if( boolean_expression 3) {\n /* Executes when the boolean expression 3 is true */\n} else {\n /* executes when the none of the above condition is true */\n}" }, { "code": null, "e": 5605, "s": 4965, "text": "#import <Foundation/Foundation.h>\n \nint main () {\n /* local variable definition */\n int a = 100;\n \n /* check the boolean condition */\n if( a == 10 ) {\n /* if condition is true then print the following */\n NSLog(@\"Value of a is 10\\n\" );\n } else if( a == 20 ) {\n /* if else if condition is true */\n NSLog(@\"Value of a is 20\\n\" );\n } else if( a == 30 ) {\n /* if else if condition is true */\n NSLog(@\"Value of a is 30\\n\" );\n } else {\n /* if none of the conditions is true */\n NSLog(@\"None of the values is matching\\n\" );\n }\n \n NSLog(@\"Exact value of a is: %d\\n\", a );\n return 0;\n}" }, { "code": null, "e": 5686, "s": 5605, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5813, "s": 5686, "text": "2013-09-07 22:05:34.168 demo[8465] None of the values is matching\n2013-09-07 22:05:34.168 demo[8465] Exact value of a is: 100\n" }, { "code": null, "e": 5846, "s": 5813, "text": "\n 18 Lectures \n 1 hours \n" }, { "code": null, "e": 5863, "s": 5846, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 5894, "s": 5863, "text": "\n 6 Lectures \n 25 mins\n" }, { "code": null, "e": 5905, "s": 5894, "text": " Ken Burke" }, { "code": null, "e": 5912, "s": 5905, "text": " Print" }, { "code": null, "e": 5923, "s": 5912, "text": " Add Notes" } ]
DAX Aggregation - SUM function
Returns the sum of all the numbers in a column. SUM (<column>) column The column that contains the numbers to sum. A decimal number. If any rows contain non-numeric values, blanks are returned. = SUM ([Sales Amount]) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2049, "s": 2001, "text": "Returns the sum of all the numbers in a column." }, { "code": null, "e": 2066, "s": 2049, "text": "SUM (<column>) \n" }, { "code": null, "e": 2073, "s": 2066, "text": "column" }, { "code": null, "e": 2118, "s": 2073, "text": "The column that contains the numbers to sum." }, { "code": null, "e": 2136, "s": 2118, "text": "A decimal number." }, { "code": null, "e": 2197, "s": 2136, "text": "If any rows contain non-numeric values, blanks are returned." }, { "code": null, "e": 2221, "s": 2197, "text": "= SUM ([Sales Amount]) " }, { "code": null, "e": 2256, "s": 2221, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2270, "s": 2256, "text": " Abhay Gadiya" }, { "code": null, "e": 2303, "s": 2270, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 2317, "s": 2303, "text": " Randy Minder" }, { "code": null, "e": 2352, "s": 2317, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2366, "s": 2352, "text": " Randy Minder" }, { "code": null, "e": 2373, "s": 2366, "text": " Print" }, { "code": null, "e": 2384, "s": 2373, "text": " Add Notes" } ]
GATE | GATE CS 2019 | Question 33 - GeeksforGeeks
05 Aug, 2021 Consider the following C program: #include<stdio.h> int main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 5}, *ip = arr + 4; printf("%d\n", ip[1]); return 0;} The number that will be displayed on execution of the program is _________ .(A) 6(B) 5(C) 4(D) segmentation errorAnswer: (A)Explanation: #include<stdio.h> int main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 5}, *ip = arr + 4; printf("%d\n", ip[1]); return 0;} Note that index of array always start from 0 in C. Initially ip pointer is pointing at (arr+4) or skipping starting first 4 position. Now in the printf system call, 1 more position is to skip, So it will point to (arr+5) or skip 5 position from starting: Hence, printf will print value at 6th position, i.e., 6 will printed. So, option (A) is correct. YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch 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:005:07 / 1:16:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fP8QED8d6ws" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2007 | Question 17 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 1997 | Question 25
[ { "code": null, "e": 24298, "s": 24270, "text": "\n05 Aug, 2021" }, { "code": null, "e": 24332, "s": 24298, "text": "Consider the following C program:" }, { "code": "#include<stdio.h> int main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 5}, *ip = arr + 4; printf(\"%d\\n\", ip[1]); return 0;}", "e": 24471, "s": 24332, "text": null }, { "code": null, "e": 24608, "s": 24471, "text": "The number that will be displayed on execution of the program is _________ .(A) 6(B) 5(C) 4(D) segmentation errorAnswer: (A)Explanation:" }, { "code": "#include<stdio.h> int main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 5}, *ip = arr + 4; printf(\"%d\\n\", ip[1]); return 0;}", "e": 24747, "s": 24608, "text": null }, { "code": null, "e": 24798, "s": 24747, "text": "Note that index of array always start from 0 in C." }, { "code": null, "e": 24881, "s": 24798, "text": "Initially ip pointer is pointing at (arr+4) or skipping starting first 4 position." }, { "code": null, "e": 25002, "s": 24881, "text": "Now in the printf system call, 1 more position is to skip, So it will point to (arr+5) or skip 5 position from starting:" }, { "code": null, "e": 25072, "s": 25002, "text": "Hence, printf will print value at 6th position, i.e., 6 will printed." }, { "code": null, "e": 25099, "s": 25072, "text": "So, option (A) is correct." }, { "code": null, "e": 26029, "s": 25099, "text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch 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:005:07 / 1:16:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fP8QED8d6ws\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 26034, "s": 26029, "text": "GATE" }, { "code": null, "e": 26132, "s": 26034, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26141, "s": 26132, "text": "Comments" }, { "code": null, "e": 26154, "s": 26141, "text": "Old Comments" }, { "code": null, "e": 26188, "s": 26154, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 26230, "s": 26188, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 26264, "s": 26230, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 26306, "s": 26264, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 26348, "s": 26306, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 26390, "s": 26348, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26432, "s": 26390, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 26466, "s": 26432, "text": "GATE | GATE-CS-2007 | Question 17" }, { "code": null, "e": 26508, "s": 26466, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" } ]
Heap Data Structures
Heap is a special case of balanced binary tree data structure where the root-node key is compared with its children and arranged accordingly. If α has child node β then − key(α) ≥ key(β) As the value of parent is greater than that of child, this property generates Max Heap. Based on this criteria, a heap can be of two types − For Input → 35 33 42 10 14 19 27 44 26 31 Min-Heap − Where the value of the root node is less than or equal to either of its children. Max-Heap − Where the value of the root node is greater than or equal to either of its children. Both trees are constructed using the same input and order of arrival. We shall use the same example to demonstrate how a Max Heap is created. The procedure to create Min Heap is similar but we go for min values instead of max values. We are going to derive an algorithm for max heap by inserting one element at a time. At any point of time, heap must maintain its property. While insertion, we also assume that we are inserting a node in an already heapified tree. Step 1 − Create a new node at the end of heap. Step 2 − Assign new value to the node. Step 3 − Compare the value of this child node with its parent. Step 4 − If value of parent is less than child, then swap them. Step 5 − Repeat step 3 & 4 until Heap property holds. Note − In Min Heap construction algorithm, we expect the value of the parent node to be less than that of the child node. Let's understand Max Heap construction by an animated illustration. We consider the same input sample that we used earlier. Let us derive an algorithm to delete from max heap. Deletion in Max (or Min) Heap always happens at the root to remove the Maximum (or minimum) value. Step 1 − Remove root node. Step 2 − Move the last element of last level to root. Step 3 − Compare the value of this child node with its parent. Step 4 − If value of parent is less than child, then swap them. Step 5 − Repeat step 3 & 4 until Heap property holds. 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2751, "s": 2580, "text": "Heap is a special case of balanced binary tree data structure where the root-node key is compared with its children and arranged accordingly. If α has child node β then −" }, { "code": null, "e": 2767, "s": 2751, "text": "key(α) ≥ key(β)" }, { "code": null, "e": 2908, "s": 2767, "text": "As the value of parent is greater than that of child, this property generates Max Heap. Based on this criteria, a heap can be of two types −" }, { "code": null, "e": 2951, "s": 2908, "text": "For Input → 35 33 42 10 14 19 27 44 26 31\n" }, { "code": null, "e": 3044, "s": 2951, "text": "Min-Heap − Where the value of the root node is less than or equal to either of its children." }, { "code": null, "e": 3140, "s": 3044, "text": "Max-Heap − Where the value of the root node is greater than or equal to either of its children." }, { "code": null, "e": 3210, "s": 3140, "text": "Both trees are constructed using the same input and order of arrival." }, { "code": null, "e": 3374, "s": 3210, "text": "We shall use the same example to demonstrate how a Max Heap is created. The procedure to create Min Heap is similar but we go for min values instead of max values." }, { "code": null, "e": 3605, "s": 3374, "text": "We are going to derive an algorithm for max heap by inserting one element at a time. At any point of time, heap must maintain its property. While insertion, we also assume that we are inserting a node in an already heapified tree." }, { "code": null, "e": 3873, "s": 3605, "text": "Step 1 − Create a new node at the end of heap.\nStep 2 − Assign new value to the node.\nStep 3 − Compare the value of this child node with its parent.\nStep 4 − If value of parent is less than child, then swap them.\nStep 5 − Repeat step 3 & 4 until Heap property holds.\n" }, { "code": null, "e": 3995, "s": 3873, "text": "Note − In Min Heap construction algorithm, we expect the value of the parent node to be less than that of the child node." }, { "code": null, "e": 4119, "s": 3995, "text": "Let's understand Max Heap construction by an animated illustration. We consider the same input sample that we used earlier." }, { "code": null, "e": 4270, "s": 4119, "text": "Let us derive an algorithm to delete from max heap. Deletion in Max (or Min) Heap always happens at the root to remove the Maximum (or minimum) value." }, { "code": null, "e": 4533, "s": 4270, "text": "Step 1 − Remove root node.\nStep 2 − Move the last element of last level to root.\nStep 3 − Compare the value of this child node with its parent.\nStep 4 − If value of parent is less than child, then swap them.\nStep 5 − Repeat step 3 & 4 until Heap property holds.\n" }, { "code": null, "e": 4568, "s": 4533, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4580, "s": 4568, "text": " Ravi Kiran" }, { "code": null, "e": 4615, "s": 4580, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 4634, "s": 4615, "text": " Arnab Chakraborty" }, { "code": null, "e": 4669, "s": 4634, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4684, "s": 4669, "text": " Parth Panjabi" }, { "code": null, "e": 4717, "s": 4684, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 4736, "s": 4717, "text": " Arnab Chakraborty" }, { "code": null, "e": 4770, "s": 4736, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4798, "s": 4770, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4834, "s": 4798, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4862, "s": 4834, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4869, "s": 4862, "text": " Print" }, { "code": null, "e": 4880, "s": 4869, "text": " Add Notes" } ]
How to query between two dates in MySQL?
You can query between dates with the help of BETWEEN statement. The syntax is as follows − select *from yourTableName where yourColumnName between ‘yourStartingDate’ and curdate(). Use curdate() or now(), both these functions will work. To understand the above syntax, let us create a table − mysql> create table BetweenDateDemo −> ( −> StartDate datetime −> ); Query OK, 0 rows affected (0.78 sec) Insert some records in the table with the help of the following query − mysql> insert into BetweenDateDemo values(date_add(now(),interval -1 year)); Query OK, 1 row affected (0.11 sec) mysql> insert into BetweenDateDemo values(date_add(now(),interval -2 year)); Query OK, 1 row affected (0.13 sec) mysql> insert into BetweenDateDemo values(date_add(now(),interval -3 year)); Query OK, 1 row affected (0.13 sec) mysql> insert into BetweenDateDemo values(date_add(now(),interval 1 year)); Query OK, 1 row affected (0.12 sec) mysql> insert into BetweenDateDemo values(date_add(now(),interval 2 year)); Query OK, 1 row affected (0.12 sec) mysql> insert into BetweenDateDemo values(date_add(now(),interval 3 year)); Query OK, 1 row affected (0.16 sec) Now you can display all records from the table with the help of select statement. The query is as follows − mysql> select *from BetweenDateDemo; The following is the output − +---------------------+ | StartDate | +---------------------+ | 2017-12-08 11:45:47 | | 2016-12-08 11:45:56 | | 2015-12-08 11:46:01 | | 2019-12-08 11:46:05 | | 2020-12-08 11:46:11 | | 2021-12-08 11:46:15 | +---------------------+ 6 rows in set (0.00 sec) Now perform select between dates using the syntax discussed above − mysql> select *from BetweenDateDemo where StartDate between '2014-8-12' and curdate(); The following is the output − +---------------------+ | StartDate | +---------------------+ | 2017-12-08 11:45:47 | | 2016-12-08 11:45:56 | | 2015-12-08 11:46:01 | +---------------------+ 3 rows in set (0.00 sec) Use ORDER BY to get in a sorted order. The query is as follows − mysql> select *from BetweenDateDemo where StartDate between '2014-8-12' and curdate() order by StartDate; The following is the output − +---------------------+ | StartDate | +---------------------+ | 2015-12-08 11:46:01 | | 2016-12-08 11:45:56 | | 2017-12-08 11:45:47 | +---------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1153, "s": 1062, "text": "You can query between dates with the help of BETWEEN statement. The syntax is as follows −" }, { "code": null, "e": 1243, "s": 1153, "text": "select *from yourTableName where yourColumnName between ‘yourStartingDate’ and curdate()." }, { "code": null, "e": 1355, "s": 1243, "text": "Use curdate() or now(), both these functions will work. To understand the above syntax, let us create a table −" }, { "code": null, "e": 1470, "s": 1355, "text": "mysql> create table BetweenDateDemo\n −> (\n −> StartDate datetime\n −> );\nQuery OK, 0 rows affected (0.78 sec)" }, { "code": null, "e": 1542, "s": 1470, "text": "Insert some records in the table with the help of the following query −" }, { "code": null, "e": 2222, "s": 1542, "text": "mysql> insert into BetweenDateDemo values(date_add(now(),interval -1 year));\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into BetweenDateDemo values(date_add(now(),interval -2 year));\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into BetweenDateDemo values(date_add(now(),interval -3 year));\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into BetweenDateDemo values(date_add(now(),interval 1 year));\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into BetweenDateDemo values(date_add(now(),interval 2 year));\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into BetweenDateDemo values(date_add(now(),interval 3 year));\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2330, "s": 2222, "text": "Now you can display all records from the table with the help of select statement. The query is as follows −" }, { "code": null, "e": 2367, "s": 2330, "text": "mysql> select *from BetweenDateDemo;" }, { "code": null, "e": 2397, "s": 2367, "text": "The following is the output −" }, { "code": null, "e": 2662, "s": 2397, "text": "+---------------------+\n| StartDate |\n+---------------------+\n| 2017-12-08 11:45:47 |\n| 2016-12-08 11:45:56 |\n| 2015-12-08 11:46:01 |\n| 2019-12-08 11:46:05 |\n| 2020-12-08 11:46:11 |\n| 2021-12-08 11:46:15 |\n+---------------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2730, "s": 2662, "text": "Now perform select between dates using the syntax discussed above −" }, { "code": null, "e": 2817, "s": 2730, "text": "mysql> select *from BetweenDateDemo where StartDate between '2014-8-12' and curdate();" }, { "code": null, "e": 2847, "s": 2817, "text": "The following is the output −" }, { "code": null, "e": 3040, "s": 2847, "text": "+---------------------+\n| StartDate |\n+---------------------+\n| 2017-12-08 11:45:47 |\n| 2016-12-08 11:45:56 |\n| 2015-12-08 11:46:01 |\n+---------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 3105, "s": 3040, "text": "Use ORDER BY to get in a sorted order. The query is as follows −" }, { "code": null, "e": 3211, "s": 3105, "text": "mysql> select *from BetweenDateDemo where StartDate between '2014-8-12' and curdate() order by StartDate;" }, { "code": null, "e": 3241, "s": 3211, "text": "The following is the output −" }, { "code": null, "e": 3434, "s": 3241, "text": "+---------------------+\n| StartDate |\n+---------------------+\n| 2015-12-08 11:46:01 |\n| 2016-12-08 11:45:56 |\n| 2017-12-08 11:45:47 |\n+---------------------+\n3 rows in set (0.00 sec)" } ]
Hive - Create Table
This chapter explains how to create a table and how to insert data into it. The conventions of creating a table in HIVE is quite similar to creating a table using SQL. Create Table is a statement used to create a table in Hive. The syntax and example are as follows: CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS] [db_name.] table_name [(col_name data_type [COMMENT col_comment], ...)] [COMMENT table_comment] [ROW FORMAT row_format] [STORED AS file_format] Let us assume you need to create a table named employee using CREATE TABLE statement. The following table lists the fields and their data types in employee table: The following data is a Comment, Row formatted fields such as Field terminator, Lines terminator, and Stored File type. COMMENT ‘Employee details’ FIELDS TERMINATED BY ‘\t’ LINES TERMINATED BY ‘\n’ STORED IN TEXT FILE The following query creates a table named employee using the above data. hive> CREATE TABLE IF NOT EXISTS employee ( eid int, name String, salary String, destination String) COMMENT ‘Employee details’ ROW FORMAT DELIMITED FIELDS TERMINATED BY ‘\t’ LINES TERMINATED BY ‘\n’ STORED AS TEXTFILE; If you add the option IF NOT EXISTS, Hive ignores the statement in case the table already exists. On successful creation of table, you get to see the following response: OK Time taken: 5.905 seconds hive> The JDBC program to create a table is given example. import java.sql.SQLException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.DriverManager; public class HiveCreateTable { private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver"; public static void main(String[] args) throws SQLException { // Register driver and create driver instance Class.forName(driverName); // get connection Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/userdb", "", ""); // create statement Statement stmt = con.createStatement(); // execute statement stmt.executeQuery("CREATE TABLE IF NOT EXISTS " +" employee ( eid int, name String, " +" salary String, destignation String)" +" COMMENT ‘Employee details’" +" ROW FORMAT DELIMITED" +" FIELDS TERMINATED BY ‘\t’" +" LINES TERMINATED BY ‘\n’" +" STORED AS TEXTFILE;"); System.out.println(“ Table employee created.”); con.close(); } } Save the program in a file named HiveCreateDb.java. The following commands are used to compile and execute this program. $ javac HiveCreateDb.java $ java HiveCreateDb Table employee created. Generally, after creating a table in SQL, we can insert data using the Insert statement. But in Hive, we can insert data using the LOAD DATA statement. While inserting data into Hive, it is better to use LOAD DATA to store bulk records. There are two ways to load data: one is from local file system and second is from Hadoop file system. The syntax for load data is as follows: LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename [PARTITION (partcol1=val1, partcol2=val2 ...)] LOCAL is identifier to specify the local path. It is optional. OVERWRITE is optional to overwrite the data in the table. PARTITION is optional. We will insert the following data into the table. It is a text file named sample.txt in /home/user directory. 1201 Gopal 45000 Technical manager 1202 Manisha 45000 Proof reader 1203 Masthanvali 40000 Technical writer 1204 Kiran 40000 Hr Admin 1205 Kranthi 30000 Op Admin The following query loads the given text into the table. hive> LOAD DATA LOCAL INPATH '/home/user/sample.txt' OVERWRITE INTO TABLE employee; On successful download, you get to see the following response: OK Time taken: 15.905 seconds hive> Given below is the JDBC program to load given data into the table. import java.sql.SQLException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.DriverManager; public class HiveLoadData { private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver"; public static void main(String[] args) throws SQLException { // Register driver and create driver instance Class.forName(driverName); // get connection Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/userdb", "", ""); // create statement Statement stmt = con.createStatement(); // execute statement stmt.executeQuery("LOAD DATA LOCAL INPATH '/home/user/sample.txt'" + "OVERWRITE INTO TABLE employee;"); System.out.println("Load Data into employee successful"); con.close(); } } Save the program in a file named HiveLoadData.java. Use the following commands to compile and execute this program. $ javac HiveLoadData.java $ java HiveLoadData Load Data into employee successful 50 Lectures 4 hours Navdeep Kaur 67 Lectures 4 hours Bigdata Engineer 109 Lectures 2 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2118, "s": 1950, "text": "This chapter explains how to create a table and how to insert data into it. The conventions of creating a table in HIVE is quite similar to creating a table using SQL." }, { "code": null, "e": 2217, "s": 2118, "text": "Create Table is a statement used to create a table in Hive. The syntax and example are as follows:" }, { "code": null, "e": 2414, "s": 2217, "text": "CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS] [db_name.] table_name\n\n[(col_name data_type [COMMENT col_comment], ...)]\n[COMMENT table_comment]\n[ROW FORMAT row_format]\n[STORED AS file_format]" }, { "code": null, "e": 2577, "s": 2414, "text": "Let us assume you need to create a table named employee using CREATE TABLE statement. The following table lists the fields and their data types in employee table:" }, { "code": null, "e": 2697, "s": 2577, "text": "The following data is a Comment, Row formatted fields such as Field terminator, Lines terminator, and Stored File type." }, { "code": null, "e": 2796, "s": 2697, "text": "COMMENT ‘Employee details’\nFIELDS TERMINATED BY ‘\\t’\nLINES TERMINATED BY ‘\\n’\nSTORED IN TEXT FILE\n" }, { "code": null, "e": 2869, "s": 2796, "text": "The following query creates a table named employee using the above data." }, { "code": null, "e": 3090, "s": 2869, "text": "hive> CREATE TABLE IF NOT EXISTS employee ( eid int, name String,\nsalary String, destination String)\nCOMMENT ‘Employee details’\nROW FORMAT DELIMITED\nFIELDS TERMINATED BY ‘\\t’\nLINES TERMINATED BY ‘\\n’\nSTORED AS TEXTFILE;\n" }, { "code": null, "e": 3188, "s": 3090, "text": "If you add the option IF NOT EXISTS, Hive ignores the statement in case the table already exists." }, { "code": null, "e": 3260, "s": 3188, "text": "On successful creation of table, you get to see the following response:" }, { "code": null, "e": 3296, "s": 3260, "text": "OK\nTime taken: 5.905 seconds\nhive>\n" }, { "code": null, "e": 3349, "s": 3296, "text": "The JDBC program to create a table is given example." }, { "code": null, "e": 4429, "s": 3349, "text": "import java.sql.SQLException;\nimport java.sql.Connection;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport java.sql.DriverManager;\n\npublic class HiveCreateTable {\n private static String driverName = \"org.apache.hadoop.hive.jdbc.HiveDriver\";\n \n public static void main(String[] args) throws SQLException {\n \n // Register driver and create driver instance\n Class.forName(driverName);\n \n // get connection\n Connection con = DriverManager.getConnection(\"jdbc:hive://localhost:10000/userdb\", \"\", \"\");\n \n // create statement\n Statement stmt = con.createStatement();\n \n // execute statement\n stmt.executeQuery(\"CREATE TABLE IF NOT EXISTS \"\n +\" employee ( eid int, name String, \"\n +\" salary String, destignation String)\"\n +\" COMMENT ‘Employee details’\"\n +\" ROW FORMAT DELIMITED\"\n +\" FIELDS TERMINATED BY ‘\\t’\"\n +\" LINES TERMINATED BY ‘\\n’\"\n +\" STORED AS TEXTFILE;\");\n \n System.out.println(“ Table employee created.”);\n con.close();\n }\n}" }, { "code": null, "e": 4550, "s": 4429, "text": "Save the program in a file named HiveCreateDb.java. The following commands are used to compile and execute this program." }, { "code": null, "e": 4597, "s": 4550, "text": "$ javac HiveCreateDb.java\n$ java HiveCreateDb\n" }, { "code": null, "e": 4622, "s": 4597, "text": "Table employee created.\n" }, { "code": null, "e": 4774, "s": 4622, "text": "Generally, after creating a table in SQL, we can insert data using the Insert statement. But in Hive, we can insert data using the LOAD DATA statement." }, { "code": null, "e": 4961, "s": 4774, "text": "While inserting data into Hive, it is better to use LOAD DATA to store bulk records. There are two ways to load data: one is from local file system and second is from Hadoop file system." }, { "code": null, "e": 5001, "s": 4961, "text": "The syntax for load data is as follows:" }, { "code": null, "e": 5119, "s": 5001, "text": "LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename \n[PARTITION (partcol1=val1, partcol2=val2 ...)]\n" }, { "code": null, "e": 5182, "s": 5119, "text": "LOCAL is identifier to specify the local path. It is optional." }, { "code": null, "e": 5240, "s": 5182, "text": "OVERWRITE is optional to overwrite the data in the table." }, { "code": null, "e": 5263, "s": 5240, "text": "PARTITION is optional." }, { "code": null, "e": 5373, "s": 5263, "text": "We will insert the following data into the table. It is a text file named sample.txt in /home/user directory." }, { "code": null, "e": 5575, "s": 5373, "text": "1201 Gopal 45000 Technical manager\n1202 Manisha 45000 Proof reader\n1203 Masthanvali 40000 Technical writer\n1204 Kiran 40000 Hr Admin\n1205 Kranthi 30000 Op Admin\n" }, { "code": null, "e": 5632, "s": 5575, "text": "The following query loads the given text into the table." }, { "code": null, "e": 5717, "s": 5632, "text": "hive> LOAD DATA LOCAL INPATH '/home/user/sample.txt'\nOVERWRITE INTO TABLE employee;\n" }, { "code": null, "e": 5780, "s": 5717, "text": "On successful download, you get to see the following response:" }, { "code": null, "e": 5817, "s": 5780, "text": "OK\nTime taken: 15.905 seconds\nhive>\n" }, { "code": null, "e": 5884, "s": 5817, "text": "Given below is the JDBC program to load given data into the table." }, { "code": null, "e": 6743, "s": 5884, "text": "import java.sql.SQLException;\nimport java.sql.Connection;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport java.sql.DriverManager;\n\npublic class HiveLoadData {\n\n private static String driverName = \"org.apache.hadoop.hive.jdbc.HiveDriver\";\n \n public static void main(String[] args) throws SQLException {\n \n // Register driver and create driver instance\n Class.forName(driverName);\n \n // get connection\n Connection con = DriverManager.getConnection(\"jdbc:hive://localhost:10000/userdb\", \"\", \"\");\n \n // create statement\n Statement stmt = con.createStatement();\n \n // execute statement\n stmt.executeQuery(\"LOAD DATA LOCAL INPATH '/home/user/sample.txt'\" + \"OVERWRITE INTO TABLE employee;\");\n System.out.println(\"Load Data into employee successful\");\n \n con.close();\n }\n}" }, { "code": null, "e": 6859, "s": 6743, "text": "Save the program in a file named HiveLoadData.java. Use the following commands to compile and execute this program." }, { "code": null, "e": 6906, "s": 6859, "text": "$ javac HiveLoadData.java\n$ java HiveLoadData\n" }, { "code": null, "e": 6942, "s": 6906, "text": "Load Data into employee successful\n" }, { "code": null, "e": 6975, "s": 6942, "text": "\n 50 Lectures \n 4 hours \n" }, { "code": null, "e": 6989, "s": 6975, "text": " Navdeep Kaur" }, { "code": null, "e": 7022, "s": 6989, "text": "\n 67 Lectures \n 4 hours \n" }, { "code": null, "e": 7040, "s": 7022, "text": " Bigdata Engineer" }, { "code": null, "e": 7074, "s": 7040, "text": "\n 109 Lectures \n 2 hours \n" }, { "code": null, "e": 7092, "s": 7074, "text": " Bigdata Engineer" }, { "code": null, "e": 7099, "s": 7092, "text": " Print" }, { "code": null, "e": 7110, "s": 7099, "text": " Add Notes" } ]
MYBATIS - Read Operation
We discussed in the last chapter, how to insert values into the STUDENT table using MyBatis by performing CREATE operation. This chapter explains how to read the data in a table using MyBatis. We have the following STUDENT table in MySQL − CREATE TABLE details.student( ID int(10) NOT NULL AUTO_INCREMENT, NAME varchar(100) NOT NULL, BRANCH varchar(255) NOT NULL, PERCENTAGE int(3) NOT NULL, PHONE int(11) NOT NULL, EMAIL varchar(255) NOT NULL, PRIMARY KEY (`ID`) ); Assume, this table has two record as − +----+----------+--------+------------+-----------+--------------------+ | ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL | +----+----------+--------+------------+-----------+--------------------+ | 1 | Mohammad | It | 80 | 984803322 | [email protected] | | 2 | shyam | It | 75 | 984800000 | [email protected] | +----+----------+--------+------------+-----------+--------------------+ To perform read operation, we would modify the Student class in Student.java as − public class Student { private int id; private String name; private String branch; private int percentage; private int phone; private String email; public Student(int id, String name, String branch, int percentage, int phone, String email) { super(); this.id = id; this.name = name; this.branch = branch; this.percentage = percentage; this.phone = phone; this.email = email; } public Student() {} public int getId() { return id; } public String getName() { return name; } public int getPhone() { return phone; } public String getEmail() { return email; } public String getBranch() { return branch; } public int getPercentage() { return percentage; } } To define SQL mapping statement using MyBatis, we would add <select> tag in Student.xml file and inside this tag definition, we would define an "id" which will be used in mybatisRead.java file for executing SQL SELECT query on database. While reading the records, we can get all the records at once or we can get a particular record using the where clause. In the XML given below, you can observe both the queries. To retrieve a particular record, we need a unique key to represent that record. Therefore, we have also defined the resultmap "id" (unique key) of type Student to map the result of the select query with the variable of Student class. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace = "Student"> <resultMap id = "result" type = "Student"> <result property = "id" column = "ID"/> </resultMap> <select id = "getAll" resultMap = "result"> SELECT * FROM STUDENT; </select> <select id = "getById" parameterType = "int" resultMap = "result"> SELECT * FROM STUDENT WHERE ID = #{id}; </select> </mapper> This file has application level logic to read all the records from the Student table. Create and save mybatisRead_ALL.java file as shown below − import java.io.IOException; import java.io.Reader; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class mybatisRead_ALL { public static void main(String args[]) throws IOException{ Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); //select contact all contacts List<Student> student = session.selectList("Student.getAll"); for(Student st : student ){ System.out.println(st.getId()); System.out.println(st.getName()); System.out.println(st.getBranch()); System.out.println(st.getPercentage()); System.out.println(st.getEmail()); System.out.println(st.getPhone()); } System.out.println("Records Read Successfully "); session.commit(); session.close(); } } Here are the steps to compile and run the mybatisRead_ALL file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student.xml as shown above. Create Student.java as shown above and compile it. Create mybatisRead_ALL.java as shown above and compile it. Execute mybatisRead_ALL binary to run the program. You would get all the record of the student table as − ++++++++++++++ details of the student who's id is :1 +++++++++++++++++++ 1 Mohammad It 80 [email protected] 984803322 ++++++++++++++ details of the student who's id is :2 +++++++++++++++++++ 2 shyam It 75 [email protected] 984800000 Records Read Successfully Copy and save the following program with the name mybatisRead_byID − import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class mybatisRead_byID { public static void main(String args[]) throws IOException{ int i = 1; Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); SqlSession session = sqlSessionFactory.openSession(); //select a particular student by id Student student = (Student) session.selectOne("Student.getById", 2); //Print the student details System.out.println(student.getId()); System.out.println(student.getName()); System.out.println(student.getBranch()); System.out.println(student.getPercentage()); System.out.println(student.getEmail()); System.out.println(student.getPhone()); session.commit(); session.close(); } } Here are the steps to compile and run the mybatisRead_byID file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution. Create Student.xml as shown above. Create Student.xml as shown above. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial. Create Student.java as shown above and compile it. Create Student.java as shown above and compile it. Create mybatisRead_byID.java as shown above and compile it. Create mybatisRead_byID.java as shown above and compile it. Execute mybatisRead_byID binary to run the program. Execute mybatisRead_byID binary to run the program. You would get the following result, and a record would be read from the Student table as − 2 shyam It 75 [email protected] 984800000 Print Add Notes Bookmark this page
[ { "code": null, "e": 2064, "s": 1871, "text": "We discussed in the last chapter, how to insert values into the STUDENT table using MyBatis by performing CREATE operation. This chapter explains how to read the data in a table using MyBatis." }, { "code": null, "e": 2111, "s": 2064, "text": "We have the following STUDENT table in MySQL −" }, { "code": null, "e": 2360, "s": 2111, "text": "CREATE TABLE details.student(\n ID int(10) NOT NULL AUTO_INCREMENT,\n NAME varchar(100) NOT NULL,\n BRANCH varchar(255) NOT NULL,\n PERCENTAGE int(3) NOT NULL,\n PHONE int(11) NOT NULL,\n EMAIL varchar(255) NOT NULL,\n PRIMARY KEY (`ID`)\n);\n" }, { "code": null, "e": 2399, "s": 2360, "text": "Assume, this table has two record as −" }, { "code": null, "e": 2838, "s": 2399, "text": "+----+----------+--------+------------+-----------+--------------------+\n| ID | NAME | BRANCH | PERCENTAGE | PHONE | EMAIL |\n+----+----------+--------+------------+-----------+--------------------+\n| 1 | Mohammad | It | 80 | 984803322 | [email protected] |\n| 2 | shyam | It | 75 | 984800000 | [email protected] |\n+----+----------+--------+------------+-----------+--------------------+\n" }, { "code": null, "e": 2920, "s": 2838, "text": "To perform read operation, we would modify the Student class in Student.java as −" }, { "code": null, "e": 3732, "s": 2920, "text": "public class Student {\n private int id;\n private String name;\n private String branch;\n private int percentage;\n private int phone;\n private String email;\n\n public Student(int id, String name, String branch, int percentage, int phone, String email) {\n super();\n this.id = id;\n this.name = name;\n this.branch = branch;\n this.percentage = percentage;\n this.phone = phone;\n this.email = email;\n }\n\t\n public Student() {}\n\n public int getId() {\n return id;\n }\n\t\t\n public String getName() {\n return name;\n }\n\t\n public int getPhone() {\n return phone;\n }\n\t\n public String getEmail() {\n return email;\n }\n \n public String getBranch() {\n return branch;\n }\n\n public int getPercentage() {\n return percentage;\n }\t\n\t\n}" }, { "code": null, "e": 4148, "s": 3732, "text": "To define SQL mapping statement using MyBatis, we would add <select> tag in Student.xml file and inside this tag definition, we would define an \"id\" which will be used in mybatisRead.java file for executing SQL SELECT query on database. While reading the records, we can get all the records at once or we can get a particular record using the where clause. In the XML given below, you can observe both the queries." }, { "code": null, "e": 4382, "s": 4148, "text": "To retrieve a particular record, we need a unique key to represent that record. Therefore, we have also defined the resultmap \"id\" (unique key) of type Student to map the result of the select query with the variable of Student class." }, { "code": null, "e": 4924, "s": 4382, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n\t\n<mapper namespace = \"Student\">\t\n\n <resultMap id = \"result\" type = \"Student\">\n <result property = \"id\" column = \"ID\"/>\t \n </resultMap>\n\t\n <select id = \"getAll\" resultMap = \"result\">\n SELECT * FROM STUDENT; \n </select>\n \n <select id = \"getById\" parameterType = \"int\" resultMap = \"result\">\n SELECT * FROM STUDENT WHERE ID = #{id};\n </select>\n \t\n</mapper>" }, { "code": null, "e": 5069, "s": 4924, "text": "This file has application level logic to read all the records from the Student table. Create and save mybatisRead_ALL.java file as shown below −" }, { "code": null, "e": 6252, "s": 5069, "text": "import java.io.IOException;\nimport java.io.Reader;\nimport java.util.List;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class mybatisRead_ALL { \n\n public static void main(String args[]) throws IOException{\n\n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession();\n \n //select contact all contacts\t\t\n List<Student> student = session.selectList(\"Student.getAll\");\n \n for(Student st : student ){ \t \n System.out.println(st.getId());\n System.out.println(st.getName());\n System.out.println(st.getBranch());\n System.out.println(st.getPercentage()); \n System.out.println(st.getEmail()); \n System.out.println(st.getPhone()); \n } \n\t\t\n System.out.println(\"Records Read Successfully \"); \n session.commit(); \n session.close();\t\t\t\n }\n} " }, { "code": null, "e": 6422, "s": 6252, "text": "Here are the steps to compile and run the mybatisRead_ALL file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 6457, "s": 6422, "text": "Create Student.xml as shown above." }, { "code": null, "e": 6508, "s": 6457, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 6567, "s": 6508, "text": "Create mybatisRead_ALL.java as shown above and compile it." }, { "code": null, "e": 6618, "s": 6567, "text": "Execute mybatisRead_ALL binary to run the program." }, { "code": null, "e": 6673, "s": 6618, "text": "You would get all the record of the student table as −" }, { "code": null, "e": 6935, "s": 6673, "text": "++++++++++++++ details of the student who's id is :1 +++++++++++++++++++\n1\nMohammad\nIt\n80\[email protected]\n984803322\n++++++++++++++ details of the student who's id is :2\n+++++++++++++++++++\n2\nshyam\nIt\n75\[email protected]\n984800000\nRecords Read Successfully \n" }, { "code": null, "e": 7004, "s": 6935, "text": "Copy and save the following program with the name mybatisRead_byID −" }, { "code": null, "e": 8121, "s": 7004, "text": "import java.io.IOException;\nimport java.io.Reader;\n\nimport org.apache.ibatis.io.Resources;\nimport org.apache.ibatis.session.SqlSession;\nimport org.apache.ibatis.session.SqlSessionFactory;\nimport org.apache.ibatis.session.SqlSessionFactoryBuilder;\n\npublic class mybatisRead_byID { \n\n public static void main(String args[]) throws IOException{\n \n int i = 1;\n Reader reader = Resources.getResourceAsReader(\"SqlMapConfig.xml\");\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);\t\t\n SqlSession session = sqlSessionFactory.openSession(); \n\t \n //select a particular student by id\t\n Student student = (Student) session.selectOne(\"Student.getById\", 2); \n\t \n //Print the student details\n System.out.println(student.getId());\n System.out.println(student.getName());\n System.out.println(student.getBranch());\n System.out.println(student.getPercentage()); \n System.out.println(student.getEmail()); \n System.out.println(student.getPhone());\n\t\t\n session.commit();\n session.close();\n\t\t\t\n }\n \n}" }, { "code": null, "e": 8292, "s": 8121, "text": "Here are the steps to compile and run the mybatisRead_byID file. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for compilation and execution." }, { "code": null, "e": 8327, "s": 8292, "text": "Create Student.xml as shown above." }, { "code": null, "e": 8362, "s": 8327, "text": "Create Student.xml as shown above." }, { "code": null, "e": 8456, "s": 8362, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 8550, "s": 8456, "text": "Create SqlMapConfig.xml as shown in the MYBATIS - Configuration XML chapter of this tutorial." }, { "code": null, "e": 8601, "s": 8550, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 8652, "s": 8601, "text": "Create Student.java as shown above and compile it." }, { "code": null, "e": 8712, "s": 8652, "text": "Create mybatisRead_byID.java as shown above and compile it." }, { "code": null, "e": 8772, "s": 8712, "text": "Create mybatisRead_byID.java as shown above and compile it." }, { "code": null, "e": 8824, "s": 8772, "text": "Execute mybatisRead_byID binary to run the program." }, { "code": null, "e": 8876, "s": 8824, "text": "Execute mybatisRead_byID binary to run the program." }, { "code": null, "e": 8967, "s": 8876, "text": "You would get the following result, and a record would be read from the Student table as −" }, { "code": null, "e": 9008, "s": 8967, "text": "2\nshyam\nIt\n75\[email protected]\n984800000\n" }, { "code": null, "e": 9015, "s": 9008, "text": " Print" }, { "code": null, "e": 9026, "s": 9015, "text": " Add Notes" } ]
Find the winner of the game - GeeksforGeeks
19 Jan, 2022 Two players are playing a game where a string str is given. The first player can take the characters at even indices and the second player can take the characters at odd indices. The player which can build the lexicographically smaller string than the other player wins the game. Print the winner of the game, either player A, B or print Tie if its a tie.Examples: Input: str = “geeksforgeeks” Output: B “eeggoss” is the lexicographically smallest string that player A can get. “eefkkr” is the lexicographically smallest string that player B can get. And B’s string is lexicographically smaller.Input: str = “abcdbh” Output: A Approach: Create two empty strings str1 and str2 for player A and B respectively. Traverse the original string character by character and for every character whose index is even, append this character in str1 else append this character in str2. Finally sort the generated string in order to get the lexicographically smallest possible string and compare them to find the winner of the game.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 to find the winner of the gamevoid find_winner(string str, int n){ // To store the strings for both the players string str1 = "", str2 = ""; for (int i = 0; i < n; i++) { // If the index is even if (i % 2 == 0) { // Append the current character // to player A's string str1 += str[i]; } // If the index is odd else { // Append the current character // to player B's string str2 += str[i]; } } // Sort both the strings to get // the lexicographically smallest // string possible sort(str1.begin(), str1.end()); sort(str2.begin(), str2.end()); // Compare both the strings to // find the winner of the game if (str1 < str2) cout << "A"; else if (str2 < str1) cout << "B"; else cout << "Tie";} // Driver codeint main(){ string str = "geeksforgeeks"; int n = str.length(); find_winner(str, n); return 0;} // Java implementation of the approachimport java.util.Arrays; class GFG{ // Function to find the winner of the gamestatic void find_winner(String str, int n){ // To store the strings for both the players String str1 = "", str2 = ""; for (int i = 0; i < n; i++) { // If the index is even if (i % 2 == 0) { // Append the current character // to player A's string str1 += str.charAt(i); } // If the index is odd else { // Append the current character // to player B's string str2 += str.charAt(i); } } // Sort both the strings to get // the lexicographically smallest // string possible char a[] = str1.toCharArray(); Arrays.sort(a); char b[] = str2.toCharArray(); Arrays.sort(b); str1 = new String(a); str2 = new String(b); // Compare both the strings to // find the winner of the game if (str1.compareTo(str2) < 0) System.out.print("A"); else if (str1.compareTo(str2) > 0) System.out.print("B"); else System.out.print("Tie");} // Driver codepublic static void main(String[] args){ String str = "geeksforgeeks"; int n = str.length(); find_winner(str, n);}} // This code is contributed by Rajput-Ji # Python3 implementation of the approach # Function to find the winner of the gamedef find_winner(string, n) : # To store the strings for both the players string1= ""; string2 = ""; for i in range(n) : # If the index is even if (i % 2 == 0) : # Append the current character # to player A's string string1 += string[i]; # If the index is odd else : # Append the current character # to player B's string string2 += string[i]; # Sort both the strings to get # the lexicographically smallest # string possible string1 = "".join(sorted(string1)) string2 = "".join(sorted(string2)) # Compare both the strings to # find the winner of the game if (string1 < string2) : print("A", end = ""); elif (string2 < string1) : print("B", end = ""); else : print("Tie", end = ""); # Driver codeif __name__ == "__main__" : string = "geeksforgeeks"; n = len(string); find_winner(string, n); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // Function to find the winner of the gamestatic void find_winner(String str, int n){ // To store the strings for both the players String str1 = "", str2 = ""; for (int i = 0; i < n; i++) { // If the index is even if (i % 2 == 0) { // Append the current character // to player A's string str1 += str[i]; } // If the index is odd else { // Append the current character // to player B's string str2 += str[i]; } } // Sort both the strings to get // the lexicographically smallest // string possible char []a = str1.ToCharArray(); Array.Sort(a); char []b = str2.ToCharArray(); Array.Sort(b); str1 = new String(a); str2 = new String(b); // Compare both the strings to // find the winner of the game if (str1.CompareTo(str2) < 0) Console.Write("A"); else if (str1.CompareTo(str2) > 0) Console.Write("B"); else Console.Write("Tie");} // Driver codepublic static void Main(String[] args){ String str = "geeksforgeeks"; int n = str.Length; find_winner(str, n);}} // This code is contributed by Rajput-Ji <script> // Javascript implementation of the approach // Function to find the winner of the gamefunction find_winner(str, n){ // To store the strings for both the players var str1 = "", str2 = ""; for (var i = 0; i < n; i++) { // If the index is even if (i % 2 == 0) { // Append the current character // to player A's string str1 += str[i]; } // If the index is odd else { // Append the current character // to player B's string str2 += str[i]; } } // Sort both the strings to get // the lexicographically smallest // string possible str1 = str1.split('').sort(); str2 = str2.split('').sort(); // Compare both the strings to // find the winner of the game if (str1 < str2) document.write( "A"); else if (str2 < str1) document.write( "B"); else document.write( "Tie");} // Driver codevar str = "geeksforgeeks";var n = str.length;find_winner(str, n); </script> B ankthon Rajput-Ji rutvik_56 surinderdawra388 varshagumber28 lexicographic-ordering Strings 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++ KMP Algorithm for Pattern Searching Check for Balanced Brackets in an expression (well-formedness) using Stack Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Reverse words in a given string Array of Strings in C++ (5 Different Ways to Create) Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 24938, "s": 24910, "text": "\n19 Jan, 2022" }, { "code": null, "e": 25305, "s": 24938, "text": "Two players are playing a game where a string str is given. The first player can take the characters at even indices and the second player can take the characters at odd indices. The player which can build the lexicographically smaller string than the other player wins the game. Print the winner of the game, either player A, B or print Tie if its a tie.Examples: " }, { "code": null, "e": 25569, "s": 25305, "text": "Input: str = “geeksforgeeks” Output: B “eeggoss” is the lexicographically smallest string that player A can get. “eefkkr” is the lexicographically smallest string that player B can get. And B’s string is lexicographically smaller.Input: str = “abcdbh” Output: A " }, { "code": null, "e": 26014, "s": 25571, "text": "Approach: Create two empty strings str1 and str2 for player A and B respectively. Traverse the original string character by character and for every character whose index is even, append this character in str1 else append this character in str2. Finally sort the generated string in order to get the lexicographically smallest possible string and compare them to find the winner of the game.Below is the implementation of the above approach: " }, { "code": null, "e": 26018, "s": 26014, "text": "C++" }, { "code": null, "e": 26023, "s": 26018, "text": "Java" }, { "code": null, "e": 26031, "s": 26023, "text": "Python3" }, { "code": null, "e": 26034, "s": 26031, "text": "C#" }, { "code": null, "e": 26045, "s": 26034, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the winner of the gamevoid find_winner(string str, int n){ // To store the strings for both the players string str1 = \"\", str2 = \"\"; for (int i = 0; i < n; i++) { // If the index is even if (i % 2 == 0) { // Append the current character // to player A's string str1 += str[i]; } // If the index is odd else { // Append the current character // to player B's string str2 += str[i]; } } // Sort both the strings to get // the lexicographically smallest // string possible sort(str1.begin(), str1.end()); sort(str2.begin(), str2.end()); // Compare both the strings to // find the winner of the game if (str1 < str2) cout << \"A\"; else if (str2 < str1) cout << \"B\"; else cout << \"Tie\";} // Driver codeint main(){ string str = \"geeksforgeeks\"; int n = str.length(); find_winner(str, n); return 0;}", "e": 27131, "s": 26045, "text": null }, { "code": "// Java implementation of the approachimport java.util.Arrays; class GFG{ // Function to find the winner of the gamestatic void find_winner(String str, int n){ // To store the strings for both the players String str1 = \"\", str2 = \"\"; for (int i = 0; i < n; i++) { // If the index is even if (i % 2 == 0) { // Append the current character // to player A's string str1 += str.charAt(i); } // If the index is odd else { // Append the current character // to player B's string str2 += str.charAt(i); } } // Sort both the strings to get // the lexicographically smallest // string possible char a[] = str1.toCharArray(); Arrays.sort(a); char b[] = str2.toCharArray(); Arrays.sort(b); str1 = new String(a); str2 = new String(b); // Compare both the strings to // find the winner of the game if (str1.compareTo(str2) < 0) System.out.print(\"A\"); else if (str1.compareTo(str2) > 0) System.out.print(\"B\"); else System.out.print(\"Tie\");} // Driver codepublic static void main(String[] args){ String str = \"geeksforgeeks\"; int n = str.length(); find_winner(str, n);}} // This code is contributed by Rajput-Ji", "e": 28445, "s": 27131, "text": null }, { "code": "# Python3 implementation of the approach # Function to find the winner of the gamedef find_winner(string, n) : # To store the strings for both the players string1= \"\"; string2 = \"\"; for i in range(n) : # If the index is even if (i % 2 == 0) : # Append the current character # to player A's string string1 += string[i]; # If the index is odd else : # Append the current character # to player B's string string2 += string[i]; # Sort both the strings to get # the lexicographically smallest # string possible string1 = \"\".join(sorted(string1)) string2 = \"\".join(sorted(string2)) # Compare both the strings to # find the winner of the game if (string1 < string2) : print(\"A\", end = \"\"); elif (string2 < string1) : print(\"B\", end = \"\"); else : print(\"Tie\", end = \"\"); # Driver codeif __name__ == \"__main__\" : string = \"geeksforgeeks\"; n = len(string); find_winner(string, n); # This code is contributed by AnkitRai01", "e": 29583, "s": 28445, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to find the winner of the gamestatic void find_winner(String str, int n){ // To store the strings for both the players String str1 = \"\", str2 = \"\"; for (int i = 0; i < n; i++) { // If the index is even if (i % 2 == 0) { // Append the current character // to player A's string str1 += str[i]; } // If the index is odd else { // Append the current character // to player B's string str2 += str[i]; } } // Sort both the strings to get // the lexicographically smallest // string possible char []a = str1.ToCharArray(); Array.Sort(a); char []b = str2.ToCharArray(); Array.Sort(b); str1 = new String(a); str2 = new String(b); // Compare both the strings to // find the winner of the game if (str1.CompareTo(str2) < 0) Console.Write(\"A\"); else if (str1.CompareTo(str2) > 0) Console.Write(\"B\"); else Console.Write(\"Tie\");} // Driver codepublic static void Main(String[] args){ String str = \"geeksforgeeks\"; int n = str.Length; find_winner(str, n);}} // This code is contributed by Rajput-Ji", "e": 30857, "s": 29583, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to find the winner of the gamefunction find_winner(str, n){ // To store the strings for both the players var str1 = \"\", str2 = \"\"; for (var i = 0; i < n; i++) { // If the index is even if (i % 2 == 0) { // Append the current character // to player A's string str1 += str[i]; } // If the index is odd else { // Append the current character // to player B's string str2 += str[i]; } } // Sort both the strings to get // the lexicographically smallest // string possible str1 = str1.split('').sort(); str2 = str2.split('').sort(); // Compare both the strings to // find the winner of the game if (str1 < str2) document.write( \"A\"); else if (str2 < str1) document.write( \"B\"); else document.write( \"Tie\");} // Driver codevar str = \"geeksforgeeks\";var n = str.length;find_winner(str, n); </script>", "e": 31894, "s": 30857, "text": null }, { "code": null, "e": 31896, "s": 31894, "text": "B" }, { "code": null, "e": 31906, "s": 31898, "text": "ankthon" }, { "code": null, "e": 31916, "s": 31906, "text": "Rajput-Ji" }, { "code": null, "e": 31926, "s": 31916, "text": "rutvik_56" }, { "code": null, "e": 31943, "s": 31926, "text": "surinderdawra388" }, { "code": null, "e": 31958, "s": 31943, "text": "varshagumber28" }, { "code": null, "e": 31981, "s": 31958, "text": "lexicographic-ordering" }, { "code": null, "e": 31989, "s": 31981, "text": "Strings" }, { "code": null, "e": 31997, "s": 31989, "text": "Strings" }, { "code": null, "e": 32095, "s": 31997, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32104, "s": 32095, "text": "Comments" }, { "code": null, "e": 32117, "s": 32104, "text": "Old Comments" }, { "code": null, "e": 32174, "s": 32117, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 32221, "s": 32174, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 32257, "s": 32221, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 32332, "s": 32257, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 32368, "s": 32332, "text": "Convert string to char array in C++" }, { "code": null, "e": 32406, "s": 32368, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 32436, "s": 32406, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 32468, "s": 32436, "text": "Reverse words in a given string" }, { "code": null, "e": 32521, "s": 32468, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
Kubernetes - Secrets
Secrets can be defined as Kubernetes objects used to store sensitive data such as user name and passwords with encryption. There are multiple ways of creating secrets in Kubernetes. Creating from txt files. Creating from yaml file. In order to create secrets from a text file such as user name and password, we first need to store them in a txt file and use the following command. $ kubectl create secret generic tomcat-passwd –-from-file = ./username.txt –fromfile = ./. password.txt apiVersion: v1 kind: Secret metadata: name: tomcat-pass type: Opaque data: password: <User Password> username: <User Name> $ kubectl create –f Secret.yaml secrets/tomcat-pass Once we have created the secrets, it can be consumed in a pod or the replication controller as − Environment Variable Volume In order to use the secret as environment variable, we will use env under the spec section of pod yaml file. env: - name: SECRET_USERNAME valueFrom: secretKeyRef: name: mysecret key: tomcat-pass spec: volumes: - name: "secretstest" secret: secretName: tomcat-pass containers: - image: tomcat:7.0 name: awebserver volumeMounts: - mountPath: "/tmp/mysec" name: "secretstest" apiVersion: v1 kind: ReplicationController metadata: name: appname spec: replicas: replica_count template: metadata: name: appname spec: nodeSelector: resource-group: containers: - name: appname image: imagePullPolicy: Always ports: - containerPort: 3000 env: -----------------------------> 1 - name: ENV valueFrom: configMapKeyRef: name: appname key: tomcat-secrets In the above code, under the env definition, we are using secrets as environment variable in the replication controller. apiVersion: v1 kind: pod metadata: name: appname spec: metadata: name: appname spec: volumes: - name: "secretstest" secret: secretName: tomcat-pass containers: - image: tomcat: 8.0 name: awebserver volumeMounts: - mountPath: "/tmp/mysec" name: "secretstest" 41 Lectures 5 hours AR Shankar 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 18 Lectures 1.5 hours Nigel Poulton 25 Lectures 1.5 hours Pranjal Srivastava 18 Lectures 1 hours Pranjal Srivastava 26 Lectures 1.5 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2318, "s": 2195, "text": "Secrets can be defined as Kubernetes objects used to store sensitive data such as user name and passwords with encryption." }, { "code": null, "e": 2377, "s": 2318, "text": "There are multiple ways of creating secrets in Kubernetes." }, { "code": null, "e": 2402, "s": 2377, "text": "Creating from txt files." }, { "code": null, "e": 2427, "s": 2402, "text": "Creating from yaml file." }, { "code": null, "e": 2576, "s": 2427, "text": "In order to create secrets from a text file such as user name and password, we first need to store them in a txt file and use the following command." }, { "code": null, "e": 2681, "s": 2576, "text": "$ kubectl create secret generic tomcat-passwd –-from-file = ./username.txt –fromfile = ./.\npassword.txt\n" }, { "code": null, "e": 2811, "s": 2681, "text": "apiVersion: v1\nkind: Secret\nmetadata:\nname: tomcat-pass\ntype: Opaque\ndata:\n password: <User Password>\n username: <User Name>\n" }, { "code": null, "e": 2864, "s": 2811, "text": "$ kubectl create –f Secret.yaml\nsecrets/tomcat-pass\n" }, { "code": null, "e": 2961, "s": 2864, "text": "Once we have created the secrets, it can be consumed in a pod or the replication controller as −" }, { "code": null, "e": 2982, "s": 2961, "text": "Environment Variable" }, { "code": null, "e": 2989, "s": 2982, "text": "Volume" }, { "code": null, "e": 3098, "s": 2989, "text": "In order to use the secret as environment variable, we will use env under the spec section of pod yaml file." }, { "code": null, "e": 3212, "s": 3098, "text": "env:\n- name: SECRET_USERNAME\n valueFrom:\n secretKeyRef:\n name: mysecret\n key: tomcat-pass\n" }, { "code": null, "e": 3472, "s": 3212, "text": "spec:\n volumes:\n - name: \"secretstest\"\n secret:\n secretName: tomcat-pass\n containers:\n - image: tomcat:7.0\n name: awebserver\n volumeMounts:\n - mountPath: \"/tmp/mysec\"\n name: \"secretstest\"\n" }, { "code": null, "e": 4047, "s": 3472, "text": "apiVersion: v1\nkind: ReplicationController\nmetadata:\n name: appname\nspec:\nreplicas: replica_count\ntemplate:\n metadata:\n name: appname\n spec:\n nodeSelector:\n resource-group:\n containers:\n - name: appname\n image:\n imagePullPolicy: Always\n ports:\n - containerPort: 3000\n env: -----------------------------> 1\n - name: ENV\n valueFrom:\n configMapKeyRef:\n name: appname\n key: tomcat-secrets\n" }, { "code": null, "e": 4168, "s": 4047, "text": "In the above code, under the env definition, we are using secrets as environment variable in the replication controller." }, { "code": null, "e": 4523, "s": 4168, "text": "apiVersion: v1\nkind: pod\nmetadata:\n name: appname\nspec:\n metadata:\n name: appname\n spec:\n volumes:\n - name: \"secretstest\"\n secret:\n secretName: tomcat-pass\n containers:\n - image: tomcat: 8.0\n name: awebserver\n volumeMounts:\n - mountPath: \"/tmp/mysec\"\n name: \"secretstest\"\n" }, { "code": null, "e": 4556, "s": 4523, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 4568, "s": 4556, "text": " AR Shankar" }, { "code": null, "e": 4601, "s": 4568, "text": "\n 15 Lectures \n 2 hours \n" }, { "code": null, "e": 4641, "s": 4601, "text": " Harshit Srivastava, Pranjal Srivastava" }, { "code": null, "e": 4676, "s": 4641, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4691, "s": 4676, "text": " Nigel Poulton" }, { "code": null, "e": 4726, "s": 4691, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4746, "s": 4726, "text": " Pranjal Srivastava" }, { "code": null, "e": 4779, "s": 4746, "text": "\n 18 Lectures \n 1 hours \n" }, { "code": null, "e": 4799, "s": 4779, "text": " Pranjal Srivastava" }, { "code": null, "e": 4834, "s": 4799, "text": "\n 26 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4854, "s": 4834, "text": " Pranjal Srivastava" }, { "code": null, "e": 4861, "s": 4854, "text": " Print" }, { "code": null, "e": 4872, "s": 4861, "text": " Add Notes" } ]
Finding Driving Lane Line live with OpenCV | by Percy Jaiswal | Towards Data Science
Hello, in this project I will attempt to find lane lines from a dash cam video feed. Once we detect lane lines, we will mark them on the original video frame and play it back. This all will be done online and without any lag using OpenCV functions. Our approach here would be to develop sequence of functions to detect lane lines. We will use a ‘sample’ image while writing this functions, and once we are able to detect lane lines on few ‘sample’ images successfully, we will club complete program into a function which can accept live feed image and return the same image frame with lane lines highlighted. So without much delay, let’s get started. First we input our sample image frame. This line will be commented in final code, where ‘image’ will be frame sent by video capture. image = cv2.imread('test_images/whiteCarLaneSwitch.jpg') To lessen the burden on our processor (which is very scarce resource in embedded systems), we will do all image processing in ‘Greyscale’ version of the image instead of original colored version. This helps execute our program faster with less resources. Below function converts color image to its greyscale version grey_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) Next we will remove noise from our image by blurring it. Image blurring is achieved by convolving the image with a low-pass filter kernel. It is useful for removing noises. It actually removes high frequency content (eg: noise, edges) from the image. So edges are blurred a little bit in this operation. OpenCV provides 4 different types of blurring techniques, with Gaussian blur being the most popular one. We can select different kernel sizes, wherein the resultant filter will simply take the average of all the pixels under kernel (a row x column matrix of kernel size) area and replace the central element with average value. Again 5 is a fairly standard value and has worked for me. kernel_size = 5blur_gray = cv2.GaussianBlur(grey_image,(kernel_size, kernel_size),0) Canny Edge Detection is a popular edge detection algorithm. In fact Canny edge function also implements a 5x5 kernel Gaussian filter that we had used in previous steps, but in many of the literature that I had come across, it’s always recommended to implement your own blurring before canny edge detection. The basic theory behind edge detection is, wherever there is an edge, the pixel on either side of the edge have a big difference (also called gradient) between their intensities. First the input image is scanned in both horizontal and vertical direction to find gradient for each pixel. After getting gradient magnitude and direction, a full scan of image is done to remove any unwanted pixels which may not constitute the edge. For this, at every pixel, pixel is checked if it is a local maximum in its neighborhood. low_threshold and high_threshold determine how strong the edge must be to be detected. A gradient is considered to be part of an edge, if its gradient is higher than ‘high_threshold’. But once an edge is detected, the next pixel is included in the edge even if it’s greater than just ‘low_threshold’. low_threshold = 50high_threshold = 150edges = cv2.Canny(blur_gray, low_threshold, high_threshold) With reference to our sample image, it’s clear that at edge conditions, especially where lane lines are, there is vast contrast difference between adjacent pixels, with lane line being white and adjacent road pixel being dark. One thing to consider is, we don’t want to find all the edges in the image. We are just interested in finding the lane around the center area of our image. Intuitively it makes sense as in an edge in top right / left portion of the image is highly unlikely to be a driving lane. Looking at out sample image, we can safely say that lane lines should be inside a trapezoidal area with broader edge at bottom of image and with edges becoming narrower as we go towards top portion of the image. Following four lines mark the region of interest in our edge detected image. First, we find out size of the image, second we create four corners of trapezoid (this step, as many others is bit of an iterative process, wherein we need to try with different values to find out best case). Third, we create the trapezoid with above vertices and finally we do a bitwise operation, so that only pixel which are inside region of interest and are classified as edge are marked as 1. imshape = image.shapevertices = np.array([[(0,imshape[0]),(450, 320), (500, 320), (imshape[1],imshape[0])]], dtype=np.int32)cv2.fillPoly(mask, vertices, ignore_mask_color)masked_edges = cv2.bitwise_and(edges, mask) Next we perform Hough Line Transform in order to detect a line from the above edge detected image. Remember an edge could be a circular edge too, but the edge we are interested in our application is line edge of a driving lane. In short, Hough’s transform method transforms a line from its traditional y = mx + b form to rho = x *cos (theta) + y * sin (theta) where rho is the perpendicular distance from origin to the line, and theta is the angle formed by this perpendicular line and horizontal axis. We know that a line (y = mx + b) when represented in m vs b graph is just a point, and a point in x, y frame is represented as a line in m vs b frame. So our strategy to find lines in image space will be to find intersecting lines in Hough space. We do this by dividing up our Hough space into a grid and define intersecting lines as all lines passing through a given grid cell. And where many lines in Hough space intersect, we declare we have found a collection of points that describe a line in image space. We have a problem though, vertical lines have infinite slope in m vs b representation and that’s where need for rho vs theta parameterization comes into picture. Now each point in image space corresponds to a sine curve in Hough space (rho vs theta). And if we take a whole line of points, it translated into whole bunch of sine curves in Hough space. You can consider a sine curve in Hough space as equivalent to a line in m vs b space which is representation of a point in image space. And again, the intersection of those sine curves in Hough space gives the representation of the line. Coming back to our code, we first define parameters for Hough Transform, and then call the function itself. rho = 2 # distance resolution in pixels of the Hough gridtheta = np.pi/180 # angular resolution in radians of the Hough gridthreshold = 15 # minimum number of votes (intersections in Hough grid cell)min_line_length = 40 #minimum number of pixels making up a linemax_line_gap = 30 # maximum gap in pixels between connectable line segmentsline_image = np.copy(image)*0 # creating a blank to draw lines on Output “lines” is an array containing endpoints of detected line segments. lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]),min_line_length, max_line_gap) Iterate over the output “lines” and draw lines on a blank image. for line in lines: for x1,y1,x2,y2 in line: cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10) Draw the lines on the original image and return it. lines_edges = cv2.addWeighted(image, 0.8, line_image, 1, 0)return lines_edges After successfully detecting lane lines on an sample image, we will take a video as an input, detect lane lines and play back the video. Note that here I am processing a previously recorded video, but this can very easily be applied to a live video using same cv2.VideoCapture function. First we create an object of our video using cv2.VideoCapture command. While ‘video_capture’ is running, we read it. Read() function will return two variable, where first variable is a Boolean value indicating success or failure of read operation with a true or false value respectively and second object is the captured frame itself. So whenever ‘ret’ is true, we take the frame and simply pass it to processImage function which we just built above. The output received from processImage is displayed showing lane marking on top of captured frame. video_capture = cv2.VideoCapture('test_videos/solidWhiteRight.mp4')while (video_capture.isOpened()): ret, frame = video_capture.read() if ret: output = processImage(frame) cv2.imshow('frame',output) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break# Release everything if job is finishedvideo_capture.release()cv2.destroyAllWindows() And that’s about it. Hope this article was written in good enough manner for you to have a pleasant read and hopefully learn a thing or two. Obviously there are many more improvements which can be implement in above program, for e.g. checking slope of detected line to check whether detect line is in fact consistent with lane line and remove outliers. Etc. Feel free to suggest any improvements and suggest which can help me grow too. Complete code with sample image and video can be found here If you liked this post, Follow, Like, Retweet it on Twitter or Claps, Likes here on Medium will act as encouragement for writing new posts as I continue my journey into Blogging world. Till next time....cheers!!
[ { "code": null, "e": 421, "s": 172, "text": "Hello, in this project I will attempt to find lane lines from a dash cam video feed. Once we detect lane lines, we will mark them on the original video frame and play it back. This all will be done online and without any lag using OpenCV functions." }, { "code": null, "e": 823, "s": 421, "text": "Our approach here would be to develop sequence of functions to detect lane lines. We will use a ‘sample’ image while writing this functions, and once we are able to detect lane lines on few ‘sample’ images successfully, we will club complete program into a function which can accept live feed image and return the same image frame with lane lines highlighted. So without much delay, let’s get started." }, { "code": null, "e": 956, "s": 823, "text": "First we input our sample image frame. This line will be commented in final code, where ‘image’ will be frame sent by video capture." }, { "code": null, "e": 1013, "s": 956, "text": "image = cv2.imread('test_images/whiteCarLaneSwitch.jpg')" }, { "code": null, "e": 1329, "s": 1013, "text": "To lessen the burden on our processor (which is very scarce resource in embedded systems), we will do all image processing in ‘Greyscale’ version of the image instead of original colored version. This helps execute our program faster with less resources. Below function converts color image to its greyscale version" }, { "code": null, "e": 1382, "s": 1329, "text": "grey_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)" }, { "code": null, "e": 1791, "s": 1382, "text": "Next we will remove noise from our image by blurring it. Image blurring is achieved by convolving the image with a low-pass filter kernel. It is useful for removing noises. It actually removes high frequency content (eg: noise, edges) from the image. So edges are blurred a little bit in this operation. OpenCV provides 4 different types of blurring techniques, with Gaussian blur being the most popular one." }, { "code": null, "e": 2072, "s": 1791, "text": "We can select different kernel sizes, wherein the resultant filter will simply take the average of all the pixels under kernel (a row x column matrix of kernel size) area and replace the central element with average value. Again 5 is a fairly standard value and has worked for me." }, { "code": null, "e": 2157, "s": 2072, "text": "kernel_size = 5blur_gray = cv2.GaussianBlur(grey_image,(kernel_size, kernel_size),0)" }, { "code": null, "e": 2982, "s": 2157, "text": "Canny Edge Detection is a popular edge detection algorithm. In fact Canny edge function also implements a 5x5 kernel Gaussian filter that we had used in previous steps, but in many of the literature that I had come across, it’s always recommended to implement your own blurring before canny edge detection. The basic theory behind edge detection is, wherever there is an edge, the pixel on either side of the edge have a big difference (also called gradient) between their intensities. First the input image is scanned in both horizontal and vertical direction to find gradient for each pixel. After getting gradient magnitude and direction, a full scan of image is done to remove any unwanted pixels which may not constitute the edge. For this, at every pixel, pixel is checked if it is a local maximum in its neighborhood." }, { "code": null, "e": 3283, "s": 2982, "text": "low_threshold and high_threshold determine how strong the edge must be to be detected. A gradient is considered to be part of an edge, if its gradient is higher than ‘high_threshold’. But once an edge is detected, the next pixel is included in the edge even if it’s greater than just ‘low_threshold’." }, { "code": null, "e": 3381, "s": 3283, "text": "low_threshold = 50high_threshold = 150edges = cv2.Canny(blur_gray, low_threshold, high_threshold)" }, { "code": null, "e": 3608, "s": 3381, "text": "With reference to our sample image, it’s clear that at edge conditions, especially where lane lines are, there is vast contrast difference between adjacent pixels, with lane line being white and adjacent road pixel being dark." }, { "code": null, "e": 4099, "s": 3608, "text": "One thing to consider is, we don’t want to find all the edges in the image. We are just interested in finding the lane around the center area of our image. Intuitively it makes sense as in an edge in top right / left portion of the image is highly unlikely to be a driving lane. Looking at out sample image, we can safely say that lane lines should be inside a trapezoidal area with broader edge at bottom of image and with edges becoming narrower as we go towards top portion of the image." }, { "code": null, "e": 4574, "s": 4099, "text": "Following four lines mark the region of interest in our edge detected image. First, we find out size of the image, second we create four corners of trapezoid (this step, as many others is bit of an iterative process, wherein we need to try with different values to find out best case). Third, we create the trapezoid with above vertices and finally we do a bitwise operation, so that only pixel which are inside region of interest and are classified as edge are marked as 1." }, { "code": null, "e": 4789, "s": 4574, "text": "imshape = image.shapevertices = np.array([[(0,imshape[0]),(450, 320), (500, 320), (imshape[1],imshape[0])]], dtype=np.int32)cv2.fillPoly(mask, vertices, ignore_mask_color)masked_edges = cv2.bitwise_and(edges, mask)" }, { "code": null, "e": 5017, "s": 4789, "text": "Next we perform Hough Line Transform in order to detect a line from the above edge detected image. Remember an edge could be a circular edge too, but the edge we are interested in our application is line edge of a driving lane." }, { "code": null, "e": 5292, "s": 5017, "text": "In short, Hough’s transform method transforms a line from its traditional y = mx + b form to rho = x *cos (theta) + y * sin (theta) where rho is the perpendicular distance from origin to the line, and theta is the angle formed by this perpendicular line and horizontal axis." }, { "code": null, "e": 5443, "s": 5292, "text": "We know that a line (y = mx + b) when represented in m vs b graph is just a point, and a point in x, y frame is represented as a line in m vs b frame." }, { "code": null, "e": 5803, "s": 5443, "text": "So our strategy to find lines in image space will be to find intersecting lines in Hough space. We do this by dividing up our Hough space into a grid and define intersecting lines as all lines passing through a given grid cell. And where many lines in Hough space intersect, we declare we have found a collection of points that describe a line in image space." }, { "code": null, "e": 5965, "s": 5803, "text": "We have a problem though, vertical lines have infinite slope in m vs b representation and that’s where need for rho vs theta parameterization comes into picture." }, { "code": null, "e": 6501, "s": 5965, "text": "Now each point in image space corresponds to a sine curve in Hough space (rho vs theta). And if we take a whole line of points, it translated into whole bunch of sine curves in Hough space. You can consider a sine curve in Hough space as equivalent to a line in m vs b space which is representation of a point in image space. And again, the intersection of those sine curves in Hough space gives the representation of the line. Coming back to our code, we first define parameters for Hough Transform, and then call the function itself." }, { "code": null, "e": 6911, "s": 6501, "text": "rho = 2 # distance resolution in pixels of the Hough gridtheta = np.pi/180 # angular resolution in radians of the Hough gridthreshold = 15 # minimum number of votes (intersections in Hough grid cell)min_line_length = 40 #minimum number of pixels making up a linemax_line_gap = 30 # maximum gap in pixels between connectable line segmentsline_image = np.copy(image)*0 # creating a blank to draw lines on" }, { "code": null, "e": 6986, "s": 6911, "text": "Output “lines” is an array containing endpoints of detected line segments." }, { "code": null, "e": 7091, "s": 6986, "text": "lines = cv2.HoughLinesP(masked_edges, rho, theta, threshold, np.array([]),min_line_length, max_line_gap)" }, { "code": null, "e": 7156, "s": 7091, "text": "Iterate over the output “lines” and draw lines on a blank image." }, { "code": null, "e": 7268, "s": 7156, "text": "for line in lines: for x1,y1,x2,y2 in line: cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10)" }, { "code": null, "e": 7320, "s": 7268, "text": "Draw the lines on the original image and return it." }, { "code": null, "e": 7398, "s": 7320, "text": "lines_edges = cv2.addWeighted(image, 0.8, line_image, 1, 0)return lines_edges" }, { "code": null, "e": 7685, "s": 7398, "text": "After successfully detecting lane lines on an sample image, we will take a video as an input, detect lane lines and play back the video. Note that here I am processing a previously recorded video, but this can very easily be applied to a live video using same cv2.VideoCapture function." }, { "code": null, "e": 8234, "s": 7685, "text": "First we create an object of our video using cv2.VideoCapture command. While ‘video_capture’ is running, we read it. Read() function will return two variable, where first variable is a Boolean value indicating success or failure of read operation with a true or false value respectively and second object is the captured frame itself. So whenever ‘ret’ is true, we take the frame and simply pass it to processImage function which we just built above. The output received from processImage is displayed showing lane marking on top of captured frame." }, { "code": null, "e": 8622, "s": 8234, "text": "video_capture = cv2.VideoCapture('test_videos/solidWhiteRight.mp4')while (video_capture.isOpened()): ret, frame = video_capture.read() if ret: output = processImage(frame) cv2.imshow('frame',output) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break# Release everything if job is finishedvideo_capture.release()cv2.destroyAllWindows()" }, { "code": null, "e": 9118, "s": 8622, "text": "And that’s about it. Hope this article was written in good enough manner for you to have a pleasant read and hopefully learn a thing or two. Obviously there are many more improvements which can be implement in above program, for e.g. checking slope of detected line to check whether detect line is in fact consistent with lane line and remove outliers. Etc. Feel free to suggest any improvements and suggest which can help me grow too. Complete code with sample image and video can be found here" }, { "code": null, "e": 9303, "s": 9118, "text": "If you liked this post, Follow, Like, Retweet it on Twitter or Claps, Likes here on Medium will act as encouragement for writing new posts as I continue my journey into Blogging world." } ]
Java program to round a number
The java.lang.Math.round(float a) returns the closest int to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int. Special cases − If the argument is NaN, the result is 0. If the argument is NaN, the result is 0. If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE. If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE. If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE. If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE. import java.util.Scanner; public class RoundingDecimalPlaces { public static void main(String[] args) { System.out.println("Enter a string value ::"); Scanner sc = new Scanner(System.in); float f = sc.nextFloat(); System.out.println("Result of the given float after rounding:: " + Math.round(f)); } } Enter a string value :: 44584.2257 Result of the given float after rounding:: 44584
[ { "code": null, "e": 1272, "s": 1062, "text": "The java.lang.Math.round(float a) returns the closest int to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int. Special cases −" }, { "code": null, "e": 1313, "s": 1272, "text": "If the argument is NaN, the result is 0." }, { "code": null, "e": 1354, "s": 1313, "text": "If the argument is NaN, the result is 0." }, { "code": null, "e": 1513, "s": 1354, "text": "If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE." }, { "code": null, "e": 1672, "s": 1513, "text": "If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE." }, { "code": null, "e": 1834, "s": 1672, "text": "If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE." }, { "code": null, "e": 1996, "s": 1834, "text": "If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE." }, { "code": null, "e": 2327, "s": 1996, "text": "import java.util.Scanner;\npublic class RoundingDecimalPlaces {\n public static void main(String[] args) {\n System.out.println(\"Enter a string value ::\");\n Scanner sc = new Scanner(System.in);\n float f = sc.nextFloat();\n System.out.println(\"Result of the given float after rounding:: \" + Math.round(f));\n }\n}" }, { "code": null, "e": 2411, "s": 2327, "text": "Enter a string value ::\n44584.2257\nResult of the given float after rounding:: 44584" } ]
R - Quick Guide
R is a programming language and software environment for statistical analysis, graphics representation and reporting. R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and is currently developed by the R Development Core Team. The core of R is an interpreted computer language which allows branching and looping as well as modular programming using functions. R allows integration with the procedures written in the C, C++, .Net, Python or FORTRAN languages for efficiency. R is freely available under the GNU General Public License, and pre-compiled binary versions are provided for various operating systems like Linux, Windows and Mac. R is free software distributed under a GNU-style copy left, and an official part of the GNU project called GNU S. R was initially written by Ross Ihaka and Robert Gentleman at the Department of Statistics of the University of Auckland in Auckland, New Zealand. R made its first appearance in 1993. A large group of individuals has contributed to R by sending code and bug reports. A large group of individuals has contributed to R by sending code and bug reports. Since mid-1997 there has been a core group (the "R Core Team") who can modify the R source code archive. Since mid-1997 there has been a core group (the "R Core Team") who can modify the R source code archive. As stated earlier, R is a programming language and software environment for statistical analysis, graphics representation and reporting. The following are the important features of R − R is a well-developed, simple and effective programming language which includes conditionals, loops, user defined recursive functions and input and output facilities. R is a well-developed, simple and effective programming language which includes conditionals, loops, user defined recursive functions and input and output facilities. R has an effective data handling and storage facility, R has an effective data handling and storage facility, R provides a suite of operators for calculations on arrays, lists, vectors and matrices. R provides a suite of operators for calculations on arrays, lists, vectors and matrices. R provides a large, coherent and integrated collection of tools for data analysis. R provides a large, coherent and integrated collection of tools for data analysis. R provides graphical facilities for data analysis and display either directly at the computer or printing at the papers. R provides graphical facilities for data analysis and display either directly at the computer or printing at the papers. As a conclusion, R is world’s most widely used statistics programming language. It's the # 1 choice of data scientists and supported by a vibrant and talented community of contributors. R is taught in universities and deployed in mission critical business applications. This tutorial will teach you R programming along with suitable examples in simple and easy steps. If you are still willing to set up your environment for R, you can follow the steps given below. You can download the Windows installer version of R from R-3.2.2 for Windows (32/64 bit) and save it in a local directory. As it is a Windows installer (.exe) with a name "R-version-win.exe". You can just double click and run the installer accepting the default settings. If your Windows is 32-bit version, it installs the 32-bit version. But if your windows is 64-bit, then it installs both the 32-bit and 64-bit versions. After installation you can locate the icon to run the Program in a directory structure "R\R3.2.2\bin\i386\Rgui.exe" under the Windows Program Files. Clicking this icon brings up the R-GUI which is the R console to do R Programming. R is available as a binary for many versions of Linux at the location R Binaries. The instruction to install Linux varies from flavor to flavor. These steps are mentioned under each type of Linux version in the mentioned link. However, if you are in a hurry, then you can use yum command to install R as follows − $ yum install R Above command will install core functionality of R programming along with standard packages, still you need additional package, then you can launch R prompt as follows − $ R R version 3.2.0 (2015-04-16) -- "Full of Ingredients" Copyright (C) 2015 The R Foundation for Statistical Computing Platform: x86_64-redhat-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > Now you can use install command at R prompt to install the required package. For example, the following command will install plotrix package which is required for 3D charts. > install.packages("plotrix") As a convention, we will start learning R programming by writing a "Hello, World!" program. Depending on the needs, you can program either at R command prompt or you can use an R script file to write your program. Let's check both one by one. Once you have R environment setup, then it’s easy to start your R command prompt by just typing the following command at your command prompt − $ R This will launch R interpreter and you will get a prompt > where you can start typing your program as follows − > myString <- "Hello, World!" > print ( myString) [1] "Hello, World!" Here first statement defines a string variable myString, where we assign a string "Hello, World!" and then next statement print() is being used to print the value stored in variable myString. Usually, you will do your programming by writing your programs in script files and then you execute those scripts at your command prompt with the help of R interpreter called Rscript. So let's start with writing following code in a text file called test.R as under − # My first program in R Programming myString <- "Hello, World!" print ( myString) Save the above code in a file test.R and execute it at Linux command prompt as given below. Even if you are using Windows or other system, syntax will remain same. $ Rscript test.R When we run the above program, it produces the following result. [1] "Hello, World!" Comments are like helping text in your R program and they are ignored by the interpreter while executing your actual program. Single comment is written using # in the beginning of the statement as follows − # My first program in R Programming R does not support multi-line comments but you can perform a trick which is something as follows − if(FALSE) { "This is a demo for multi-line comments and it should be put inside either a single OR double quote" } myString <- "Hello, World!" print ( myString) [1] "Hello, World!" Though above comments will be executed by R interpreter, they will not interfere with your actual program. You should put such comments inside, either single or double quote. Generally, while doing programming in any programming language, you need to use various variables to store various information. Variables are nothing but reserved memory locations to store values. This means that, when you create a variable you reserve some space in memory. You may like to store information of various data types like character, wide character, integer, floating point, double floating point, Boolean etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. In contrast to other programming languages like C and java in R, the variables are not declared as some data type. The variables are assigned with R-Objects and the data type of the R-object becomes the data type of the variable. There are many types of R-objects. The frequently used ones are − Vectors Lists Matrices Arrays Factors Data Frames The simplest of these objects is the vector object and there are six data types of these atomic vectors, also termed as six classes of vectors. The other R-Objects are built upon the atomic vectors. v <- TRUE print(class(v)) it produces the following result − [1] "logical" v <- 23.5 print(class(v)) it produces the following result − [1] "numeric" v <- 2L print(class(v)) it produces the following result − [1] "integer" v <- 2+5i print(class(v)) it produces the following result − [1] "complex" v <- "TRUE" print(class(v)) it produces the following result − [1] "character" v <- charToRaw("Hello") print(class(v)) it produces the following result − [1] "raw" In R programming, the very basic data types are the R-objects called vectors which hold elements of different classes as shown above. Please note in R the number of classes is not confined to only the above six types. For example, we can use many atomic vectors and create an array whose class will become array. When you want to create vector with more than one element, you should use c() function which means to combine the elements into a vector. # Create a vector. apple <- c('red','green',"yellow") print(apple) # Get the class of the vector. print(class(apple)) When we execute the above code, it produces the following result − [1] "red" "green" "yellow" [1] "character" A list is an R-object which can contain many different types of elements inside it like vectors, functions and even another list inside it. # Create a list. list1 <- list(c(2,5,3),21.3,sin) # Print the list. print(list1) When we execute the above code, it produces the following result − [[1]] [1] 2 5 3 [[2]] [1] 21.3 [[3]] function (x) .Primitive("sin") A matrix is a two-dimensional rectangular data set. It can be created using a vector input to the matrix function. # Create a matrix. M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE) print(M) When we execute the above code, it produces the following result − [,1] [,2] [,3] [1,] "a" "a" "b" [2,] "c" "b" "a" While matrices are confined to two dimensions, arrays can be of any number of dimensions. The array function takes a dim attribute which creates the required number of dimension. In the below example we create an array with two elements which are 3x3 matrices each. # Create an array. a <- array(c('green','yellow'),dim = c(3,3,2)) print(a) When we execute the above code, it produces the following result − , , 1 [,1] [,2] [,3] [1,] "green" "yellow" "green" [2,] "yellow" "green" "yellow" [3,] "green" "yellow" "green" , , 2 [,1] [,2] [,3] [1,] "yellow" "green" "yellow" [2,] "green" "yellow" "green" [3,] "yellow" "green" "yellow" Factors are the r-objects which are created using a vector. It stores the vector along with the distinct values of the elements in the vector as labels. The labels are always character irrespective of whether it is numeric or character or Boolean etc. in the input vector. They are useful in statistical modeling. Factors are created using the factor() function. The nlevels functions gives the count of levels. # Create a vector. apple_colors <- c('green','green','yellow','red','red','red','green') # Create a factor object. factor_apple <- factor(apple_colors) # Print the factor. print(factor_apple) print(nlevels(factor_apple)) When we execute the above code, it produces the following result − [1] green green yellow red red red green Levels: green red yellow [1] 3 Data frames are tabular data objects. Unlike a matrix in data frame each column can contain different modes of data. The first column can be numeric while the second column can be character and third column can be logical. It is a list of vectors of equal length. Data Frames are created using the data.frame() function. # Create the data frame. BMI <- data.frame( gender = c("Male", "Male","Female"), height = c(152, 171.5, 165), weight = c(81,93, 78), Age = c(42,38,26) ) print(BMI) When we execute the above code, it produces the following result − gender height weight Age 1 Male 152.0 81 42 2 Male 171.5 93 38 3 Female 165.0 78 26 A variable provides us with named storage that our programs can manipulate. A variable in R can store an atomic vector, group of atomic vectors or a combination of many Robjects. A valid variable name consists of letters, numbers and the dot or underline characters. The variable name starts with a letter or the dot not followed by a number. .var_name, var.name The variables can be assigned values using leftward, rightward and equal to operator. The values of the variables can be printed using print() or cat() function. The cat() function combines multiple items into a continuous print output. # Assignment using equal operator. var.1 = c(0,1,2,3) # Assignment using leftward operator. var.2 <- c("learn","R") # Assignment using rightward operator. c(TRUE,1) -> var.3 print(var.1) cat ("var.1 is ", var.1 ,"\n") cat ("var.2 is ", var.2 ,"\n") cat ("var.3 is ", var.3 ,"\n") When we execute the above code, it produces the following result − [1] 0 1 2 3 var.1 is 0 1 2 3 var.2 is learn R var.3 is 1 1 Note − The vector c(TRUE,1) has a mix of logical and numeric class. So logical class is coerced to numeric class making TRUE as 1. In R, a variable itself is not declared of any data type, rather it gets the data type of the R - object assigned to it. So R is called a dynamically typed language, which means that we can change a variable’s data type of the same variable again and again when using it in a program. var_x <- "Hello" cat("The class of var_x is ",class(var_x),"\n") var_x <- 34.5 cat(" Now the class of var_x is ",class(var_x),"\n") var_x <- 27L cat(" Next the class of var_x becomes ",class(var_x),"\n") When we execute the above code, it produces the following result − The class of var_x is character Now the class of var_x is numeric Next the class of var_x becomes integer To know all the variables currently available in the workspace we use the ls() function. Also the ls() function can use patterns to match the variable names. print(ls()) When we execute the above code, it produces the following result − [1] "my var" "my_new_var" "my_var" "var.1" [5] "var.2" "var.3" "var.name" "var_name2." [9] "var_x" "varname" Note − It is a sample output depending on what variables are declared in your environment. The ls() function can use patterns to match the variable names. # List the variables starting with the pattern "var". print(ls(pattern = "var")) When we execute the above code, it produces the following result − [1] "my var" "my_new_var" "my_var" "var.1" [5] "var.2" "var.3" "var.name" "var_name2." [9] "var_x" "varname" The variables starting with dot(.) are hidden, they can be listed using "all.names = TRUE" argument to ls() function. print(ls(all.name = TRUE)) When we execute the above code, it produces the following result − [1] ".cars" ".Random.seed" ".var_name" ".varname" ".varname2" [6] "my var" "my_new_var" "my_var" "var.1" "var.2" [11]"var.3" "var.name" "var_name2." "var_x" Variables can be deleted by using the rm() function. Below we delete the variable var.3. On printing the value of the variable error is thrown. rm(var.3) print(var.3) When we execute the above code, it produces the following result − [1] "var.3" Error in print(var.3) : object 'var.3' not found All the variables can be deleted by using the rm() and ls() function together. rm(list = ls()) print(ls()) When we execute the above code, it produces the following result − character(0) An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. R language is rich in built-in operators and provides following types of operators. We have the following types of operators in R programming − Arithmetic Operators Relational Operators Logical Operators Assignment Operators Miscellaneous Operators Following table shows the arithmetic operators supported by R language. The operators act on each element of the vector. v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v+t) it produces the following result − [1] 10.0 8.5 10.0 v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v-t) it produces the following result − [1] -6.0 2.5 2.0 v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v*t) it produces the following result − [1] 16.0 16.5 24.0 v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v/t) When we execute the above code, it produces the following result − [1] 0.250000 1.833333 1.500000 v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v%%t) it produces the following result − [1] 2.0 2.5 2.0 v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v%/%t) it produces the following result − [1] 0 1 1 v <- c( 2,5.5,6) t <- c(8, 3, 4) print(v^t) it produces the following result − [1] 256.000 166.375 1296.000 Following table shows the relational operators supported by R language. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value. v <- c(2,5.5,6,9) t <- c(8,2.5,14,9) print(v>t) it produces the following result − [1] FALSE TRUE FALSE FALSE v <- c(2,5.5,6,9) t <- c(8,2.5,14,9) print(v < t) it produces the following result − [1] TRUE FALSE TRUE FALSE v <- c(2,5.5,6,9) t <- c(8,2.5,14,9) print(v == t) it produces the following result − [1] FALSE FALSE FALSE TRUE v <- c(2,5.5,6,9) t <- c(8,2.5,14,9) print(v<=t) it produces the following result − [1] TRUE FALSE TRUE TRUE v <- c(2,5.5,6,9) t <- c(8,2.5,14,9) print(v>=t) it produces the following result − [1] FALSE TRUE FALSE TRUE v <- c(2,5.5,6,9) t <- c(8,2.5,14,9) print(v!=t) it produces the following result − [1] TRUE TRUE TRUE FALSE Following table shows the logical operators supported by R language. It is applicable only to vectors of type logical, numeric or complex. All numbers greater than 1 are considered as logical value TRUE. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value. v <- c(3,1,TRUE,2+3i) t <- c(4,1,FALSE,2+3i) print(v&t) it produces the following result − [1] TRUE TRUE FALSE TRUE v <- c(3,0,TRUE,2+2i) t <- c(4,0,FALSE,2+3i) print(v|t) it produces the following result − [1] TRUE FALSE TRUE TRUE v <- c(3,0,TRUE,2+2i) print(!v) it produces the following result − [1] FALSE TRUE FALSE FALSE The logical operator && and || considers only the first element of the vectors and give a vector of single element as output. v <- c(3,0,TRUE,2+2i) t <- c(1,3,TRUE,2+3i) print(v&&t) it produces the following result − [1] TRUE v <- c(0,0,TRUE,2+2i) t <- c(0,3,TRUE,2+3i) print(v||t) it produces the following result − [1] FALSE These operators are used to assign values to vectors. <− or = or <<− v1 <- c(3,1,TRUE,2+3i) v2 <<- c(3,1,TRUE,2+3i) v3 = c(3,1,TRUE,2+3i) print(v1) print(v2) print(v3) it produces the following result − [1] 3+0i 1+0i 1+0i 2+3i [1] 3+0i 1+0i 1+0i 2+3i [1] 3+0i 1+0i 1+0i 2+3i -> or ->> c(3,1,TRUE,2+3i) -> v1 c(3,1,TRUE,2+3i) ->> v2 print(v1) print(v2) it produces the following result − [1] 3+0i 1+0i 1+0i 2+3i [1] 3+0i 1+0i 1+0i 2+3i These operators are used to for specific purpose and not general mathematical or logical computation. v <- 2:8 print(v) it produces the following result − [1] 2 3 4 5 6 7 8 v1 <- 8 v2 <- 12 t <- 1:10 print(v1 %in% t) print(v2 %in% t) it produces the following result − [1] TRUE [1] FALSE M = matrix( c(2,6,5,1,10,4), nrow = 2,ncol = 3,byrow = TRUE) t = M %*% t(M) print(t) it produces the following result − [,1] [,2] [1,] 65 82 [2,] 82 117 Decision making structures require the programmer to specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − R provides the following types of decision making statements. Click the following links to check their detail. An if statement consists of a Boolean expression followed by one or more statements. An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. A switch statement allows a variable to be tested for equality against a list of values. There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially. The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and the following is the general form of a loop statement in most of the programming languages − R programming language provides the following kinds of loop to handle looping requirements. Click the following links to check their detail. Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. Like a while statement, except that it tests the condition at the end of the loop body. Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. R supports the following control statements. Click the following links to check their detail. Terminates the loop statement and transfers execution to the statement immediately following the loop. The next statement simulates the behavior of R switch. A function is a set of statements organized together to perform a specific task. R has a large number of in-built functions and the user can create their own functions. In R, a function is an object so the R interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions. The function in turn performs its task and returns control to the interpreter as well as any result which may be stored in other objects. An R function is created by using the keyword function. The basic syntax of an R function definition is as follows − function_name <- function(arg_1, arg_2, ...) { Function body } The different parts of a function are − Function Name − This is the actual name of the function. It is stored in R environment as an object with this name. Function Name − This is the actual name of the function. It is stored in R environment as an object with this name. Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values. Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values. Function Body − The function body contains a collection of statements that defines what the function does. Function Body − The function body contains a collection of statements that defines what the function does. Return Value − The return value of a function is the last expression in the function body to be evaluated. Return Value − The return value of a function is the last expression in the function body to be evaluated. R has many in-built functions which can be directly called in the program without defining them first. We can also create and use our own functions referred as user defined functions. Simple examples of in-built functions are seq(), mean(), max(), sum(x) and paste(...) etc. They are directly called by user written programs. You can refer most widely used R functions. # Create a sequence of numbers from 32 to 44. print(seq(32,44)) # Find mean of numbers from 25 to 82. print(mean(25:82)) # Find sum of numbers frm 41 to 68. print(sum(41:68)) When we execute the above code, it produces the following result − [1] 32 33 34 35 36 37 38 39 40 41 42 43 44 [1] 53.5 [1] 1526 We can create user-defined functions in R. They are specific to what a user wants and once created they can be used like the built-in functions. Below is an example of how a function is created and used. # Create a function to print squares of numbers in sequence. new.function <- function(a) { for(i in 1:a) { b <- i^2 print(b) } } # Create a function to print squares of numbers in sequence. new.function <- function(a) { for(i in 1:a) { b <- i^2 print(b) } } # Call the function new.function supplying 6 as an argument. new.function(6) When we execute the above code, it produces the following result − [1] 1 [1] 4 [1] 9 [1] 16 [1] 25 [1] 36 # Create a function without an argument. new.function <- function() { for(i in 1:5) { print(i^2) } } # Call the function without supplying an argument. new.function() When we execute the above code, it produces the following result − [1] 1 [1] 4 [1] 9 [1] 16 [1] 25 The arguments to a function call can be supplied in the same sequence as defined in the function or they can be supplied in a different sequence but assigned to the names of the arguments. # Create a function with arguments. new.function <- function(a,b,c) { result <- a * b + c print(result) } # Call the function by position of arguments. new.function(5,3,11) # Call the function by names of the arguments. new.function(a = 11, b = 5, c = 3) When we execute the above code, it produces the following result − [1] 26 [1] 58 We can define the value of the arguments in the function definition and call the function without supplying any argument to get the default result. But we can also call such functions by supplying new values of the argument and get non default result. # Create a function with arguments. new.function <- function(a = 3, b = 6) { result <- a * b print(result) } # Call the function without giving any argument. new.function() # Call the function with giving new values of the argument. new.function(9,5) When we execute the above code, it produces the following result − [1] 18 [1] 45 Arguments to functions are evaluated lazily, which means so they are evaluated only when needed by the function body. # Create a function with arguments. new.function <- function(a, b) { print(a^2) print(a) print(b) } # Evaluate the function without supplying one of the arguments. new.function(6) When we execute the above code, it produces the following result − [1] 36 [1] 6 Error in print(b) : argument "b" is missing, with no default Any value written within a pair of single quote or double quotes in R is treated as a string. Internally R stores every string within double quotes, even when you create them with single quote. The quotes at the beginning and end of a string should be both double quotes or both single quote. They can not be mixed. The quotes at the beginning and end of a string should be both double quotes or both single quote. They can not be mixed. Double quotes can be inserted into a string starting and ending with single quote. Double quotes can be inserted into a string starting and ending with single quote. Single quote can be inserted into a string starting and ending with double quotes. Single quote can be inserted into a string starting and ending with double quotes. Double quotes can not be inserted into a string starting and ending with double quotes. Double quotes can not be inserted into a string starting and ending with double quotes. Single quote can not be inserted into a string starting and ending with single quote. Single quote can not be inserted into a string starting and ending with single quote. Following examples clarify the rules about creating a string in R. a <- 'Start and end with single quote' print(a) b <- "Start and end with double quotes" print(b) c <- "single quote ' in between double quotes" print(c) d <- 'Double quotes " in between single quote' print(d) When the above code is run we get the following output − [1] "Start and end with single quote" [1] "Start and end with double quotes" [1] "single quote ' in between double quote" [1] "Double quote \" in between single quote" e <- 'Mixed quotes" print(e) f <- 'Single quote ' inside single quote' print(f) g <- "Double quotes " inside double quotes" print(g) When we run the script it fails giving below results. Error: unexpected symbol in: "print(e) f <- 'Single" Execution halted Many strings in R are combined using the paste() function. It can take any number of arguments to be combined together. The basic syntax for paste function is − paste(..., sep = " ", collapse = NULL) Following is the description of the parameters used − ... represents any number of arguments to be combined. ... represents any number of arguments to be combined. sep represents any separator between the arguments. It is optional. sep represents any separator between the arguments. It is optional. collapse is used to eliminate the space in between two strings. But not the space within two words of one string. collapse is used to eliminate the space in between two strings. But not the space within two words of one string. a <- "Hello" b <- 'How' c <- "are you? " print(paste(a,b,c)) print(paste(a,b,c, sep = "-")) print(paste(a,b,c, sep = "", collapse = "")) When we execute the above code, it produces the following result − [1] "Hello How are you? " [1] "Hello-How-are you? " [1] "HelloHoware you? " Numbers and strings can be formatted to a specific style using format() function. The basic syntax for format function is − format(x, digits, nsmall, scientific, width, justify = c("left", "right", "centre", "none")) Following is the description of the parameters used − x is the vector input. x is the vector input. digits is the total number of digits displayed. digits is the total number of digits displayed. nsmall is the minimum number of digits to the right of the decimal point. nsmall is the minimum number of digits to the right of the decimal point. scientific is set to TRUE to display scientific notation. scientific is set to TRUE to display scientific notation. width indicates the minimum width to be displayed by padding blanks in the beginning. width indicates the minimum width to be displayed by padding blanks in the beginning. justify is the display of the string to left, right or center. justify is the display of the string to left, right or center. # Total number of digits displayed. Last digit rounded off. result <- format(23.123456789, digits = 9) print(result) # Display numbers in scientific notation. result <- format(c(6, 13.14521), scientific = TRUE) print(result) # The minimum number of digits to the right of the decimal point. result <- format(23.47, nsmall = 5) print(result) # Format treats everything as a string. result <- format(6) print(result) # Numbers are padded with blank in the beginning for width. result <- format(13.7, width = 6) print(result) # Left justify strings. result <- format("Hello", width = 8, justify = "l") print(result) # Justfy string with center. result <- format("Hello", width = 8, justify = "c") print(result) When we execute the above code, it produces the following result − [1] "23.1234568" [1] "6.000000e+00" "1.314521e+01" [1] "23.47000" [1] "6" [1] " 13.7" [1] "Hello " [1] " Hello " This function counts the number of characters including spaces in a string. The basic syntax for nchar() function is − nchar(x) Following is the description of the parameters used − x is the vector input. x is the vector input. result <- nchar("Count the number of characters") print(result) When we execute the above code, it produces the following result − [1] 30 These functions change the case of characters of a string. The basic syntax for toupper() & tolower() function is − toupper(x) tolower(x) Following is the description of the parameters used − x is the vector input. x is the vector input. # Changing to Upper case. result <- toupper("Changing To Upper") print(result) # Changing to lower case. result <- tolower("Changing To Lower") print(result) When we execute the above code, it produces the following result − [1] "CHANGING TO UPPER" [1] "changing to lower" This function extracts parts of a String. The basic syntax for substring() function is − substring(x,first,last) Following is the description of the parameters used − x is the character vector input. x is the character vector input. first is the position of the first character to be extracted. first is the position of the first character to be extracted. last is the position of the last character to be extracted. last is the position of the last character to be extracted. # Extract characters from 5th to 7th position. result <- substring("Extract", 5, 7) print(result) When we execute the above code, it produces the following result − [1] "act" Vectors are the most basic R data objects and there are six types of atomic vectors. They are logical, integer, double, complex, character and raw. Even when you write just one value in R, it becomes a vector of length 1 and belongs to one of the above vector types. # Atomic vector of type character. print("abc"); # Atomic vector of type double. print(12.5) # Atomic vector of type integer. print(63L) # Atomic vector of type logical. print(TRUE) # Atomic vector of type complex. print(2+3i) # Atomic vector of type raw. print(charToRaw('hello')) When we execute the above code, it produces the following result − [1] "abc" [1] 12.5 [1] 63 [1] TRUE [1] 2+3i [1] 68 65 6c 6c 6f Using colon operator with numeric data # Creating a sequence from 5 to 13. v <- 5:13 print(v) # Creating a sequence from 6.6 to 12.6. v <- 6.6:12.6 print(v) # If the final element specified does not belong to the sequence then it is discarded. v <- 3.8:11.4 print(v) When we execute the above code, it produces the following result − [1] 5 6 7 8 9 10 11 12 13 [1] 6.6 7.6 8.6 9.6 10.6 11.6 12.6 [1] 3.8 4.8 5.8 6.8 7.8 8.8 9.8 10.8 Using sequence (Seq.) operator # Create vector with elements from 5 to 9 incrementing by 0.4. print(seq(5, 9, by = 0.4)) When we execute the above code, it produces the following result − [1] 5.0 5.4 5.8 6.2 6.6 7.0 7.4 7.8 8.2 8.6 9.0 Using the c() function The non-character values are coerced to character type if one of the elements is a character. # The logical and numeric values are converted to characters. s <- c('apple','red',5,TRUE) print(s) When we execute the above code, it produces the following result − [1] "apple" "red" "5" "TRUE" Elements of a Vector are accessed using indexing. The [ ] brackets are used for indexing. Indexing starts with position 1. Giving a negative value in the index drops that element from result.TRUE, FALSE or 0 and 1 can also be used for indexing. # Accessing vector elements using position. t <- c("Sun","Mon","Tue","Wed","Thurs","Fri","Sat") u <- t[c(2,3,6)] print(u) # Accessing vector elements using logical indexing. v <- t[c(TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE)] print(v) # Accessing vector elements using negative indexing. x <- t[c(-2,-5)] print(x) # Accessing vector elements using 0/1 indexing. y <- t[c(0,0,0,0,0,0,1)] print(y) When we execute the above code, it produces the following result − [1] "Mon" "Tue" "Fri" [1] "Sun" "Fri" [1] "Sun" "Tue" "Wed" "Fri" "Sat" [1] "Sun" Two vectors of same length can be added, subtracted, multiplied or divided giving the result as a vector output. # Create two vectors. v1 <- c(3,8,4,5,0,11) v2 <- c(4,11,0,8,1,2) # Vector addition. add.result <- v1+v2 print(add.result) # Vector subtraction. sub.result <- v1-v2 print(sub.result) # Vector multiplication. multi.result <- v1*v2 print(multi.result) # Vector division. divi.result <- v1/v2 print(divi.result) When we execute the above code, it produces the following result − [1] 7 19 4 13 1 13 [1] -1 -3 4 -3 -1 9 [1] 12 88 0 40 0 22 [1] 0.7500000 0.7272727 Inf 0.6250000 0.0000000 5.5000000 If we apply arithmetic operations to two vectors of unequal length, then the elements of the shorter vector are recycled to complete the operations. v1 <- c(3,8,4,5,0,11) v2 <- c(4,11) # V2 becomes c(4,11,4,11,4,11) add.result <- v1+v2 print(add.result) sub.result <- v1-v2 print(sub.result) When we execute the above code, it produces the following result − [1] 7 19 8 16 4 22 [1] -1 -3 0 -6 -4 0 Elements in a vector can be sorted using the sort() function. v <- c(3,8,4,5,0,11, -9, 304) # Sort the elements of the vector. sort.result <- sort(v) print(sort.result) # Sort the elements in the reverse order. revsort.result <- sort(v, decreasing = TRUE) print(revsort.result) # Sorting character vectors. v <- c("Red","Blue","yellow","violet") sort.result <- sort(v) print(sort.result) # Sorting character vectors in reverse order. revsort.result <- sort(v, decreasing = TRUE) print(revsort.result) When we execute the above code, it produces the following result − [1] -9 0 3 4 5 8 11 304 [1] 304 11 8 5 4 3 0 -9 [1] "Blue" "Red" "violet" "yellow" [1] "yellow" "violet" "Red" "Blue" Lists are the R objects which contain elements of different types like − numbers, strings, vectors and another list inside it. A list can also contain a matrix or a function as its elements. List is created using list() function. Following is an example to create a list containing strings, numbers, vectors and a logical values. # Create a list containing strings, numbers, vectors and a logical # values. list_data <- list("Red", "Green", c(21,32,11), TRUE, 51.23, 119.1) print(list_data) When we execute the above code, it produces the following result − [[1]] [1] "Red" [[2]] [1] "Green" [[3]] [1] 21 32 11 [[4]] [1] TRUE [[5]] [1] 51.23 [[6]] [1] 119.1 The list elements can be given names and they can be accessed using these names. # Create a list containing a vector, a matrix and a list. list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2), list("green",12.3)) # Give names to the elements in the list. names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list") # Show the list. print(list_data) When we execute the above code, it produces the following result − $`1st_Quarter` [1] "Jan" "Feb" "Mar" $A_Matrix [,1] [,2] [,3] [1,] 3 5 -2 [2,] 9 1 8 $A_Inner_list $A_Inner_list[[1]] [1] "green" $A_Inner_list[[2]] [1] 12.3 Elements of the list can be accessed by the index of the element in the list. In case of named lists it can also be accessed using the names. We continue to use the list in the above example − # Create a list containing a vector, a matrix and a list. list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2), list("green",12.3)) # Give names to the elements in the list. names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list") # Access the first element of the list. print(list_data[1]) # Access the thrid element. As it is also a list, all its elements will be printed. print(list_data[3]) # Access the list element using the name of the element. print(list_data$A_Matrix) When we execute the above code, it produces the following result − $`1st_Quarter` [1] "Jan" "Feb" "Mar" $A_Inner_list $A_Inner_list[[1]] [1] "green" $A_Inner_list[[2]] [1] 12.3 [,1] [,2] [,3] [1,] 3 5 -2 [2,] 9 1 8 We can add, delete and update list elements as shown below. We can add and delete elements only at the end of a list. But we can update any element. # Create a list containing a vector, a matrix and a list. list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2), list("green",12.3)) # Give names to the elements in the list. names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list") # Add element at the end of the list. list_data[4] <- "New element" print(list_data[4]) # Remove the last element. list_data[4] <- NULL # Print the 4th Element. print(list_data[4]) # Update the 3rd Element. list_data[3] <- "updated element" print(list_data[3]) When we execute the above code, it produces the following result − [[1]] [1] "New element" $<NA> NULL $`A Inner list` [1] "updated element" You can merge many lists into one list by placing all the lists inside one list() function. # Create two lists. list1 <- list(1,2,3) list2 <- list("Sun","Mon","Tue") # Merge the two lists. merged.list <- c(list1,list2) # Print the merged list. print(merged.list) When we execute the above code, it produces the following result − [[1]] [1] 1 [[2]] [1] 2 [[3]] [1] 3 [[4]] [1] "Sun" [[5]] [1] "Mon" [[6]] [1] "Tue" A list can be converted to a vector so that the elements of the vector can be used for further manipulation. All the arithmetic operations on vectors can be applied after the list is converted into vectors. To do this conversion, we use the unlist() function. It takes the list as input and produces a vector. # Create lists. list1 <- list(1:5) print(list1) list2 <-list(10:14) print(list2) # Convert the lists to vectors. v1 <- unlist(list1) v2 <- unlist(list2) print(v1) print(v2) # Now add the vectors result <- v1+v2 print(result) When we execute the above code, it produces the following result − [[1]] [1] 1 2 3 4 5 [[1]] [1] 10 11 12 13 14 [1] 1 2 3 4 5 [1] 10 11 12 13 14 [1] 11 13 15 17 19 Matrices are the R objects in which the elements are arranged in a two-dimensional rectangular layout. They contain elements of the same atomic types. Though we can create a matrix containing only characters or only logical values, they are not of much use. We use matrices containing numeric elements to be used in mathematical calculations. A Matrix is created using the matrix() function. The basic syntax for creating a matrix in R is − matrix(data, nrow, ncol, byrow, dimnames) Following is the description of the parameters used − data is the input vector which becomes the data elements of the matrix. data is the input vector which becomes the data elements of the matrix. nrow is the number of rows to be created. nrow is the number of rows to be created. ncol is the number of columns to be created. ncol is the number of columns to be created. byrow is a logical clue. If TRUE then the input vector elements are arranged by row. byrow is a logical clue. If TRUE then the input vector elements are arranged by row. dimname is the names assigned to the rows and columns. dimname is the names assigned to the rows and columns. Create a matrix taking a vector of numbers as input. # Elements are arranged sequentially by row. M <- matrix(c(3:14), nrow = 4, byrow = TRUE) print(M) # Elements are arranged sequentially by column. N <- matrix(c(3:14), nrow = 4, byrow = FALSE) print(N) # Define the column and row names. rownames = c("row1", "row2", "row3", "row4") colnames = c("col1", "col2", "col3") P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames)) print(P) When we execute the above code, it produces the following result − [,1] [,2] [,3] [1,] 3 4 5 [2,] 6 7 8 [3,] 9 10 11 [4,] 12 13 14 [,1] [,2] [,3] [1,] 3 7 11 [2,] 4 8 12 [3,] 5 9 13 [4,] 6 10 14 col1 col2 col3 row1 3 4 5 row2 6 7 8 row3 9 10 11 row4 12 13 14 Elements of a matrix can be accessed by using the column and row index of the element. We consider the matrix P above to find the specific elements below. # Define the column and row names. rownames = c("row1", "row2", "row3", "row4") colnames = c("col1", "col2", "col3") # Create the matrix. P <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames)) # Access the element at 3rd column and 1st row. print(P[1,3]) # Access the element at 2nd column and 4th row. print(P[4,2]) # Access only the 2nd row. print(P[2,]) # Access only the 3rd column. print(P[,3]) When we execute the above code, it produces the following result − [1] 5 [1] 13 col1 col2 col3 6 7 8 row1 row2 row3 row4 5 8 11 14 Various mathematical operations are performed on the matrices using the R operators. The result of the operation is also a matrix. The dimensions (number of rows and columns) should be same for the matrices involved in the operation. # Create two 2x3 matrices. matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2) print(matrix1) matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2) print(matrix2) # Add the matrices. result <- matrix1 + matrix2 cat("Result of addition","\n") print(result) # Subtract the matrices result <- matrix1 - matrix2 cat("Result of subtraction","\n") print(result) When we execute the above code, it produces the following result − [,1] [,2] [,3] [1,] 3 -1 2 [2,] 9 4 6 [,1] [,2] [,3] [1,] 5 0 3 [2,] 2 9 4 Result of addition [,1] [,2] [,3] [1,] 8 -1 5 [2,] 11 13 10 Result of subtraction [,1] [,2] [,3] [1,] -2 -1 -1 [2,] 7 -5 2 # Create two 2x3 matrices. matrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2) print(matrix1) matrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2) print(matrix2) # Multiply the matrices. result <- matrix1 * matrix2 cat("Result of multiplication","\n") print(result) # Divide the matrices result <- matrix1 / matrix2 cat("Result of division","\n") print(result) When we execute the above code, it produces the following result − [,1] [,2] [,3] [1,] 3 -1 2 [2,] 9 4 6 [,1] [,2] [,3] [1,] 5 0 3 [2,] 2 9 4 Result of multiplication [,1] [,2] [,3] [1,] 15 0 6 [2,] 18 36 24 Result of division [,1] [,2] [,3] [1,] 0.6 -Inf 0.6666667 [2,] 4.5 0.4444444 1.5000000 Arrays are the R data objects which can store data in more than two dimensions. For example − If we create an array of dimension (2, 3, 4) then it creates 4 rectangular matrices each with 2 rows and 3 columns. Arrays can store only data type. An array is created using the array() function. It takes vectors as input and uses the values in the dim parameter to create an array. The following example creates an array of two 3x3 matrices each with 3 rows and 3 columns. # Create two vectors of different lengths. vector1 <- c(5,9,3) vector2 <- c(10,11,12,13,14,15) # Take these vectors as input to the array. result <- array(c(vector1,vector2),dim = c(3,3,2)) print(result) When we execute the above code, it produces the following result − , , 1 [,1] [,2] [,3] [1,] 5 10 13 [2,] 9 11 14 [3,] 3 12 15 , , 2 [,1] [,2] [,3] [1,] 5 10 13 [2,] 9 11 14 [3,] 3 12 15 We can give names to the rows, columns and matrices in the array by using the dimnames parameter. # Create two vectors of different lengths. vector1 <- c(5,9,3) vector2 <- c(10,11,12,13,14,15) column.names <- c("COL1","COL2","COL3") row.names <- c("ROW1","ROW2","ROW3") matrix.names <- c("Matrix1","Matrix2") # Take these vectors as input to the array. result <- array(c(vector1,vector2),dim = c(3,3,2),dimnames = list(row.names,column.names, matrix.names)) print(result) When we execute the above code, it produces the following result − , , Matrix1 COL1 COL2 COL3 ROW1 5 10 13 ROW2 9 11 14 ROW3 3 12 15 , , Matrix2 COL1 COL2 COL3 ROW1 5 10 13 ROW2 9 11 14 ROW3 3 12 15 # Create two vectors of different lengths. vector1 <- c(5,9,3) vector2 <- c(10,11,12,13,14,15) column.names <- c("COL1","COL2","COL3") row.names <- c("ROW1","ROW2","ROW3") matrix.names <- c("Matrix1","Matrix2") # Take these vectors as input to the array. result <- array(c(vector1,vector2),dim = c(3,3,2),dimnames = list(row.names, column.names, matrix.names)) # Print the third row of the second matrix of the array. print(result[3,,2]) # Print the element in the 1st row and 3rd column of the 1st matrix. print(result[1,3,1]) # Print the 2nd Matrix. print(result[,,2]) When we execute the above code, it produces the following result − COL1 COL2 COL3 3 12 15 [1] 13 COL1 COL2 COL3 ROW1 5 10 13 ROW2 9 11 14 ROW3 3 12 15 As array is made up matrices in multiple dimensions, the operations on elements of array are carried out by accessing elements of the matrices. # Create two vectors of different lengths. vector1 <- c(5,9,3) vector2 <- c(10,11,12,13,14,15) # Take these vectors as input to the array. array1 <- array(c(vector1,vector2),dim = c(3,3,2)) # Create two vectors of different lengths. vector3 <- c(9,1,0) vector4 <- c(6,0,11,3,14,1,2,6,9) array2 <- array(c(vector1,vector2),dim = c(3,3,2)) # create matrices from these arrays. matrix1 <- array1[,,2] matrix2 <- array2[,,2] # Add the matrices. result <- matrix1+matrix2 print(result) When we execute the above code, it produces the following result − [,1] [,2] [,3] [1,] 10 20 26 [2,] 18 22 28 [3,] 6 24 30 We can do calculations across the elements in an array using the apply() function. apply(x, margin, fun) Following is the description of the parameters used − x is an array. x is an array. margin is the name of the data set used. margin is the name of the data set used. fun is the function to be applied across the elements of the array. fun is the function to be applied across the elements of the array. We use the apply() function below to calculate the sum of the elements in the rows of an array across all the matrices. # Create two vectors of different lengths. vector1 <- c(5,9,3) vector2 <- c(10,11,12,13,14,15) # Take these vectors as input to the array. new.array <- array(c(vector1,vector2),dim = c(3,3,2)) print(new.array) # Use apply to calculate the sum of the rows across all the matrices. result <- apply(new.array, c(1), sum) print(result) When we execute the above code, it produces the following result − , , 1 [,1] [,2] [,3] [1,] 5 10 13 [2,] 9 11 14 [3,] 3 12 15 , , 2 [,1] [,2] [,3] [1,] 5 10 13 [2,] 9 11 14 [3,] 3 12 15 [1] 56 68 60 Factors are the data objects which are used to categorize the data and store it as levels. They can store both strings and integers. They are useful in the columns which have a limited number of unique values. Like "Male, "Female" and True, False etc. They are useful in data analysis for statistical modeling. Factors are created using the factor () function by taking a vector as input. # Create a vector as input. data <- c("East","West","East","North","North","East","West","West","West","East","North") print(data) print(is.factor(data)) # Apply the factor function. factor_data <- factor(data) print(factor_data) print(is.factor(factor_data)) When we execute the above code, it produces the following result − [1] "East" "West" "East" "North" "North" "East" "West" "West" "West" "East" "North" [1] FALSE [1] East West East North North East West West West East North Levels: East North West [1] TRUE On creating any data frame with a column of text data, R treats the text column as categorical data and creates factors on it. # Create the vectors for data frame. height <- c(132,151,162,139,166,147,122) weight <- c(48,49,66,53,67,52,40) gender <- c("male","male","female","female","male","female","male") # Create the data frame. input_data <- data.frame(height,weight,gender) print(input_data) # Test if the gender column is a factor. print(is.factor(input_data$gender)) # Print the gender column so see the levels. print(input_data$gender) When we execute the above code, it produces the following result − height weight gender 1 132 48 male 2 151 49 male 3 162 66 female 4 139 53 female 5 166 67 male 6 147 52 female 7 122 40 male [1] TRUE [1] male male female female male female male Levels: female male The order of the levels in a factor can be changed by applying the factor function again with new order of the levels. data <- c("East","West","East","North","North","East","West", "West","West","East","North") # Create the factors factor_data <- factor(data) print(factor_data) # Apply the factor function with required order of the level. new_order_data <- factor(factor_data,levels = c("East","West","North")) print(new_order_data) When we execute the above code, it produces the following result − [1] East West East North North East West West West East North Levels: East North West [1] East West East North North East West West West East North Levels: East West North We can generate factor levels by using the gl() function. It takes two integers as input which indicates how many levels and how many times each level. gl(n, k, labels) Following is the description of the parameters used − n is a integer giving the number of levels. n is a integer giving the number of levels. k is a integer giving the number of replications. k is a integer giving the number of replications. labels is a vector of labels for the resulting factor levels. labels is a vector of labels for the resulting factor levels. v <- gl(3, 4, labels = c("Tampa", "Seattle","Boston")) print(v) When we execute the above code, it produces the following result − Tampa Tampa Tampa Tampa Seattle Seattle Seattle Seattle Boston [10] Boston Boston Boston Levels: Tampa Seattle Boston A data frame is a table or a two-dimensional array-like structure in which each column contains values of one variable and each row contains one set of values from each column. Following are the characteristics of a data frame. The column names should be non-empty. The row names should be unique. The data stored in a data frame can be of numeric, factor or character type. Each column should contain same number of data items. # Create the data frame. emp.data <- data.frame( emp_id = c (1:5), emp_name = c("Rick","Dan","Michelle","Ryan","Gary"), salary = c(623.3,515.2,611.0,729.0,843.25), start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11", "2015-03-27")), stringsAsFactors = FALSE ) # Print the data frame. print(emp.data) When we execute the above code, it produces the following result − emp_id emp_name salary start_date 1 1 Rick 623.30 2012-01-01 2 2 Dan 515.20 2013-09-23 3 3 Michelle 611.00 2014-11-15 4 4 Ryan 729.00 2014-05-11 5 5 Gary 843.25 2015-03-27 The structure of the data frame can be seen by using str() function. # Create the data frame. emp.data <- data.frame( emp_id = c (1:5), emp_name = c("Rick","Dan","Michelle","Ryan","Gary"), salary = c(623.3,515.2,611.0,729.0,843.25), start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11", "2015-03-27")), stringsAsFactors = FALSE ) # Get the structure of the data frame. str(emp.data) When we execute the above code, it produces the following result − 'data.frame': 5 obs. of 4 variables: $ emp_id : int 1 2 3 4 5 $ emp_name : chr "Rick" "Dan" "Michelle" "Ryan" ... $ salary : num 623 515 611 729 843 $ start_date: Date, format: "2012-01-01" "2013-09-23" "2014-11-15" "2014-05-11" ... The statistical summary and nature of the data can be obtained by applying summary() function. # Create the data frame. emp.data <- data.frame( emp_id = c (1:5), emp_name = c("Rick","Dan","Michelle","Ryan","Gary"), salary = c(623.3,515.2,611.0,729.0,843.25), start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11", "2015-03-27")), stringsAsFactors = FALSE ) # Print the summary. print(summary(emp.data)) When we execute the above code, it produces the following result − emp_id emp_name salary start_date Min. :1 Length:5 Min. :515.2 Min. :2012-01-01 1st Qu.:2 Class :character 1st Qu.:611.0 1st Qu.:2013-09-23 Median :3 Mode :character Median :623.3 Median :2014-05-11 Mean :3 Mean :664.4 Mean :2014-01-14 3rd Qu.:4 3rd Qu.:729.0 3rd Qu.:2014-11-15 Max. :5 Max. :843.2 Max. :2015-03-27 Extract specific column from a data frame using column name. # Create the data frame. emp.data <- data.frame( emp_id = c (1:5), emp_name = c("Rick","Dan","Michelle","Ryan","Gary"), salary = c(623.3,515.2,611.0,729.0,843.25), start_date = as.Date(c("2012-01-01","2013-09-23","2014-11-15","2014-05-11", "2015-03-27")), stringsAsFactors = FALSE ) # Extract Specific columns. result <- data.frame(emp.data$emp_name,emp.data$salary) print(result) When we execute the above code, it produces the following result − emp.data.emp_name emp.data.salary 1 Rick 623.30 2 Dan 515.20 3 Michelle 611.00 4 Ryan 729.00 5 Gary 843.25 Extract the first two rows and then all columns # Create the data frame. emp.data <- data.frame( emp_id = c (1:5), emp_name = c("Rick","Dan","Michelle","Ryan","Gary"), salary = c(623.3,515.2,611.0,729.0,843.25), start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11", "2015-03-27")), stringsAsFactors = FALSE ) # Extract first two rows. result <- emp.data[1:2,] print(result) When we execute the above code, it produces the following result − emp_id emp_name salary start_date 1 1 Rick 623.3 2012-01-01 2 2 Dan 515.2 2013-09-23 Extract 3rd and 5th row with 2nd and 4th column # Create the data frame. emp.data <- data.frame( emp_id = c (1:5), emp_name = c("Rick","Dan","Michelle","Ryan","Gary"), salary = c(623.3,515.2,611.0,729.0,843.25), start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11", "2015-03-27")), stringsAsFactors = FALSE ) # Extract 3rd and 5th row with 2nd and 4th column. result <- emp.data[c(3,5),c(2,4)] print(result) When we execute the above code, it produces the following result − emp_name start_date 3 Michelle 2014-11-15 5 Gary 2015-03-27 A data frame can be expanded by adding columns and rows. Just add the column vector using a new column name. # Create the data frame. emp.data <- data.frame( emp_id = c (1:5), emp_name = c("Rick","Dan","Michelle","Ryan","Gary"), salary = c(623.3,515.2,611.0,729.0,843.25), start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11", "2015-03-27")), stringsAsFactors = FALSE ) # Add the "dept" coulmn. emp.data$dept <- c("IT","Operations","IT","HR","Finance") v <- emp.data print(v) When we execute the above code, it produces the following result − emp_id emp_name salary start_date dept 1 1 Rick 623.30 2012-01-01 IT 2 2 Dan 515.20 2013-09-23 Operations 3 3 Michelle 611.00 2014-11-15 IT 4 4 Ryan 729.00 2014-05-11 HR 5 5 Gary 843.25 2015-03-27 Finance To add more rows permanently to an existing data frame, we need to bring in the new rows in the same structure as the existing data frame and use the rbind() function. In the example below we create a data frame with new rows and merge it with the existing data frame to create the final data frame. # Create the first data frame. emp.data <- data.frame( emp_id = c (1:5), emp_name = c("Rick","Dan","Michelle","Ryan","Gary"), salary = c(623.3,515.2,611.0,729.0,843.25), start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11", "2015-03-27")), dept = c("IT","Operations","IT","HR","Finance"), stringsAsFactors = FALSE ) # Create the second data frame emp.newdata <- data.frame( emp_id = c (6:8), emp_name = c("Rasmi","Pranab","Tusar"), salary = c(578.0,722.5,632.8), start_date = as.Date(c("2013-05-21","2013-07-30","2014-06-17")), dept = c("IT","Operations","Fianance"), stringsAsFactors = FALSE ) # Bind the two data frames. emp.finaldata <- rbind(emp.data,emp.newdata) print(emp.finaldata) When we execute the above code, it produces the following result − emp_id emp_name salary start_date dept 1 1 Rick 623.30 2012-01-01 IT 2 2 Dan 515.20 2013-09-23 Operations 3 3 Michelle 611.00 2014-11-15 IT 4 4 Ryan 729.00 2014-05-11 HR 5 5 Gary 843.25 2015-03-27 Finance 6 6 Rasmi 578.00 2013-05-21 IT 7 7 Pranab 722.50 2013-07-30 Operations 8 8 Tusar 632.80 2014-06-17 Fianance R packages are a collection of R functions, complied code and sample data. They are stored under a directory called "library" in the R environment. By default, R installs a set of packages during installation. More packages are added later, when they are needed for some specific purpose. When we start the R console, only the default packages are available by default. Other packages which are already installed have to be loaded explicitly to be used by the R program that is going to use them. All the packages available in R language are listed at R Packages. Below is a list of commands to be used to check, verify and use the R packages. Get library locations containing R packages .libPaths() When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc. [2] "C:/Program Files/R/R-3.2.2/library" library() When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc. Packages in library ‘C:/Program Files/R/R-3.2.2/library’: base The R Base Package boot Bootstrap Functions (Originally by Angelo Canty for S) class Functions for Classification cluster "Finding Groups in Data": Cluster Analysis Extended Rousseeuw et al. codetools Code Analysis Tools for R compiler The R Compiler Package datasets The R Datasets Package foreign Read Data Stored by 'Minitab', 'S', 'SAS', 'SPSS', 'Stata', 'Systat', 'Weka', 'dBase', ... graphics The R Graphics Package grDevices The R Graphics Devices and Support for Colours and Fonts grid The Grid Graphics Package KernSmooth Functions for Kernel Smoothing Supporting Wand & Jones (1995) lattice Trellis Graphics for R MASS Support Functions and Datasets for Venables and Ripley's MASS Matrix Sparse and Dense Matrix Classes and Methods methods Formal Methods and Classes mgcv Mixed GAM Computation Vehicle with GCV/AIC/REML Smoothness Estimation nlme Linear and Nonlinear Mixed Effects Models nnet Feed-Forward Neural Networks and Multinomial Log-Linear Models parallel Support for Parallel computation in R rpart Recursive Partitioning and Regression Trees spatial Functions for Kriging and Point Pattern Analysis splines Regression Spline Functions and Classes stats The R Stats Package stats4 Statistical Functions using S4 Classes survival Survival Analysis tcltk Tcl/Tk Interface tools Tools for Package Development utils The R Utils Package Get all packages currently loaded in the R environment search() When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc. [1] ".GlobalEnv" "package:stats" "package:graphics" [4] "package:grDevices" "package:utils" "package:datasets" [7] "package:methods" "Autoloads" "package:base" There are two ways to add new R packages. One is installing directly from the CRAN directory and another is downloading the package to your local system and installing it manually. The following command gets the packages directly from CRAN webpage and installs the package in the R environment. You may be prompted to choose a nearest mirror. Choose the one appropriate to your location. install.packages("Package Name") # Install the package named "XML". install.packages("XML") Go to the link R Packages to download the package needed. Save the package as a .zip file in a suitable location in the local system. Now you can run the following command to install this package in the R environment. install.packages(file_name_with_path, repos = NULL, type = "source") # Install the package named "XML" install.packages("E:/XML_3.98-1.3.zip", repos = NULL, type = "source") Before a package can be used in the code, it must be loaded to the current R environment. You also need to load a package that is already installed previously but not available in the current environment. A package is loaded using the following command − library("package Name", lib.loc = "path to library") # Load the package named "XML" install.packages("E:/XML_3.98-1.3.zip", repos = NULL, type = "source") Data Reshaping in R is about changing the way data is organized into rows and columns. Most of the time data processing in R is done by taking the input data as a data frame. It is easy to extract data from the rows and columns of a data frame but there are situations when we need the data frame in a format that is different from format in which we received it. R has many functions to split, merge and change the rows to columns and vice-versa in a data frame. We can join multiple vectors to create a data frame using the cbind()function. Also we can merge two data frames using rbind() function. # Create vector objects. city <- c("Tampa","Seattle","Hartford","Denver") state <- c("FL","WA","CT","CO") zipcode <- c(33602,98104,06161,80294) # Combine above three vectors into one data frame. addresses <- cbind(city,state,zipcode) # Print a header. cat("# # # # The First data frame\n") # Print the data frame. print(addresses) # Create another data frame with similar columns new.address <- data.frame( city = c("Lowry","Charlotte"), state = c("CO","FL"), zipcode = c("80230","33949"), stringsAsFactors = FALSE ) # Print a header. cat("# # # The Second data frame\n") # Print the data frame. print(new.address) # Combine rows form both the data frames. all.addresses <- rbind(addresses,new.address) # Print a header. cat("# # # The combined data frame\n") # Print the result. print(all.addresses) When we execute the above code, it produces the following result − # # # # The First data frame city state zipcode [1,] "Tampa" "FL" "33602" [2,] "Seattle" "WA" "98104" [3,] "Hartford" "CT" "6161" [4,] "Denver" "CO" "80294" # # # The Second data frame city state zipcode 1 Lowry CO 80230 2 Charlotte FL 33949 # # # The combined data frame city state zipcode 1 Tampa FL 33602 2 Seattle WA 98104 3 Hartford CT 6161 4 Denver CO 80294 5 Lowry CO 80230 6 Charlotte FL 33949 We can merge two data frames by using the merge() function. The data frames must have same column names on which the merging happens. In the example below, we consider the data sets about Diabetes in Pima Indian Women available in the library names "MASS". we merge the two data sets based on the values of blood pressure("bp") and body mass index("bmi"). On choosing these two columns for merging, the records where values of these two variables match in both data sets are combined together to form a single data frame. library(MASS) merged.Pima <- merge(x = Pima.te, y = Pima.tr, by.x = c("bp", "bmi"), by.y = c("bp", "bmi") ) print(merged.Pima) nrow(merged.Pima) When we execute the above code, it produces the following result − bp bmi npreg.x glu.x skin.x ped.x age.x type.x npreg.y glu.y skin.y ped.y 1 60 33.8 1 117 23 0.466 27 No 2 125 20 0.088 2 64 29.7 2 75 24 0.370 33 No 2 100 23 0.368 3 64 31.2 5 189 33 0.583 29 Yes 3 158 13 0.295 4 64 33.2 4 117 27 0.230 24 No 1 96 27 0.289 5 66 38.1 3 115 39 0.150 28 No 1 114 36 0.289 6 68 38.5 2 100 25 0.324 26 No 7 129 49 0.439 7 70 27.4 1 116 28 0.204 21 No 0 124 20 0.254 8 70 33.1 4 91 32 0.446 22 No 9 123 44 0.374 9 70 35.4 9 124 33 0.282 34 No 6 134 23 0.542 10 72 25.6 1 157 21 0.123 24 No 4 99 17 0.294 11 72 37.7 5 95 33 0.370 27 No 6 103 32 0.324 12 74 25.9 9 134 33 0.460 81 No 8 126 38 0.162 13 74 25.9 1 95 21 0.673 36 No 8 126 38 0.162 14 78 27.6 5 88 30 0.258 37 No 6 125 31 0.565 15 78 27.6 10 122 31 0.512 45 No 6 125 31 0.565 16 78 39.4 2 112 50 0.175 24 No 4 112 40 0.236 17 88 34.5 1 117 24 0.403 40 Yes 4 127 11 0.598 age.y type.y 1 31 No 2 21 No 3 24 No 4 21 No 5 21 No 6 43 Yes 7 36 Yes 8 40 No 9 29 Yes 10 28 No 11 55 No 12 39 No 13 39 No 14 49 Yes 15 49 Yes 16 38 No 17 28 No [1] 17 One of the most interesting aspects of R programming is about changing the shape of the data in multiple steps to get a desired shape. The functions used to do this are called melt() and cast(). We consider the dataset called ships present in the library called "MASS". library(MASS) print(ships) When we execute the above code, it produces the following result − type year period service incidents 1 A 60 60 127 0 2 A 60 75 63 0 3 A 65 60 1095 3 4 A 65 75 1095 4 5 A 70 60 1512 6 ............. ............. 8 A 75 75 2244 11 9 B 60 60 44882 39 10 B 60 75 17176 29 11 B 65 60 28609 58 ............ ............ 17 C 60 60 1179 1 18 C 60 75 552 1 19 C 65 60 781 0 ............ ............ Now we melt the data to organize it, converting all columns other than type and year into multiple rows. molten.ships <- melt(ships, id = c("type","year")) print(molten.ships) When we execute the above code, it produces the following result − type year variable value 1 A 60 period 60 2 A 60 period 75 3 A 65 period 60 4 A 65 period 75 ............ ............ 9 B 60 period 60 10 B 60 period 75 11 B 65 period 60 12 B 65 period 75 13 B 70 period 60 ........... ........... 41 A 60 service 127 42 A 60 service 63 43 A 65 service 1095 ........... ........... 70 D 70 service 1208 71 D 75 service 0 72 D 75 service 2051 73 E 60 service 45 74 E 60 service 0 75 E 65 service 789 ........... ........... 101 C 70 incidents 6 102 C 70 incidents 2 103 C 75 incidents 0 104 C 75 incidents 1 105 D 60 incidents 0 106 D 60 incidents 0 ........... ........... We can cast the molten data into a new form where the aggregate of each type of ship for each year is created. It is done using the cast() function. recasted.ship <- cast(molten.ships, type+year~variable,sum) print(recasted.ship) When we execute the above code, it produces the following result − type year period service incidents 1 A 60 135 190 0 2 A 65 135 2190 7 3 A 70 135 4865 24 4 A 75 135 2244 11 5 B 60 135 62058 68 6 B 65 135 48979 111 7 B 70 135 20163 56 8 B 75 135 7117 18 9 C 60 135 1731 2 10 C 65 135 1457 1 11 C 70 135 2731 8 12 C 75 135 274 1 13 D 60 135 356 0 14 D 65 135 480 0 15 D 70 135 1557 13 16 D 75 135 2051 4 17 E 60 135 45 0 18 E 65 135 1226 14 19 E 70 135 3318 17 20 E 75 135 542 1 In R, we can read data from files stored outside the R environment. We can also write data into files which will be stored and accessed by the operating system. R can read and write into various file formats like csv, excel, xml etc. In this chapter we will learn to read data from a csv file and then write data into a csv file. The file should be present in current working directory so that R can read it. Of course we can also set our own directory and read files from there. You can check which directory the R workspace is pointing to using the getwd() function. You can also set a new working directory using setwd()function. # Get and print current working directory. print(getwd()) # Set current working directory. setwd("/web/com") # Get and print current working directory. print(getwd()) When we execute the above code, it produces the following result − [1] "/web/com/1441086124_2016" [1] "/web/com" This result depends on your OS and your current directory where you are working. The csv file is a text file in which the values in the columns are separated by a comma. Let's consider the following data present in the file named input.csv. You can create this file using windows notepad by copying and pasting this data. Save the file as input.csv using the save As All files(*.*) option in notepad. id,name,salary,start_date,dept 1,Rick,623.3,2012-01-01,IT 2,Dan,515.2,2013-09-23,Operations 3,Michelle,611,2014-11-15,IT 4,Ryan,729,2014-05-11,HR 5,Gary,843.25,2015-03-27,Finance 6,Nina,578,2013-05-21,IT 7,Simon,632.8,2013-07-30,Operations 8,Guru,722.5,2014-06-17,Finance Following is a simple example of read.csv() function to read a CSV file available in your current working directory − data <- read.csv("input.csv") print(data) When we execute the above code, it produces the following result − id, name, salary, start_date, dept 1 1 Rick 623.30 2012-01-01 IT 2 2 Dan 515.20 2013-09-23 Operations 3 3 Michelle 611.00 2014-11-15 IT 4 4 Ryan 729.00 2014-05-11 HR 5 NA Gary 843.25 2015-03-27 Finance 6 6 Nina 578.00 2013-05-21 IT 7 7 Simon 632.80 2013-07-30 Operations 8 8 Guru 722.50 2014-06-17 Finance By default the read.csv() function gives the output as a data frame. This can be easily checked as follows. Also we can check the number of columns and rows. data <- read.csv("input.csv") print(is.data.frame(data)) print(ncol(data)) print(nrow(data)) When we execute the above code, it produces the following result − [1] TRUE [1] 5 [1] 8 Once we read data in a data frame, we can apply all the functions applicable to data frames as explained in subsequent section. # Create a data frame. data <- read.csv("input.csv") # Get the max salary from data frame. sal <- max(data$salary) print(sal) When we execute the above code, it produces the following result − [1] 843.25 We can fetch rows meeting specific filter criteria similar to a SQL where clause. # Create a data frame. data <- read.csv("input.csv") # Get the max salary from data frame. sal <- max(data$salary) # Get the person detail having max salary. retval <- subset(data, salary == max(salary)) print(retval) When we execute the above code, it produces the following result − id name salary start_date dept 5 NA Gary 843.25 2015-03-27 Finance # Create a data frame. data <- read.csv("input.csv") retval <- subset( data, dept == "IT") print(retval) When we execute the above code, it produces the following result − id name salary start_date dept 1 1 Rick 623.3 2012-01-01 IT 3 3 Michelle 611.0 2014-11-15 IT 6 6 Nina 578.0 2013-05-21 IT # Create a data frame. data <- read.csv("input.csv") info <- subset(data, salary > 600 & dept == "IT") print(info) When we execute the above code, it produces the following result − id name salary start_date dept 1 1 Rick 623.3 2012-01-01 IT 3 3 Michelle 611.0 2014-11-15 IT # Create a data frame. data <- read.csv("input.csv") retval <- subset(data, as.Date(start_date) > as.Date("2014-01-01")) print(retval) When we execute the above code, it produces the following result − id name salary start_date dept 3 3 Michelle 611.00 2014-11-15 IT 4 4 Ryan 729.00 2014-05-11 HR 5 NA Gary 843.25 2015-03-27 Finance 8 8 Guru 722.50 2014-06-17 Finance R can create csv file form existing data frame. The write.csv() function is used to create the csv file. This file gets created in the working directory. # Create a data frame. data <- read.csv("input.csv") retval <- subset(data, as.Date(start_date) > as.Date("2014-01-01")) # Write filtered data into a new file. write.csv(retval,"output.csv") newdata <- read.csv("output.csv") print(newdata) When we execute the above code, it produces the following result − X id name salary start_date dept 1 3 3 Michelle 611.00 2014-11-15 IT 2 4 4 Ryan 729.00 2014-05-11 HR 3 5 NA Gary 843.25 2015-03-27 Finance 4 8 8 Guru 722.50 2014-06-17 Finance Here the column X comes from the data set newper. This can be dropped using additional parameters while writing the file. # Create a data frame. data <- read.csv("input.csv") retval <- subset(data, as.Date(start_date) > as.Date("2014-01-01")) # Write filtered data into a new file. write.csv(retval,"output.csv", row.names = FALSE) newdata <- read.csv("output.csv") print(newdata) When we execute the above code, it produces the following result − id name salary start_date dept 1 3 Michelle 611.00 2014-11-15 IT 2 4 Ryan 729.00 2014-05-11 HR 3 NA Gary 843.25 2015-03-27 Finance 4 8 Guru 722.50 2014-06-17 Finance Microsoft Excel is the most widely used spreadsheet program which stores data in the .xls or .xlsx format. R can read directly from these files using some excel specific packages. Few such packages are - XLConnect, xlsx, gdata etc. We will be using xlsx package. R can also write into excel file using this package. You can use the following command in the R console to install the "xlsx" package. It may ask to install some additional packages on which this package is dependent. Follow the same command with required package name to install the additional packages. install.packages("xlsx") Use the following command to verify and load the "xlsx" package. # Verify the package is installed. any(grepl("xlsx",installed.packages())) # Load the library into R workspace. library("xlsx") When the script is run we get the following output. [1] TRUE Loading required package: rJava Loading required package: methods Loading required package: xlsxjars Open Microsoft excel. Copy and paste the following data in the work sheet named as sheet1. id name salary start_date dept 1 Rick 623.3 1/1/2012 IT 2 Dan 515.2 9/23/2013 Operations 3 Michelle 611 11/15/2014 IT 4 Ryan 729 5/11/2014 HR 5 Gary 43.25 3/27/2015 Finance 6 Nina 578 5/21/2013 IT 7 Simon 632.8 7/30/2013 Operations 8 Guru 722.5 6/17/2014 Finance Also copy and paste the following data to another worksheet and rename this worksheet to "city". name city Rick Seattle Dan Tampa Michelle Chicago Ryan Seattle Gary Houston Nina Boston Simon Mumbai Guru Dallas Save the Excel file as "input.xlsx". You should save it in the current working directory of the R workspace. The input.xlsx is read by using the read.xlsx() function as shown below. The result is stored as a data frame in the R environment. # Read the first worksheet in the file input.xlsx. data <- read.xlsx("input.xlsx", sheetIndex = 1) print(data) When we execute the above code, it produces the following result − id, name, salary, start_date, dept 1 1 Rick 623.30 2012-01-01 IT 2 2 Dan 515.20 2013-09-23 Operations 3 3 Michelle 611.00 2014-11-15 IT 4 4 Ryan 729.00 2014-05-11 HR 5 NA Gary 843.25 2015-03-27 Finance 6 6 Nina 578.00 2013-05-21 IT 7 7 Simon 632.80 2013-07-30 Operations 8 8 Guru 722.50 2014-06-17 Finance A binary file is a file that contains information stored only in form of bits and bytes.(0’s and 1’s). They are not human readable as the bytes in it translate to characters and symbols which contain many other non-printable characters. Attempting to read a binary file using any text editor will show characters like Ø and ð. The binary file has to be read by specific programs to be useable. For example, the binary file of a Microsoft Word program can be read to a human readable form only by the Word program. Which indicates that, besides the human readable text, there is a lot more information like formatting of characters and page numbers etc., which are also stored along with alphanumeric characters. And finally a binary file is a continuous sequence of bytes. The line break we see in a text file is a character joining first line to the next. Sometimes, the data generated by other programs are required to be processed by R as a binary file. Also R is required to create binary files which can be shared with other programs. R has two functions WriteBin() and readBin() to create and read binary files. writeBin(object, con) readBin(con, what, n ) Following is the description of the parameters used − con is the connection object to read or write the binary file. con is the connection object to read or write the binary file. object is the binary file which to be written. object is the binary file which to be written. what is the mode like character, integer etc. representing the bytes to be read. what is the mode like character, integer etc. representing the bytes to be read. n is the number of bytes to read from the binary file. n is the number of bytes to read from the binary file. We consider the R inbuilt data "mtcars". First we create a csv file from it and convert it to a binary file and store it as a OS file. Next we read this binary file created into R. We read the data frame "mtcars" as a csv file and then write it as a binary file to the OS. # Read the "mtcars" data frame as a csv file and store only the columns "cyl", "am" and "gear". write.table(mtcars, file = "mtcars.csv",row.names = FALSE, na = "", col.names = TRUE, sep = ",") # Store 5 records from the csv file as a new data frame. new.mtcars <- read.table("mtcars.csv",sep = ",",header = TRUE,nrows = 5) # Create a connection object to write the binary file using mode "wb". write.filename = file("/web/com/binmtcars.dat", "wb") # Write the column names of the data frame to the connection object. writeBin(colnames(new.mtcars), write.filename) # Write the records in each of the column to the file. writeBin(c(new.mtcars$cyl,new.mtcars$am,new.mtcars$gear), write.filename) # Close the file for writing so that it can be read by other program. close(write.filename) The binary file created above stores all the data as continuous bytes. So we will read it by choosing appropriate values of column names as well as the column values. # Create a connection object to read the file in binary mode using "rb". read.filename <- file("/web/com/binmtcars.dat", "rb") # First read the column names. n = 3 as we have 3 columns. column.names <- readBin(read.filename, character(), n = 3) # Next read the column values. n = 18 as we have 3 column names and 15 values. read.filename <- file("/web/com/binmtcars.dat", "rb") bindata <- readBin(read.filename, integer(), n = 18) # Print the data. print(bindata) # Read the values from 4th byte to 8th byte which represents "cyl". cyldata = bindata[4:8] print(cyldata) # Read the values form 9th byte to 13th byte which represents "am". amdata = bindata[9:13] print(amdata) # Read the values form 9th byte to 13th byte which represents "gear". geardata = bindata[14:18] print(geardata) # Combine all the read values to a dat frame. finaldata = cbind(cyldata, amdata, geardata) colnames(finaldata) = column.names print(finaldata) When we execute the above code, it produces the following result and chart − [1] 7108963 1728081249 7496037 6 6 4 [7] 6 8 1 1 1 0 [13] 0 4 4 4 3 3 [1] 6 6 4 6 8 [1] 1 1 1 0 0 [1] 4 4 4 3 3 cyl am gear [1,] 6 1 4 [2,] 6 1 4 [3,] 4 1 4 [4,] 6 0 3 [5,] 8 0 3 As we can see, we got the original data back by reading the binary file in R. XML is a file format which shares both the file format and the data on the World Wide Web, intranets, and elsewhere using standard ASCII text. It stands for Extensible Markup Language (XML). Similar to HTML it contains markup tags. But unlike HTML where the markup tag describes structure of the page, in xml the markup tags describe the meaning of the data contained into he file. You can read a xml file in R using the "XML" package. This package can be installed using following command. install.packages("XML") Create a XMl file by copying the below data into a text editor like notepad. Save the file with a .xml extension and choosing the file type as all files(*.*). <RECORDS> <EMPLOYEE> <ID>1</ID> <NAME>Rick</NAME> <SALARY>623.3</SALARY> <STARTDATE>1/1/2012</STARTDATE> <DEPT>IT</DEPT> </EMPLOYEE> <EMPLOYEE> <ID>2</ID> <NAME>Dan</NAME> <SALARY>515.2</SALARY> <STARTDATE>9/23/2013</STARTDATE> <DEPT>Operations</DEPT> </EMPLOYEE> <EMPLOYEE> <ID>3</ID> <NAME>Michelle</NAME> <SALARY>611</SALARY> <STARTDATE>11/15/2014</STARTDATE> <DEPT>IT</DEPT> </EMPLOYEE> <EMPLOYEE> <ID>4</ID> <NAME>Ryan</NAME> <SALARY>729</SALARY> <STARTDATE>5/11/2014</STARTDATE> <DEPT>HR</DEPT> </EMPLOYEE> <EMPLOYEE> <ID>5</ID> <NAME>Gary</NAME> <SALARY>843.25</SALARY> <STARTDATE>3/27/2015</STARTDATE> <DEPT>Finance</DEPT> </EMPLOYEE> <EMPLOYEE> <ID>6</ID> <NAME>Nina</NAME> <SALARY>578</SALARY> <STARTDATE>5/21/2013</STARTDATE> <DEPT>IT</DEPT> </EMPLOYEE> <EMPLOYEE> <ID>7</ID> <NAME>Simon</NAME> <SALARY>632.8</SALARY> <STARTDATE>7/30/2013</STARTDATE> <DEPT>Operations</DEPT> </EMPLOYEE> <EMPLOYEE> <ID>8</ID> <NAME>Guru</NAME> <SALARY>722.5</SALARY> <STARTDATE>6/17/2014</STARTDATE> <DEPT>Finance</DEPT> </EMPLOYEE> </RECORDS> The xml file is read by R using the function xmlParse(). It is stored as a list in R. # Load the package required to read XML files. library("XML") # Also load the other required package. library("methods") # Give the input file name to the function. result <- xmlParse(file = "input.xml") # Print the result. print(result) When we execute the above code, it produces the following result − 1 Rick 623.3 1/1/2012 IT 2 Dan 515.2 9/23/2013 Operations 3 Michelle 611 11/15/2014 IT 4 Ryan 729 5/11/2014 HR 5 Gary 843.25 3/27/2015 Finance 6 Nina 578 5/21/2013 IT 7 Simon 632.8 7/30/2013 Operations 8 Guru 722.5 6/17/2014 Finance # Load the packages required to read XML files. library("XML") library("methods") # Give the input file name to the function. result <- xmlParse(file = "input.xml") # Exract the root node form the xml file. rootnode <- xmlRoot(result) # Find number of nodes in the root. rootsize <- xmlSize(rootnode) # Print the result. print(rootsize) When we execute the above code, it produces the following result − output [1] 8 Let's look at the first record of the parsed file. It will give us an idea of the various elements present in the top level node. # Load the packages required to read XML files. library("XML") library("methods") # Give the input file name to the function. result <- xmlParse(file = "input.xml") # Exract the root node form the xml file. rootnode <- xmlRoot(result) # Print the result. print(rootnode[1]) When we execute the above code, it produces the following result − $EMPLOYEE 1 Rick 623.3 1/1/2012 IT attr(,"class") [1] "XMLInternalNodeList" "XMLNodeList" # Load the packages required to read XML files. library("XML") library("methods") # Give the input file name to the function. result <- xmlParse(file = "input.xml") # Exract the root node form the xml file. rootnode <- xmlRoot(result) # Get the first element of the first node. print(rootnode[[1]][[1]]) # Get the fifth element of the first node. print(rootnode[[1]][[5]]) # Get the second element of the third node. print(rootnode[[3]][[2]]) When we execute the above code, it produces the following result − 1 IT Michelle To handle the data effectively in large files we read the data in the xml file as a data frame. Then process the data frame for data analysis. # Load the packages required to read XML files. library("XML") library("methods") # Convert the input xml file to a data frame. xmldataframe <- xmlToDataFrame("input.xml") print(xmldataframe) When we execute the above code, it produces the following result − ID NAME SALARY STARTDATE DEPT 1 1 Rick 623.30 2012-01-01 IT 2 2 Dan 515.20 2013-09-23 Operations 3 3 Michelle 611.00 2014-11-15 IT 4 4 Ryan 729.00 2014-05-11 HR 5 NA Gary 843.25 2015-03-27 Finance 6 6 Nina 578.00 2013-05-21 IT 7 7 Simon 632.80 2013-07-30 Operations 8 8 Guru 722.50 2014-06-17 Finance As the data is now available as a dataframe we can use data frame related function to read and manipulate the file. JSON file stores data as text in human-readable format. Json stands for JavaScript Object Notation. R can read JSON files using the rjson package. In the R console, you can issue the following command to install the rjson package. install.packages("rjson") Create a JSON file by copying the below data into a text editor like notepad. Save the file with a .json extension and choosing the file type as all files(*.*). { "ID":["1","2","3","4","5","6","7","8" ], "Name":["Rick","Dan","Michelle","Ryan","Gary","Nina","Simon","Guru" ], "Salary":["623.3","515.2","611","729","843.25","578","632.8","722.5" ], "StartDate":[ "1/1/2012","9/23/2013","11/15/2014","5/11/2014","3/27/2015","5/21/2013", "7/30/2013","6/17/2014"], "Dept":[ "IT","Operations","IT","HR","Finance","IT","Operations","Finance"] } The JSON file is read by R using the function from JSON(). It is stored as a list in R. # Load the package required to read JSON files. library("rjson") # Give the input file name to the function. result <- fromJSON(file = "input.json") # Print the result. print(result) When we execute the above code, it produces the following result − $ID [1] "1" "2" "3" "4" "5" "6" "7" "8" $Name [1] "Rick" "Dan" "Michelle" "Ryan" "Gary" "Nina" "Simon" "Guru" $Salary [1] "623.3" "515.2" "611" "729" "843.25" "578" "632.8" "722.5" $StartDate [1] "1/1/2012" "9/23/2013" "11/15/2014" "5/11/2014" "3/27/2015" "5/21/2013" "7/30/2013" "6/17/2014" $Dept [1] "IT" "Operations" "IT" "HR" "Finance" "IT" "Operations" "Finance" We can convert the extracted data above to a R data frame for further analysis using the as.data.frame() function. # Load the package required to read JSON files. library("rjson") # Give the input file name to the function. result <- fromJSON(file = "input.json") # Convert JSON file to a data frame. json_data_frame <- as.data.frame(result) print(json_data_frame) When we execute the above code, it produces the following result − id, name, salary, start_date, dept 1 1 Rick 623.30 2012-01-01 IT 2 2 Dan 515.20 2013-09-23 Operations 3 3 Michelle 611.00 2014-11-15 IT 4 4 Ryan 729.00 2014-05-11 HR 5 NA Gary 843.25 2015-03-27 Finance 6 6 Nina 578.00 2013-05-21 IT 7 7 Simon 632.80 2013-07-30 Operations 8 8 Guru 722.50 2014-06-17 Finance Many websites provide data for consumption by its users. For example the World Health Organization(WHO) provides reports on health and medical information in the form of CSV, txt and XML files. Using R programs, we can programmatically extract specific data from such websites. Some packages in R which are used to scrap data form the web are − "RCurl",XML", and "stringr". They are used to connect to the URL’s, identify required links for the files and download them to the local environment. The following packages are required for processing the URL’s and links to the files. If they are not available in your R Environment, you can install them using following commands. install.packages("RCurl") install.packages("XML") install.packages("stringr") install.packages("plyr") We will visit the URL weather data and download the CSV files using R for the year 2015. We will use the function getHTMLLinks() to gather the URLs of the files. Then we will use the function download.file() to save the files to the local system. As we will be applying the same code again and again for multiple files, we will create a function to be called multiple times. The filenames are passed as parameters in form of a R list object to this function. # Read the URL. url <- "http://www.geos.ed.ac.uk/~weather/jcmb_ws/" # Gather the html links present in the webpage. links <- getHTMLLinks(url) # Identify only the links which point to the JCMB 2015 files. filenames <- links[str_detect(links, "JCMB_2015")] # Store the file names as a list. filenames_list <- as.list(filenames) # Create a function to download the files by passing the URL and filename list. downloadcsv <- function (mainurl,filename) { filedetails <- str_c(mainurl,filename) download.file(filedetails,filename) } # Now apply the l_ply function and save the files into the current R working directory. l_ply(filenames,downloadcsv,mainurl = "http://www.geos.ed.ac.uk/~weather/jcmb_ws/") After running the above code, you can locate the following files in the current R working directory. "JCMB_2015.csv" "JCMB_2015_Apr.csv" "JCMB_2015_Feb.csv" "JCMB_2015_Jan.csv" "JCMB_2015_Mar.csv" The data is Relational database systems are stored in a normalized format. So, to carry out statistical computing we will need very advanced and complex Sql queries. But R can connect easily to many relational databases like MySql, Oracle, Sql server etc. and fetch records from them as a data frame. Once the data is available in the R environment, it becomes a normal R data set and can be manipulated or analyzed using all the powerful packages and functions. In this tutorial we will be using MySql as our reference database for connecting to R. R has a built-in package named "RMySQL" which provides native connectivity between with MySql database. You can install this package in the R environment using the following command. install.packages("RMySQL") Once the package is installed we create a connection object in R to connect to the database. It takes the username, password, database name and host name as input. # Create a connection Object to MySQL database. # We will connect to the sampel database named "sakila" that comes with MySql installation. mysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'sakila', host = 'localhost') # List the tables available in this database. dbListTables(mysqlconnection) When we execute the above code, it produces the following result − [1] "actor" "actor_info" [3] "address" "category" [5] "city" "country" [7] "customer" "customer_list" [9] "film" "film_actor" [11] "film_category" "film_list" [13] "film_text" "inventory" [15] "language" "nicer_but_slower_film_list" [17] "payment" "rental" [19] "sales_by_film_category" "sales_by_store" [21] "staff" "staff_list" [23] "store" We can query the database tables in MySql using the function dbSendQuery(). The query gets executed in MySql and the result set is returned using the R fetch() function. Finally it is stored as a data frame in R. # Query the "actor" tables to get all the rows. result = dbSendQuery(mysqlconnection, "select * from actor") # Store the result in a R data frame object. n = 5 is used to fetch first 5 rows. data.frame = fetch(result, n = 5) print(data.fame) When we execute the above code, it produces the following result − actor_id first_name last_name last_update 1 1 PENELOPE GUINESS 2006-02-15 04:34:33 2 2 NICK WAHLBERG 2006-02-15 04:34:33 3 3 ED CHASE 2006-02-15 04:34:33 4 4 JENNIFER DAVIS 2006-02-15 04:34:33 5 5 JOHNNY LOLLOBRIGIDA 2006-02-15 04:34:33 We can pass any valid select query to get the result. result = dbSendQuery(mysqlconnection, "select * from actor where last_name = 'TORN'") # Fetch all the records(with n = -1) and store it as a data frame. data.frame = fetch(result, n = -1) print(data) When we execute the above code, it produces the following result − actor_id first_name last_name last_update 1 18 DAN TORN 2006-02-15 04:34:33 2 94 KENNETH TORN 2006-02-15 04:34:33 3 102 WALTER TORN 2006-02-15 04:34:33 We can update the rows in a Mysql table by passing the update query to the dbSendQuery() function. dbSendQuery(mysqlconnection, "update mtcars set disp = 168.5 where hp = 110") After executing the above code we can see the table updated in the MySql Environment. dbSendQuery(mysqlconnection, "insert into mtcars(row_names, mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb) values('New Mazda RX4 Wag', 21, 6, 168.5, 110, 3.9, 2.875, 17.02, 0, 1, 4, 4)" ) After executing the above code we can see the row inserted into the table in the MySql Environment. We can create tables in the MySql using the function dbWriteTable(). It overwrites the table if it already exists and takes a data frame as input. # Create the connection object to the database where we want to create the table. mysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'sakila', host = 'localhost') # Use the R data frame "mtcars" to create the table in MySql. # All the rows of mtcars are taken inot MySql. dbWriteTable(mysqlconnection, "mtcars", mtcars[, ], overwrite = TRUE) After executing the above code we can see the table created in the MySql Environment. We can drop the tables in MySql database passing the drop table statement into the dbSendQuery() in the same way we used it for querying data from tables. dbSendQuery(mysqlconnection, 'drop table if exists mtcars') After executing the above code we can see the table is dropped in the MySql Environment. R Programming language has numerous libraries to create charts and graphs. A pie-chart is a representation of values as slices of a circle with different colors. The slices are labeled and the numbers corresponding to each slice is also represented in the chart. In R the pie chart is created using the pie() function which takes positive numbers as a vector input. The additional parameters are used to control labels, color, title etc. The basic syntax for creating a pie-chart using the R is − pie(x, labels, radius, main, col, clockwise) Following is the description of the parameters used − x is a vector containing the numeric values used in the pie chart. x is a vector containing the numeric values used in the pie chart. labels is used to give description to the slices. labels is used to give description to the slices. radius indicates the radius of the circle of the pie chart.(value between −1 and +1). radius indicates the radius of the circle of the pie chart.(value between −1 and +1). main indicates the title of the chart. main indicates the title of the chart. col indicates the color palette. col indicates the color palette. clockwise is a logical value indicating if the slices are drawn clockwise or anti clockwise. clockwise is a logical value indicating if the slices are drawn clockwise or anti clockwise. A very simple pie-chart is created using just the input vector and labels. The below script will create and save the pie chart in the current R working directory. # Create data for the graph. x <- c(21, 62, 10, 53) labels <- c("London", "New York", "Singapore", "Mumbai") # Give the chart file a name. png(file = "city.png") # Plot the chart. pie(x,labels) # Save the file. dev.off() When we execute the above code, it produces the following result − We can expand the features of the chart by adding more parameters to the function. We will use parameter main to add a title to the chart and another parameter is col which will make use of rainbow colour pallet while drawing the chart. The length of the pallet should be same as the number of values we have for the chart. Hence we use length(x). The below script will create and save the pie chart in the current R working directory. # Create data for the graph. x <- c(21, 62, 10, 53) labels <- c("London", "New York", "Singapore", "Mumbai") # Give the chart file a name. png(file = "city_title_colours.jpg") # Plot the chart with title and rainbow color pallet. pie(x, labels, main = "City pie chart", col = rainbow(length(x))) # Save the file. dev.off() When we execute the above code, it produces the following result − We can add slice percentage and a chart legend by creating additional chart variables. # Create data for the graph. x <- c(21, 62, 10,53) labels <- c("London","New York","Singapore","Mumbai") piepercent<- round(100*x/sum(x), 1) # Give the chart file a name. png(file = "city_percentage_legends.jpg") # Plot the chart. pie(x, labels = piepercent, main = "City pie chart",col = rainbow(length(x))) legend("topright", c("London","New York","Singapore","Mumbai"), cex = 0.8, fill = rainbow(length(x))) # Save the file. dev.off() When we execute the above code, it produces the following result − A pie chart with 3 dimensions can be drawn using additional packages. The package plotrix has a function called pie3D() that is used for this. # Get the library. library(plotrix) # Create data for the graph. x <- c(21, 62, 10,53) lbl <- c("London","New York","Singapore","Mumbai") # Give the chart file a name. png(file = "3d_pie_chart.jpg") # Plot the chart. pie3D(x,labels = lbl,explode = 0.1, main = "Pie Chart of Countries ") # Save the file. dev.off() When we execute the above code, it produces the following result − A bar chart represents data in rectangular bars with length of the bar proportional to the value of the variable. R uses the function barplot() to create bar charts. R can draw both vertical and Horizontal bars in the bar chart. In bar chart each of the bars can be given different colors. The basic syntax to create a bar-chart in R is − barplot(H,xlab,ylab,main, names.arg,col) Following is the description of the parameters used − H is a vector or matrix containing numeric values used in bar chart. xlab is the label for x axis. ylab is the label for y axis. main is the title of the bar chart. names.arg is a vector of names appearing under each bar. col is used to give colors to the bars in the graph. A simple bar chart is created using just the input vector and the name of each bar. The below script will create and save the bar chart in the current R working directory. # Create the data for the chart H <- c(7,12,28,3,41) # Give the chart file a name png(file = "barchart.png") # Plot the bar chart barplot(H) # Save the file dev.off() When we execute above code, it produces following result − The features of the bar chart can be expanded by adding more parameters. The main parameter is used to add title. The col parameter is used to add colors to the bars. The args.name is a vector having same number of values as the input vector to describe the meaning of each bar. The below script will create and save the bar chart in the current R working directory. # Create the data for the chart H <- c(7,12,28,3,41) M <- c("Mar","Apr","May","Jun","Jul") # Give the chart file a name png(file = "barchart_months_revenue.png") # Plot the bar chart barplot(H,names.arg=M,xlab="Month",ylab="Revenue",col="blue", main="Revenue chart",border="red") # Save the file dev.off() When we execute above code, it produces following result − We can create bar chart with groups of bars and stacks in each bar by using a matrix as input values. More than two variables are represented as a matrix which is used to create the group bar chart and stacked bar chart. # Create the input vectors. colors = c("green","orange","brown") months <- c("Mar","Apr","May","Jun","Jul") regions <- c("East","West","North") # Create the matrix of the values. Values <- matrix(c(2,9,3,11,9,4,8,7,3,12,5,2,8,10,11), nrow = 3, ncol = 5, byrow = TRUE) # Give the chart file a name png(file = "barchart_stacked.png") # Create the bar chart barplot(Values, main = "total revenue", names.arg = months, xlab = "month", ylab = "revenue", col = colors) # Add the legend to the chart legend("topleft", regions, cex = 1.3, fill = colors) # Save the file dev.off() Boxplots are a measure of how well distributed is the data in a data set. It divides the data set into three quartiles. This graph represents the minimum, maximum, median, first quartile and third quartile in the data set. It is also useful in comparing the distribution of data across data sets by drawing boxplots for each of them. Boxplots are created in R by using the boxplot() function. The basic syntax to create a boxplot in R is − boxplot(x, data, notch, varwidth, names, main) Following is the description of the parameters used − x is a vector or a formula. x is a vector or a formula. data is the data frame. data is the data frame. notch is a logical value. Set as TRUE to draw a notch. notch is a logical value. Set as TRUE to draw a notch. varwidth is a logical value. Set as true to draw width of the box proportionate to the sample size. varwidth is a logical value. Set as true to draw width of the box proportionate to the sample size. names are the group labels which will be printed under each boxplot. names are the group labels which will be printed under each boxplot. main is used to give a title to the graph. main is used to give a title to the graph. We use the data set "mtcars" available in the R environment to create a basic boxplot. Let's look at the columns "mpg" and "cyl" in mtcars. input <- mtcars[,c('mpg','cyl')] print(head(input)) When we execute above code, it produces following result − mpg cyl Mazda RX4 21.0 6 Mazda RX4 Wag 21.0 6 Datsun 710 22.8 4 Hornet 4 Drive 21.4 6 Hornet Sportabout 18.7 8 Valiant 18.1 6 The below script will create a boxplot graph for the relation between mpg (miles per gallon) and cyl (number of cylinders). # Give the chart file a name. png(file = "boxplot.png") # Plot the chart. boxplot(mpg ~ cyl, data = mtcars, xlab = "Number of Cylinders", ylab = "Miles Per Gallon", main = "Mileage Data") # Save the file. dev.off() When we execute the above code, it produces the following result − We can draw boxplot with notch to find out how the medians of different data groups match with each other. The below script will create a boxplot graph with notch for each of the data group. # Give the chart file a name. png(file = "boxplot_with_notch.png") # Plot the chart. boxplot(mpg ~ cyl, data = mtcars, xlab = "Number of Cylinders", ylab = "Miles Per Gallon", main = "Mileage Data", notch = TRUE, varwidth = TRUE, col = c("green","yellow","purple"), names = c("High","Medium","Low") ) # Save the file. dev.off() When we execute the above code, it produces the following result − A histogram represents the frequencies of values of a variable bucketed into ranges. Histogram is similar to bar chat but the difference is it groups the values into continuous ranges. Each bar in histogram represents the height of the number of values present in that range. R creates histogram using hist() function. This function takes a vector as an input and uses some more parameters to plot histograms. The basic syntax for creating a histogram using R is − hist(v,main,xlab,xlim,ylim,breaks,col,border) Following is the description of the parameters used − v is a vector containing numeric values used in histogram. v is a vector containing numeric values used in histogram. main indicates title of the chart. main indicates title of the chart. col is used to set color of the bars. col is used to set color of the bars. border is used to set border color of each bar. border is used to set border color of each bar. xlab is used to give description of x-axis. xlab is used to give description of x-axis. xlim is used to specify the range of values on the x-axis. xlim is used to specify the range of values on the x-axis. ylim is used to specify the range of values on the y-axis. ylim is used to specify the range of values on the y-axis. breaks is used to mention the width of each bar. breaks is used to mention the width of each bar. A simple histogram is created using input vector, label, col and border parameters. The script given below will create and save the histogram in the current R working directory. # Create data for the graph. v <- c(9,13,21,8,36,22,12,41,31,33,19) # Give the chart file a name. png(file = "histogram.png") # Create the histogram. hist(v,xlab = "Weight",col = "yellow",border = "blue") # Save the file. dev.off() When we execute the above code, it produces the following result − To specify the range of values allowed in X axis and Y axis, we can use the xlim and ylim parameters. The width of each of the bar can be decided by using breaks. # Create data for the graph. v <- c(9,13,21,8,36,22,12,41,31,33,19) # Give the chart file a name. png(file = "histogram_lim_breaks.png") # Create the histogram. hist(v,xlab = "Weight",col = "green",border = "red", xlim = c(0,40), ylim = c(0,5), breaks = 5) # Save the file. dev.off() When we execute the above code, it produces the following result − A line chart is a graph that connects a series of points by drawing line segments between them. These points are ordered in one of their coordinate (usually the x-coordinate) value. Line charts are usually used in identifying the trends in data. The plot() function in R is used to create the line graph. The basic syntax to create a line chart in R is − plot(v,type,col,xlab,ylab) Following is the description of the parameters used − v is a vector containing the numeric values. v is a vector containing the numeric values. type takes the value "p" to draw only the points, "l" to draw only the lines and "o" to draw both points and lines. type takes the value "p" to draw only the points, "l" to draw only the lines and "o" to draw both points and lines. xlab is the label for x axis. xlab is the label for x axis. ylab is the label for y axis. ylab is the label for y axis. main is the Title of the chart. main is the Title of the chart. col is used to give colors to both the points and lines. col is used to give colors to both the points and lines. A simple line chart is created using the input vector and the type parameter as "O". The below script will create and save a line chart in the current R working directory. # Create the data for the chart. v <- c(7,12,28,3,41) # Give the chart file a name. png(file = "line_chart.jpg") # Plot the bar chart. plot(v,type = "o") # Save the file. dev.off() When we execute the above code, it produces the following result − The features of the line chart can be expanded by using additional parameters. We add color to the points and lines, give a title to the chart and add labels to the axes. # Create the data for the chart. v <- c(7,12,28,3,41) # Give the chart file a name. png(file = "line_chart_label_colored.jpg") # Plot the bar chart. plot(v,type = "o", col = "red", xlab = "Month", ylab = "Rain fall", main = "Rain fall chart") # Save the file. dev.off() When we execute the above code, it produces the following result − More than one line can be drawn on the same chart by using the lines()function. After the first line is plotted, the lines() function can use an additional vector as input to draw the second line in the chart, # Create the data for the chart. v <- c(7,12,28,3,41) t <- c(14,7,6,19,3) # Give the chart file a name. png(file = "line_chart_2_lines.jpg") # Plot the bar chart. plot(v,type = "o",col = "red", xlab = "Month", ylab = "Rain fall", main = "Rain fall chart") lines(t, type = "o", col = "blue") # Save the file. dev.off() When we execute the above code, it produces the following result − Scatterplots show many points plotted in the Cartesian plane. Each point represents the values of two variables. One variable is chosen in the horizontal axis and another in the vertical axis. The simple scatterplot is created using the plot() function. The basic syntax for creating scatterplot in R is − plot(x, y, main, xlab, ylab, xlim, ylim, axes) Following is the description of the parameters used − x is the data set whose values are the horizontal coordinates. x is the data set whose values are the horizontal coordinates. y is the data set whose values are the vertical coordinates. y is the data set whose values are the vertical coordinates. main is the tile of the graph. main is the tile of the graph. xlab is the label in the horizontal axis. xlab is the label in the horizontal axis. ylab is the label in the vertical axis. ylab is the label in the vertical axis. xlim is the limits of the values of x used for plotting. xlim is the limits of the values of x used for plotting. ylim is the limits of the values of y used for plotting. ylim is the limits of the values of y used for plotting. axes indicates whether both axes should be drawn on the plot. axes indicates whether both axes should be drawn on the plot. We use the data set "mtcars" available in the R environment to create a basic scatterplot. Let's use the columns "wt" and "mpg" in mtcars. input <- mtcars[,c('wt','mpg')] print(head(input)) When we execute the above code, it produces the following result − wt mpg Mazda RX4 2.620 21.0 Mazda RX4 Wag 2.875 21.0 Datsun 710 2.320 22.8 Hornet 4 Drive 3.215 21.4 Hornet Sportabout 3.440 18.7 Valiant 3.460 18.1 The below script will create a scatterplot graph for the relation between wt(weight) and mpg(miles per gallon). # Get the input values. input <- mtcars[,c('wt','mpg')] # Give the chart file a name. png(file = "scatterplot.png") # Plot the chart for cars with weight between 2.5 to 5 and mileage between 15 and 30. plot(x = input$wt,y = input$mpg, xlab = "Weight", ylab = "Milage", xlim = c(2.5,5), ylim = c(15,30), main = "Weight vs Milage" ) # Save the file. dev.off() When we execute the above code, it produces the following result − When we have more than two variables and we want to find the correlation between one variable versus the remaining ones we use scatterplot matrix. We use pairs() function to create matrices of scatterplots. The basic syntax for creating scatterplot matrices in R is − pairs(formula, data) Following is the description of the parameters used − formula represents the series of variables used in pairs. formula represents the series of variables used in pairs. data represents the data set from which the variables will be taken. data represents the data set from which the variables will be taken. Each variable is paired up with each of the remaining variable. A scatterplot is plotted for each pair. # Give the chart file a name. png(file = "scatterplot_matrices.png") # Plot the matrices between 4 variables giving 12 plots. # One variable with 3 others and total 4 variables. pairs(~wt+mpg+disp+cyl,data = mtcars, main = "Scatterplot Matrix") # Save the file. dev.off() When the above code is executed we get the following output. Statistical analysis in R is performed by using many in-built functions. Most of these functions are part of the R base package. These functions take R vector as an input along with the arguments and give the result. The functions we are discussing in this chapter are mean, median and mode. It is calculated by taking the sum of the values and dividing with the number of values in a data series. The function mean() is used to calculate this in R. The basic syntax for calculating mean in R is − mean(x, trim = 0, na.rm = FALSE, ...) Following is the description of the parameters used − x is the input vector. x is the input vector. trim is used to drop some observations from both end of the sorted vector. trim is used to drop some observations from both end of the sorted vector. na.rm is used to remove the missing values from the input vector. na.rm is used to remove the missing values from the input vector. # Create a vector. x <- c(12,7,3,4.2,18,2,54,-21,8,-5) # Find Mean. result.mean <- mean(x) print(result.mean) When we execute the above code, it produces the following result − [1] 8.22 When trim parameter is supplied, the values in the vector get sorted and then the required numbers of observations are dropped from calculating the mean. When trim = 0.3, 3 values from each end will be dropped from the calculations to find mean. In this case the sorted vector is (−21, −5, 2, 3, 4.2, 7, 8, 12, 18, 54) and the values removed from the vector for calculating mean are (−21,−5,2) from left and (12,18,54) from right. # Create a vector. x <- c(12,7,3,4.2,18,2,54,-21,8,-5) # Find Mean. result.mean <- mean(x,trim = 0.3) print(result.mean) When we execute the above code, it produces the following result − [1] 5.55 If there are missing values, then the mean function returns NA. To drop the missing values from the calculation use na.rm = TRUE. which means remove the NA values. # Create a vector. x <- c(12,7,3,4.2,18,2,54,-21,8,-5,NA) # Find mean. result.mean <- mean(x) print(result.mean) # Find mean dropping NA values. result.mean <- mean(x,na.rm = TRUE) print(result.mean) When we execute the above code, it produces the following result − [1] NA [1] 8.22 The middle most value in a data series is called the median. The median() function is used in R to calculate this value. The basic syntax for calculating median in R is − median(x, na.rm = FALSE) Following is the description of the parameters used − x is the input vector. x is the input vector. na.rm is used to remove the missing values from the input vector. na.rm is used to remove the missing values from the input vector. # Create the vector. x <- c(12,7,3,4.2,18,2,54,-21,8,-5) # Find the median. median.result <- median(x) print(median.result) When we execute the above code, it produces the following result − [1] 5.6 The mode is the value that has highest number of occurrences in a set of data. Unike mean and median, mode can have both numeric and character data. R does not have a standard in-built function to calculate mode. So we create a user function to calculate mode of a data set in R. This function takes the vector as input and gives the mode value as output. # Create the function. getmode <- function(v) { uniqv <- unique(v) uniqv[which.max(tabulate(match(v, uniqv)))] } # Create the vector with numbers. v <- c(2,1,2,3,1,2,3,4,1,5,5,3,2,3) # Calculate the mode using the user function. result <- getmode(v) print(result) # Create the vector with characters. charv <- c("o","it","the","it","it") # Calculate the mode using the user function. result <- getmode(charv) print(result) When we execute the above code, it produces the following result − [1] 2 [1] "it" Regression analysis is a very widely used statistical tool to establish a relationship model between two variables. One of these variable is called predictor variable whose value is gathered through experiments. The other variable is called response variable whose value is derived from the predictor variable. In Linear Regression these two variables are related through an equation, where exponent (power) of both these variables is 1. Mathematically a linear relationship represents a straight line when plotted as a graph. A non-linear relationship where the exponent of any variable is not equal to 1 creates a curve. The general mathematical equation for a linear regression is − y = ax + b Following is the description of the parameters used − y is the response variable. y is the response variable. x is the predictor variable. x is the predictor variable. a and b are constants which are called the coefficients. a and b are constants which are called the coefficients. A simple example of regression is predicting weight of a person when his height is known. To do this we need to have the relationship between height and weight of a person. The steps to create the relationship is − Carry out the experiment of gathering a sample of observed values of height and corresponding weight. Carry out the experiment of gathering a sample of observed values of height and corresponding weight. Create a relationship model using the lm() functions in R. Create a relationship model using the lm() functions in R. Find the coefficients from the model created and create the mathematical equation using these Find the coefficients from the model created and create the mathematical equation using these Get a summary of the relationship model to know the average error in prediction. Also called residuals. Get a summary of the relationship model to know the average error in prediction. Also called residuals. To predict the weight of new persons, use the predict() function in R. To predict the weight of new persons, use the predict() function in R. Below is the sample data representing the observations − # Values of height 151, 174, 138, 186, 128, 136, 179, 163, 152, 131 # Values of weight. 63, 81, 56, 91, 47, 57, 76, 72, 62, 48 This function creates the relationship model between the predictor and the response variable. The basic syntax for lm() function in linear regression is − lm(formula,data) Following is the description of the parameters used − formula is a symbol presenting the relation between x and y. formula is a symbol presenting the relation between x and y. data is the vector on which the formula will be applied. data is the vector on which the formula will be applied. x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131) y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48) # Apply the lm() function. relation <- lm(y~x) print(relation) When we execute the above code, it produces the following result − Call: lm(formula = y ~ x) Coefficients: (Intercept) x -38.4551 0.6746 x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131) y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48) # Apply the lm() function. relation <- lm(y~x) print(summary(relation)) When we execute the above code, it produces the following result − Call: lm(formula = y ~ x) Residuals: Min 1Q Median 3Q Max -6.3002 -1.6629 0.0412 1.8944 3.9775 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) -38.45509 8.04901 -4.778 0.00139 ** x 0.67461 0.05191 12.997 1.16e-06 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 3.253 on 8 degrees of freedom Multiple R-squared: 0.9548, Adjusted R-squared: 0.9491 F-statistic: 168.9 on 1 and 8 DF, p-value: 1.164e-06 The basic syntax for predict() in linear regression is − predict(object, newdata) Following is the description of the parameters used − object is the formula which is already created using the lm() function. object is the formula which is already created using the lm() function. newdata is the vector containing the new value for predictor variable. newdata is the vector containing the new value for predictor variable. # The predictor vector. x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131) # The resposne vector. y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48) # Apply the lm() function. relation <- lm(y~x) # Find weight of a person with height 170. a <- data.frame(x = 170) result <- predict(relation,a) print(result) When we execute the above code, it produces the following result − 1 76.22869 # Create the predictor and response variable. x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131) y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48) relation <- lm(y~x) # Give the chart file a name. png(file = "linearregression.png") # Plot the chart. plot(y,x,col = "blue",main = "Height & Weight Regression", abline(lm(x~y)),cex = 1.3,pch = 16,xlab = "Weight in Kg",ylab = "Height in cm") # Save the file. dev.off() When we execute the above code, it produces the following result − Multiple regression is an extension of linear regression into relationship between more than two variables. In simple linear relation we have one predictor and one response variable, but in multiple regression we have more than one predictor variable and one response variable. The general mathematical equation for multiple regression is − y = a + b1x1 + b2x2 +...bnxn Following is the description of the parameters used − y is the response variable. y is the response variable. a, b1, b2...bn are the coefficients. a, b1, b2...bn are the coefficients. x1, x2, ...xn are the predictor variables. x1, x2, ...xn are the predictor variables. We create the regression model using the lm() function in R. The model determines the value of the coefficients using the input data. Next we can predict the value of the response variable for a given set of predictor variables using these coefficients. This function creates the relationship model between the predictor and the response variable. The basic syntax for lm() function in multiple regression is − lm(y ~ x1+x2+x3...,data) Following is the description of the parameters used − formula is a symbol presenting the relation between the response variable and predictor variables. formula is a symbol presenting the relation between the response variable and predictor variables. data is the vector on which the formula will be applied. data is the vector on which the formula will be applied. Consider the data set "mtcars" available in the R environment. It gives a comparison between different car models in terms of mileage per gallon (mpg), cylinder displacement("disp"), horse power("hp"), weight of the car("wt") and some more parameters. The goal of the model is to establish the relationship between "mpg" as a response variable with "disp","hp" and "wt" as predictor variables. We create a subset of these variables from the mtcars data set for this purpose. input <- mtcars[,c("mpg","disp","hp","wt")] print(head(input)) When we execute the above code, it produces the following result − mpg disp hp wt Mazda RX4 21.0 160 110 2.620 Mazda RX4 Wag 21.0 160 110 2.875 Datsun 710 22.8 108 93 2.320 Hornet 4 Drive 21.4 258 110 3.215 Hornet Sportabout 18.7 360 175 3.440 Valiant 18.1 225 105 3.460 input <- mtcars[,c("mpg","disp","hp","wt")] # Create the relationship model. model <- lm(mpg~disp+hp+wt, data = input) # Show the model. print(model) # Get the Intercept and coefficients as vector elements. cat("# # # # The Coefficient Values # # # ","\n") a <- coef(model)[1] print(a) Xdisp <- coef(model)[2] Xhp <- coef(model)[3] Xwt <- coef(model)[4] print(Xdisp) print(Xhp) print(Xwt) When we execute the above code, it produces the following result − Call: lm(formula = mpg ~ disp + hp + wt, data = input) Coefficients: (Intercept) disp hp wt 37.105505 -0.000937 -0.031157 -3.800891 # # # # The Coefficient Values # # # (Intercept) 37.10551 disp -0.0009370091 hp -0.03115655 wt -3.800891 Based on the above intercept and coefficient values, we create the mathematical equation. Y = a+Xdisp.x1+Xhp.x2+Xwt.x3 or Y = 37.15+(-0.000937)*x1+(-0.0311)*x2+(-3.8008)*x3 We can use the regression equation created above to predict the mileage when a new set of values for displacement, horse power and weight is provided. For a car with disp = 221, hp = 102 and wt = 2.91 the predicted mileage is − Y = 37.15+(-0.000937)*221+(-0.0311)*102+(-3.8008)*2.91 = 22.7104 The Logistic Regression is a regression model in which the response variable (dependent variable) has categorical values such as True/False or 0/1. It actually measures the probability of a binary response as the value of response variable based on the mathematical equation relating it with the predictor variables. The general mathematical equation for logistic regression is − y = 1/(1+e^-(a+b1x1+b2x2+b3x3+...)) Following is the description of the parameters used − y is the response variable. y is the response variable. x is the predictor variable. x is the predictor variable. a and b are the coefficients which are numeric constants. a and b are the coefficients which are numeric constants. The function used to create the regression model is the glm() function. The basic syntax for glm() function in logistic regression is − glm(formula,data,family) Following is the description of the parameters used − formula is the symbol presenting the relationship between the variables. formula is the symbol presenting the relationship between the variables. data is the data set giving the values of these variables. data is the data set giving the values of these variables. family is R object to specify the details of the model. It's value is binomial for logistic regression. family is R object to specify the details of the model. It's value is binomial for logistic regression. The in-built data set "mtcars" describes different models of a car with their various engine specifications. In "mtcars" data set, the transmission mode (automatic or manual) is described by the column am which is a binary value (0 or 1). We can create a logistic regression model between the columns "am" and 3 other columns - hp, wt and cyl. # Select some columns form mtcars. input <- mtcars[,c("am","cyl","hp","wt")] print(head(input)) When we execute the above code, it produces the following result − am cyl hp wt Mazda RX4 1 6 110 2.620 Mazda RX4 Wag 1 6 110 2.875 Datsun 710 1 4 93 2.320 Hornet 4 Drive 0 6 110 3.215 Hornet Sportabout 0 8 175 3.440 Valiant 0 6 105 3.460 We use the glm() function to create the regression model and get its summary for analysis. input <- mtcars[,c("am","cyl","hp","wt")] am.data = glm(formula = am ~ cyl + hp + wt, data = input, family = binomial) print(summary(am.data)) When we execute the above code, it produces the following result − Call: glm(formula = am ~ cyl + hp + wt, family = binomial, data = input) Deviance Residuals: Min 1Q Median 3Q Max -2.17272 -0.14907 -0.01464 0.14116 1.27641 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 19.70288 8.11637 2.428 0.0152 * cyl 0.48760 1.07162 0.455 0.6491 hp 0.03259 0.01886 1.728 0.0840 . wt -9.14947 4.15332 -2.203 0.0276 * --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for binomial family taken to be 1) Null deviance: 43.2297 on 31 degrees of freedom Residual deviance: 9.8415 on 28 degrees of freedom AIC: 17.841 Number of Fisher Scoring iterations: 8 In the summary as the p-value in the last column is more than 0.05 for the variables "cyl" and "hp", we consider them to be insignificant in contributing to the value of the variable "am". Only weight (wt) impacts the "am" value in this regression model. In a random collection of data from independent sources, it is generally observed that the distribution of data is normal. Which means, on plotting a graph with the value of the variable in the horizontal axis and the count of the values in the vertical axis we get a bell shape curve. The center of the curve represents the mean of the data set. In the graph, fifty percent of values lie to the left of the mean and the other fifty percent lie to the right of the graph. This is referred as normal distribution in statistics. R has four in built functions to generate normal distribution. They are described below. dnorm(x, mean, sd) pnorm(x, mean, sd) qnorm(p, mean, sd) rnorm(n, mean, sd) Following is the description of the parameters used in above functions − x is a vector of numbers. x is a vector of numbers. p is a vector of probabilities. p is a vector of probabilities. n is number of observations(sample size). n is number of observations(sample size). mean is the mean value of the sample data. It's default value is zero. mean is the mean value of the sample data. It's default value is zero. sd is the standard deviation. It's default value is 1. sd is the standard deviation. It's default value is 1. This function gives height of the probability distribution at each point for a given mean and standard deviation. # Create a sequence of numbers between -10 and 10 incrementing by 0.1. x <- seq(-10, 10, by = .1) # Choose the mean as 2.5 and standard deviation as 0.5. y <- dnorm(x, mean = 2.5, sd = 0.5) # Give the chart file a name. png(file = "dnorm.png") plot(x,y) # Save the file. dev.off() When we execute the above code, it produces the following result − This function gives the probability of a normally distributed random number to be less that the value of a given number. It is also called "Cumulative Distribution Function". # Create a sequence of numbers between -10 and 10 incrementing by 0.2. x <- seq(-10,10,by = .2) # Choose the mean as 2.5 and standard deviation as 2. y <- pnorm(x, mean = 2.5, sd = 2) # Give the chart file a name. png(file = "pnorm.png") # Plot the graph. plot(x,y) # Save the file. dev.off() When we execute the above code, it produces the following result − This function takes the probability value and gives a number whose cumulative value matches the probability value. # Create a sequence of probability values incrementing by 0.02. x <- seq(0, 1, by = 0.02) # Choose the mean as 2 and standard deviation as 3. y <- qnorm(x, mean = 2, sd = 1) # Give the chart file a name. png(file = "qnorm.png") # Plot the graph. plot(x,y) # Save the file. dev.off() When we execute the above code, it produces the following result − This function is used to generate random numbers whose distribution is normal. It takes the sample size as input and generates that many random numbers. We draw a histogram to show the distribution of the generated numbers. # Create a sample of 50 numbers which are normally distributed. y <- rnorm(50) # Give the chart file a name. png(file = "rnorm.png") # Plot the histogram for this sample. hist(y, main = "Normal DIstribution") # Save the file. dev.off() When we execute the above code, it produces the following result − The binomial distribution model deals with finding the probability of success of an event which has only two possible outcomes in a series of experiments. For example, tossing of a coin always gives a head or a tail. The probability of finding exactly 3 heads in tossing a coin repeatedly for 10 times is estimated during the binomial distribution. R has four in-built functions to generate binomial distribution. They are described below. dbinom(x, size, prob) pbinom(x, size, prob) qbinom(p, size, prob) rbinom(n, size, prob) Following is the description of the parameters used − x is a vector of numbers. x is a vector of numbers. p is a vector of probabilities. p is a vector of probabilities. n is number of observations. n is number of observations. size is the number of trials. size is the number of trials. prob is the probability of success of each trial. prob is the probability of success of each trial. This function gives the probability density distribution at each point. # Create a sample of 50 numbers which are incremented by 1. x <- seq(0,50,by = 1) # Create the binomial distribution. y <- dbinom(x,50,0.5) # Give the chart file a name. png(file = "dbinom.png") # Plot the graph for this sample. plot(x,y) # Save the file. dev.off() When we execute the above code, it produces the following result − This function gives the cumulative probability of an event. It is a single value representing the probability. # Probability of getting 26 or less heads from a 51 tosses of a coin. x <- pbinom(26,51,0.5) print(x) When we execute the above code, it produces the following result − [1] 0.610116 This function takes the probability value and gives a number whose cumulative value matches the probability value. # How many heads will have a probability of 0.25 will come out when a coin # is tossed 51 times. x <- qbinom(0.25,51,1/2) print(x) When we execute the above code, it produces the following result − [1] 23 This function generates required number of random values of given probability from a given sample. # Find 8 random values from a sample of 150 with probability of 0.4. x <- rbinom(8,150,.4) print(x) When we execute the above code, it produces the following result − [1] 58 61 59 66 55 60 61 67 Poisson Regression involves regression models in which the response variable is in the form of counts and not fractional numbers. For example, the count of number of births or number of wins in a football match series. Also the values of the response variables follow a Poisson distribution. The general mathematical equation for Poisson regression is − log(y) = a + b1x1 + b2x2 + bnxn..... Following is the description of the parameters used − y is the response variable. y is the response variable. a and b are the numeric coefficients. a and b are the numeric coefficients. x is the predictor variable. x is the predictor variable. The function used to create the Poisson regression model is the glm() function. The basic syntax for glm() function in Poisson regression is − glm(formula,data,family) Following is the description of the parameters used in above functions − formula is the symbol presenting the relationship between the variables. formula is the symbol presenting the relationship between the variables. data is the data set giving the values of these variables. data is the data set giving the values of these variables. family is R object to specify the details of the model. It's value is 'Poisson' for Logistic Regression. family is R object to specify the details of the model. It's value is 'Poisson' for Logistic Regression. We have the in-built data set "warpbreaks" which describes the effect of wool type (A or B) and tension (low, medium or high) on the number of warp breaks per loom. Let's consider "breaks" as the response variable which is a count of number of breaks. The wool "type" and "tension" are taken as predictor variables. Input Data input <- warpbreaks print(head(input)) When we execute the above code, it produces the following result − breaks wool tension 1 26 A L 2 30 A L 3 54 A L 4 25 A L 5 70 A L 6 52 A L output <-glm(formula = breaks ~ wool+tension, data = warpbreaks, family = poisson) print(summary(output)) When we execute the above code, it produces the following result − Call: glm(formula = breaks ~ wool + tension, family = poisson, data = warpbreaks) Deviance Residuals: Min 1Q Median 3Q Max -3.6871 -1.6503 -0.4269 1.1902 4.2616 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 3.69196 0.04541 81.302 < 2e-16 *** woolB -0.20599 0.05157 -3.994 6.49e-05 *** tensionM -0.32132 0.06027 -5.332 9.73e-08 *** tensionH -0.51849 0.06396 -8.107 5.21e-16 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for poisson family taken to be 1) Null deviance: 297.37 on 53 degrees of freedom Residual deviance: 210.39 on 50 degrees of freedom AIC: 493.06 Number of Fisher Scoring iterations: 4 In the summary we look for the p-value in the last column to be less than 0.05 to consider an impact of the predictor variable on the response variable. As seen the wooltype B having tension type M and H have impact on the count of breaks. We use Regression analysis to create models which describe the effect of variation in predictor variables on the response variable. Sometimes, if we have a categorical variable with values like Yes/No or Male/Female etc. The simple regression analysis gives multiple results for each value of the categorical variable. In such scenario, we can study the effect of the categorical variable by using it along with the predictor variable and comparing the regression lines for each level of the categorical variable. Such an analysis is termed as Analysis of Covariance also called as ANCOVA. Consider the R built in data set mtcars. In it we observer that the field "am" represents the type of transmission (auto or manual). It is a categorical variable with values 0 and 1. The miles per gallon value(mpg) of a car can also depend on it besides the value of horse power("hp"). We study the effect of the value of "am" on the regression between "mpg" and "hp". It is done by using the aov() function followed by the anova() function to compare the multiple regressions. Create a data frame containing the fields "mpg", "hp" and "am" from the data set mtcars. Here we take "mpg" as the response variable, "hp" as the predictor variable and "am" as the categorical variable. input <- mtcars[,c("am","mpg","hp")] print(head(input)) When we execute the above code, it produces the following result − am mpg hp Mazda RX4 1 21.0 110 Mazda RX4 Wag 1 21.0 110 Datsun 710 1 22.8 93 Hornet 4 Drive 0 21.4 110 Hornet Sportabout 0 18.7 175 Valiant 0 18.1 105 We create a regression model taking "hp" as the predictor variable and "mpg" as the response variable taking into account the interaction between "am" and "hp". # Get the dataset. input <- mtcars # Create the regression model. result <- aov(mpg~hp*am,data = input) print(summary(result)) When we execute the above code, it produces the following result − Df Sum Sq Mean Sq F value Pr(>F) hp 1 678.4 678.4 77.391 1.50e-09 *** am 1 202.2 202.2 23.072 4.75e-05 *** hp:am 1 0.0 0.0 0.001 0.981 Residuals 28 245.4 8.8 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 This result shows that both horse power and transmission type has significant effect on miles per gallon as the p value in both cases is less than 0.05. But the interaction between these two variables is not significant as the p-value is more than 0.05. # Get the dataset. input <- mtcars # Create the regression model. result <- aov(mpg~hp+am,data = input) print(summary(result)) When we execute the above code, it produces the following result − Df Sum Sq Mean Sq F value Pr(>F) hp 1 678.4 678.4 80.15 7.63e-10 *** am 1 202.2 202.2 23.89 3.46e-05 *** Residuals 29 245.4 8.5 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 This result shows that both horse power and transmission type has significant effect on miles per gallon as the p value in both cases is less than 0.05. Now we can compare the two models to conclude if the interaction of the variables is truly in-significant. For this we use the anova() function. # Get the dataset. input <- mtcars # Create the regression models. result1 <- aov(mpg~hp*am,data = input) result2 <- aov(mpg~hp+am,data = input) # Compare the two models. print(anova(result1,result2)) When we execute the above code, it produces the following result − Model 1: mpg ~ hp * am Model 2: mpg ~ hp + am Res.Df RSS Df Sum of Sq F Pr(>F) 1 28 245.43 2 29 245.44 -1 -0.0052515 6e-04 0.9806 As the p-value is greater than 0.05 we conclude that the interaction between horse power and transmission type is not significant. So the mileage per gallon will depend in a similar manner on the horse power of the car in both auto and manual transmission mode. Time series is a series of data points in which each data point is associated with a timestamp. A simple example is the price of a stock in the stock market at different points of time on a given day. Another example is the amount of rainfall in a region at different months of the year. R language uses many functions to create, manipulate and plot the time series data. The data for the time series is stored in an R object called time-series object. It is also a R data object like a vector or data frame. The time series object is created by using the ts() function. The basic syntax for ts() function in time series analysis is − timeseries.object.name <- ts(data, start, end, frequency) Following is the description of the parameters used − data is a vector or matrix containing the values used in the time series. data is a vector or matrix containing the values used in the time series. start specifies the start time for the first observation in time series. start specifies the start time for the first observation in time series. end specifies the end time for the last observation in time series. end specifies the end time for the last observation in time series. frequency specifies the number of observations per unit time. frequency specifies the number of observations per unit time. Except the parameter "data" all other parameters are optional. Consider the annual rainfall details at a place starting from January 2012. We create an R time series object for a period of 12 months and plot it. # Get the data points in form of a R vector. rainfall <- c(799,1174.8,865.1,1334.6,635.4,918.5,685.5,998.6,784.2,985,882.8,1071) # Convert it to a time series object. rainfall.timeseries <- ts(rainfall,start = c(2012,1),frequency = 12) # Print the timeseries data. print(rainfall.timeseries) # Give the chart file a name. png(file = "rainfall.png") # Plot a graph of the time series. plot(rainfall.timeseries) # Save the file. dev.off() When we execute the above code, it produces the following result and chart − Jan Feb Mar Apr May Jun Jul Aug Sep 2012 799.0 1174.8 865.1 1334.6 635.4 918.5 685.5 998.6 784.2 Oct Nov Dec 2012 985.0 882.8 1071.0 The Time series chart − The value of the frequency parameter in the ts() function decides the time intervals at which the data points are measured. A value of 12 indicates that the time series is for 12 months. Other values and its meaning is as below − frequency = 12 pegs the data points for every month of a year. frequency = 12 pegs the data points for every month of a year. frequency = 4 pegs the data points for every quarter of a year. frequency = 4 pegs the data points for every quarter of a year. frequency = 6 pegs the data points for every 10 minutes of an hour. frequency = 6 pegs the data points for every 10 minutes of an hour. frequency = 24*6 pegs the data points for every 10 minutes of a day. frequency = 24*6 pegs the data points for every 10 minutes of a day. We can plot multiple time series in one chart by combining both the series into a matrix. # Get the data points in form of a R vector. rainfall1 <- c(799,1174.8,865.1,1334.6,635.4,918.5,685.5,998.6,784.2,985,882.8,1071) rainfall2 <- c(655,1306.9,1323.4,1172.2,562.2,824,822.4,1265.5,799.6,1105.6,1106.7,1337.8) # Convert them to a matrix. combined.rainfall <- matrix(c(rainfall1,rainfall2),nrow = 12) # Convert it to a time series object. rainfall.timeseries <- ts(combined.rainfall,start = c(2012,1),frequency = 12) # Print the timeseries data. print(rainfall.timeseries) # Give the chart file a name. png(file = "rainfall_combined.png") # Plot a graph of the time series. plot(rainfall.timeseries, main = "Multiple Time Series") # Save the file. dev.off() When we execute the above code, it produces the following result and chart − Series 1 Series 2 Jan 2012 799.0 655.0 Feb 2012 1174.8 1306.9 Mar 2012 865.1 1323.4 Apr 2012 1334.6 1172.2 May 2012 635.4 562.2 Jun 2012 918.5 824.0 Jul 2012 685.5 822.4 Aug 2012 998.6 1265.5 Sep 2012 784.2 799.6 Oct 2012 985.0 1105.6 Nov 2012 882.8 1106.7 Dec 2012 1071.0 1337.8 The Multiple Time series chart − When modeling real world data for regression analysis, we observe that it is rarely the case that the equation of the model is a linear equation giving a linear graph. Most of the time, the equation of the model of real world data involves mathematical functions of higher degree like an exponent of 3 or a sin function. In such a scenario, the plot of the model gives a curve rather than a line. The goal of both linear and non-linear regression is to adjust the values of the model's parameters to find the line or curve that comes closest to your data. On finding these values we will be able to estimate the response variable with good accuracy. In Least Square regression, we establish a regression model in which the sum of the squares of the vertical distances of different points from the regression curve is minimized. We generally start with a defined model and assume some values for the coefficients. We then apply the nls() function of R to get the more accurate values along with the confidence intervals. The basic syntax for creating a nonlinear least square test in R is − nls(formula, data, start) Following is the description of the parameters used − formula is a nonlinear model formula including variables and parameters. formula is a nonlinear model formula including variables and parameters. data is a data frame used to evaluate the variables in the formula. data is a data frame used to evaluate the variables in the formula. start is a named list or named numeric vector of starting estimates. start is a named list or named numeric vector of starting estimates. We will consider a nonlinear model with assumption of initial values of its coefficients. Next we will see what is the confidence intervals of these assumed values so that we can judge how well these values fir into the model. So let's consider the below equation for this purpose − a = b1*x^2+b2 Let's assume the initial coefficients to be 1 and 3 and fit these values into nls() function. xvalues <- c(1.6,2.1,2,2.23,3.71,3.25,3.4,3.86,1.19,2.21) yvalues <- c(5.19,7.43,6.94,8.11,18.75,14.88,16.06,19.12,3.21,7.58) # Give the chart file a name. png(file = "nls.png") # Plot these values. plot(xvalues,yvalues) # Take the assumed values and fit into the model. model <- nls(yvalues ~ b1*xvalues^2+b2,start = list(b1 = 1,b2 = 3)) # Plot the chart with new data by fitting it to a prediction from 100 data points. new.data <- data.frame(xvalues = seq(min(xvalues),max(xvalues),len = 100)) lines(new.data$xvalues,predict(model,newdata = new.data)) # Save the file. dev.off() # Get the sum of the squared residuals. print(sum(resid(model)^2)) # Get the confidence intervals on the chosen values of the coefficients. print(confint(model)) When we execute the above code, it produces the following result − [1] 1.081935 Waiting for profiling to be done... 2.5% 97.5% b1 1.137708 1.253135 b2 1.497364 2.496484 We can conclude that the value of b1 is more close to 1 while the value of b2 is more close to 2 and not 3. Decision tree is a graph to represent choices and their results in form of a tree. The nodes in the graph represent an event or choice and the edges of the graph represent the decision rules or conditions. It is mostly used in Machine Learning and Data Mining applications using R. Examples of use of decision tress is − predicting an email as spam or not spam, predicting of a tumor is cancerous or predicting a loan as a good or bad credit risk based on the factors in each of these. Generally, a model is created with observed data also called training data. Then a set of validation data is used to verify and improve the model. R has packages which are used to create and visualize decision trees. For new set of predictor variable, we use this model to arrive at a decision on the category (yes/No, spam/not spam) of the data. The R package "party" is used to create decision trees. Use the below command in R console to install the package. You also have to install the dependent packages if any. install.packages("party") The package "party" has the function ctree() which is used to create and analyze decison tree. The basic syntax for creating a decision tree in R is − ctree(formula, data) Following is the description of the parameters used − formula is a formula describing the predictor and response variables. formula is a formula describing the predictor and response variables. data is the name of the data set used. data is the name of the data set used. We will use the R in-built data set named readingSkills to create a decision tree. It describes the score of someone's readingSkills if we know the variables "age","shoesize","score" and whether the person is a native speaker or not. Here is the sample data. # Load the party package. It will automatically load other # dependent packages. library(party) # Print some records from data set readingSkills. print(head(readingSkills)) When we execute the above code, it produces the following result and chart − nativeSpeaker age shoeSize score 1 yes 5 24.83189 32.29385 2 yes 6 25.95238 36.63105 3 no 11 30.42170 49.60593 4 yes 7 28.66450 40.28456 5 yes 11 31.88207 55.46085 6 yes 10 30.07843 52.83124 Loading required package: methods Loading required package: grid ............................... ............................... We will use the ctree() function to create the decision tree and see its graph. # Load the party package. It will automatically load other # dependent packages. library(party) # Create the input data frame. input.dat <- readingSkills[c(1:105),] # Give the chart file a name. png(file = "decision_tree.png") # Create the tree. output.tree <- ctree( nativeSpeaker ~ age + shoeSize + score, data = input.dat) # Plot the tree. plot(output.tree) # Save the file. dev.off() When we execute the above code, it produces the following result − null device 1 Loading required package: methods Loading required package: grid Loading required package: mvtnorm Loading required package: modeltools Loading required package: stats4 Loading required package: strucchange Loading required package: zoo Attaching package: ‘zoo’ The following objects are masked from ‘package:base’: as.Date, as.Date.numeric Loading required package: sandwich From the decision tree shown above we can conclude that anyone whose readingSkills score is less than 38.3 and age is more than 6 is not a native Speaker. In the random forest approach, a large number of decision trees are created. Every observation is fed into every decision tree. The most common outcome for each observation is used as the final output. A new observation is fed into all the trees and taking a majority vote for each classification model. An error estimate is made for the cases which were not used while building the tree. That is called an OOB (Out-of-bag) error estimate which is mentioned as a percentage. The R package "randomForest" is used to create random forests. Use the below command in R console to install the package. You also have to install the dependent packages if any. install.packages("randomForest) The package "randomForest" has the function randomForest() which is used to create and analyze random forests. The basic syntax for creating a random forest in R is − randomForest(formula, data) Following is the description of the parameters used − formula is a formula describing the predictor and response variables. formula is a formula describing the predictor and response variables. data is the name of the data set used. data is the name of the data set used. We will use the R in-built data set named readingSkills to create a decision tree. It describes the score of someone's readingSkills if we know the variables "age","shoesize","score" and whether the person is a native speaker. Here is the sample data. # Load the party package. It will automatically load other # required packages. library(party) # Print some records from data set readingSkills. print(head(readingSkills)) When we execute the above code, it produces the following result and chart − nativeSpeaker age shoeSize score 1 yes 5 24.83189 32.29385 2 yes 6 25.95238 36.63105 3 no 11 30.42170 49.60593 4 yes 7 28.66450 40.28456 5 yes 11 31.88207 55.46085 6 yes 10 30.07843 52.83124 Loading required package: methods Loading required package: grid ............................... ............................... We will use the randomForest() function to create the decision tree and see it's graph. # Load the party package. It will automatically load other # required packages. library(party) library(randomForest) # Create the forest. output.forest <- randomForest(nativeSpeaker ~ age + shoeSize + score, data = readingSkills) # View the forest results. print(output.forest) # Importance of each predictor. print(importance(fit,type = 2)) When we execute the above code, it produces the following result − Call: randomForest(formula = nativeSpeaker ~ age + shoeSize + score, data = readingSkills) Type of random forest: classification Number of trees: 500 No. of variables tried at each split: 1 OOB estimate of error rate: 1% Confusion matrix: no yes class.error no 99 1 0.01 yes 1 99 0.01 MeanDecreaseGini age 13.95406 shoeSize 18.91006 score 56.73051 From the random forest shown above we can conclude that the shoesize and score are the important factors deciding if someone is a native speaker or not. Also the model has only 1% error which means we can predict with 99% accuracy. Survival analysis deals with predicting the time when a specific event is going to occur. It is also known as failure time analysis or analysis of time to death. For example predicting the number of days a person with cancer will survive or predicting the time when a mechanical system is going to fail. The R package named survival is used to carry out survival analysis. This package contains the function Surv() which takes the input data as a R formula and creates a survival object among the chosen variables for analysis. Then we use the function survfit() to create a plot for the analysis. install.packages("survival") The basic syntax for creating survival analysis in R is − Surv(time,event) survfit(formula) Following is the description of the parameters used − time is the follow up time until the event occurs. time is the follow up time until the event occurs. event indicates the status of occurrence of the expected event. event indicates the status of occurrence of the expected event. formula is the relationship between the predictor variables. formula is the relationship between the predictor variables. We will consider the data set named "pbc" present in the survival packages installed above. It describes the survival data points about people affected with primary biliary cirrhosis (PBC) of the liver. Among the many columns present in the data set we are primarily concerned with the fields "time" and "status". Time represents the number of days between registration of the patient and earlier of the event between the patient receiving a liver transplant or death of the patient. # Load the library. library("survival") # Print first few rows. print(head(pbc)) When we execute the above code, it produces the following result and chart − id time status trt age sex ascites hepato spiders edema bili chol 1 1 400 2 1 58.76523 f 1 1 1 1.0 14.5 261 2 2 4500 0 1 56.44627 f 0 1 1 0.0 1.1 302 3 3 1012 2 1 70.07255 m 0 0 0 0.5 1.4 176 4 4 1925 2 1 54.74059 f 0 1 1 0.5 1.8 244 5 5 1504 1 2 38.10541 f 0 1 1 0.0 3.4 279 6 6 2503 2 2 66.25873 f 0 1 0 0.0 0.8 248 albumin copper alk.phos ast trig platelet protime stage 1 2.60 156 1718.0 137.95 172 190 12.2 4 2 4.14 54 7394.8 113.52 88 221 10.6 3 3 3.48 210 516.0 96.10 55 151 12.0 4 4 2.54 64 6121.8 60.63 92 183 10.3 4 5 3.53 143 671.0 113.15 72 136 10.9 3 6 3.98 50 944.0 93.00 63 NA 11.0 3 From the above data we are considering time and status for our analysis. Now we proceed to apply the Surv() function to the above data set and create a plot that will show the trend. # Load the library. library("survival") # Create the survival object. survfit(Surv(pbc$time,pbc$status == 2)~1) # Give the chart file a name. png(file = "survival.png") # Plot the graph. plot(survfit(Surv(pbc$time,pbc$status == 2)~1)) # Save the file. dev.off() When we execute the above code, it produces the following result and chart − Call: survfit(formula = Surv(pbc$time, pbc$status == 2) ~ 1) n events median 0.95LCL 0.95UCL 418 161 3395 3090 3853 The trend in the above graph helps us predicting the probability of survival at the end of a certain number of days. Chi-Square test is a statistical method to determine if two categorical variables have a significant correlation between them. Both those variables should be from same population and they should be categorical like − Yes/No, Male/Female, Red/Green etc. For example, we can build a data set with observations on people's ice-cream buying pattern and try to correlate the gender of a person with the flavor of the ice-cream they prefer. If a correlation is found we can plan for appropriate stock of flavors by knowing the number of gender of people visiting. The function used for performing chi-Square test is chisq.test(). The basic syntax for creating a chi-square test in R is − chisq.test(data) Following is the description of the parameters used − data is the data in form of a table containing the count value of the variables in the observation. data is the data in form of a table containing the count value of the variables in the observation. We will take the Cars93 data in the "MASS" library which represents the sales of different models of car in the year 1993. library("MASS") print(str(Cars93)) When we execute the above code, it produces the following result − 'data.frame': 93 obs. of 27 variables: $ Manufacturer : Factor w/ 32 levels "Acura","Audi",..: 1 1 2 2 3 4 4 4 4 5 ... $ Model : Factor w/ 93 levels "100","190E","240",..: 49 56 9 1 6 24 54 74 73 35 ... $ Type : Factor w/ 6 levels "Compact","Large",..: 4 3 1 3 3 3 2 2 3 2 ... $ Min.Price : num 12.9 29.2 25.9 30.8 23.7 14.2 19.9 22.6 26.3 33 ... $ Price : num 15.9 33.9 29.1 37.7 30 15.7 20.8 23.7 26.3 34.7 ... $ Max.Price : num 18.8 38.7 32.3 44.6 36.2 17.3 21.7 24.9 26.3 36.3 ... $ MPG.city : int 25 18 20 19 22 22 19 16 19 16 ... $ MPG.highway : int 31 25 26 26 30 31 28 25 27 25 ... $ AirBags : Factor w/ 3 levels "Driver & Passenger",..: 3 1 2 1 2 2 2 2 2 2 ... $ DriveTrain : Factor w/ 3 levels "4WD","Front",..: 2 2 2 2 3 2 2 3 2 2 ... $ Cylinders : Factor w/ 6 levels "3","4","5","6",..: 2 4 4 4 2 2 4 4 4 5 ... $ EngineSize : num 1.8 3.2 2.8 2.8 3.5 2.2 3.8 5.7 3.8 4.9 ... $ Horsepower : int 140 200 172 172 208 110 170 180 170 200 ... $ RPM : int 6300 5500 5500 5500 5700 5200 4800 4000 4800 4100 ... $ Rev.per.mile : int 2890 2335 2280 2535 2545 2565 1570 1320 1690 1510 ... $ Man.trans.avail : Factor w/ 2 levels "No","Yes": 2 2 2 2 2 1 1 1 1 1 ... $ Fuel.tank.capacity: num 13.2 18 16.9 21.1 21.1 16.4 18 23 18.8 18 ... $ Passengers : int 5 5 5 6 4 6 6 6 5 6 ... $ Length : int 177 195 180 193 186 189 200 216 198 206 ... $ Wheelbase : int 102 115 102 106 109 105 111 116 108 114 ... $ Width : int 68 71 67 70 69 69 74 78 73 73 ... $ Turn.circle : int 37 38 37 37 39 41 42 45 41 43 ... $ Rear.seat.room : num 26.5 30 28 31 27 28 30.5 30.5 26.5 35 ... $ Luggage.room : int 11 15 14 17 13 16 17 21 14 18 ... $ Weight : int 2705 3560 3375 3405 3640 2880 3470 4105 3495 3620 ... $ Origin : Factor w/ 2 levels "USA","non-USA": 2 2 2 2 2 1 1 1 1 1 ... $ Make : Factor w/ 93 levels "Acura Integra",..: 1 2 4 3 5 6 7 9 8 10 ... The above result shows the dataset has many Factor variables which can be considered as categorical variables. For our model we will consider the variables "AirBags" and "Type". Here we aim to find out any significant correlation between the types of car sold and the type of Air bags it has. If correlation is observed we can estimate which types of cars can sell better with what types of air bags. # Load the library. library("MASS") # Create a data frame from the main data set. car.data <- data.frame(Cars93$AirBags, Cars93$Type) # Create a table with the needed variables. car.data = table(Cars93$AirBags, Cars93$Type) print(car.data) # Perform the Chi-Square test. print(chisq.test(car.data)) When we execute the above code, it produces the following result − Compact Large Midsize Small Sporty Van Driver & Passenger 2 4 7 0 3 0 Driver only 9 7 11 5 8 3 None 5 0 4 16 3 6 Pearson's Chi-squared test data: car.data X-squared = 33.001, df = 10, p-value = 0.0002723 Warning message: In chisq.test(car.data) : Chi-squared approximation may be incorrect The result shows the p-value of less than 0.05 which indicates a string correlation. 12 Lectures 2 hours Nishant Malik 10 Lectures 1.5 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 20 Lectures 2 hours Asif Hussain 10 Lectures 1.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2672, "s": 2402, "text": "R is a programming language and software environment for statistical analysis, graphics representation and reporting. R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and is currently developed by the R Development Core Team." }, { "code": null, "e": 2919, "s": 2672, "text": "The core of R is an interpreted computer language which allows branching and looping as well as modular programming using functions. R allows integration with the procedures written in the C, C++, .Net, Python or FORTRAN languages for efficiency." }, { "code": null, "e": 3084, "s": 2919, "text": "R is freely available under the GNU General Public License, and pre-compiled binary versions are provided for various operating systems like Linux, Windows and Mac." }, { "code": null, "e": 3198, "s": 3084, "text": "R is free software distributed under a GNU-style copy left, and an official part of the GNU project called GNU S." }, { "code": null, "e": 3382, "s": 3198, "text": "R was initially written by Ross Ihaka and Robert Gentleman at the Department of Statistics of the University of Auckland in Auckland, New Zealand. R made its first appearance in 1993." }, { "code": null, "e": 3465, "s": 3382, "text": "A large group of individuals has contributed to R by sending code and bug reports." }, { "code": null, "e": 3548, "s": 3465, "text": "A large group of individuals has contributed to R by sending code and bug reports." }, { "code": null, "e": 3653, "s": 3548, "text": "Since mid-1997 there has been a core group (the \"R Core Team\") who can modify the R source code archive." }, { "code": null, "e": 3758, "s": 3653, "text": "Since mid-1997 there has been a core group (the \"R Core Team\") who can modify the R source code archive." }, { "code": null, "e": 3943, "s": 3758, "text": "As stated earlier, R is a programming language and software environment for statistical analysis, graphics representation and reporting. The following are the important features of R −" }, { "code": null, "e": 4110, "s": 3943, "text": "R is a well-developed, simple and effective programming language which includes conditionals, loops, user defined recursive functions and input and output facilities." }, { "code": null, "e": 4277, "s": 4110, "text": "R is a well-developed, simple and effective programming language which includes conditionals, loops, user defined recursive functions and input and output facilities." }, { "code": null, "e": 4332, "s": 4277, "text": "R has an effective data handling and storage facility," }, { "code": null, "e": 4387, "s": 4332, "text": "R has an effective data handling and storage facility," }, { "code": null, "e": 4476, "s": 4387, "text": "R provides a suite of operators for calculations on arrays, lists, vectors and matrices." }, { "code": null, "e": 4565, "s": 4476, "text": "R provides a suite of operators for calculations on arrays, lists, vectors and matrices." }, { "code": null, "e": 4648, "s": 4565, "text": "R provides a large, coherent and integrated collection of tools for data analysis." }, { "code": null, "e": 4731, "s": 4648, "text": "R provides a large, coherent and integrated collection of tools for data analysis." }, { "code": null, "e": 4852, "s": 4731, "text": "R provides graphical facilities for data analysis and display either directly at the computer or printing at the papers." }, { "code": null, "e": 4973, "s": 4852, "text": "R provides graphical facilities for data analysis and display either directly at the computer or printing at the papers." }, { "code": null, "e": 5341, "s": 4973, "text": "As a conclusion, R is world’s most widely used statistics programming language. It's the # 1 choice of data scientists and supported by a vibrant and talented community of contributors. R is taught in universities and deployed in mission critical business applications. This tutorial will teach you R programming along with suitable examples in simple and easy steps." }, { "code": null, "e": 5438, "s": 5341, "text": "If you are still willing to set up your environment for R, you can follow the steps given below." }, { "code": null, "e": 5561, "s": 5438, "text": "You can download the Windows installer version of R from R-3.2.2 for Windows (32/64 bit) and save it in a local directory." }, { "code": null, "e": 5862, "s": 5561, "text": "As it is a Windows installer (.exe) with a name \"R-version-win.exe\". You can just double click and run the installer accepting the default settings. If your Windows is 32-bit version, it installs the 32-bit version. But if your windows is 64-bit, then it installs both the 32-bit and 64-bit versions." }, { "code": null, "e": 6094, "s": 5862, "text": "After installation you can locate the icon to run the Program in a directory structure \"R\\R3.2.2\\bin\\i386\\Rgui.exe\" under the Windows Program Files. Clicking this icon brings up the R-GUI which is the R console to do R Programming." }, { "code": null, "e": 6176, "s": 6094, "text": "R is available as a binary for many versions of Linux at the location R Binaries." }, { "code": null, "e": 6408, "s": 6176, "text": "The instruction to install Linux varies from flavor to flavor. These steps are mentioned under each type of Linux version in the mentioned link. However, if you are in a hurry, then you can use yum command to install R as follows −" }, { "code": null, "e": 6425, "s": 6408, "text": "$ yum install R\n" }, { "code": null, "e": 6595, "s": 6425, "text": "Above command will install core functionality of R programming along with standard packages, still you need additional package, then you can launch R prompt as follows −" }, { "code": null, "e": 7272, "s": 6595, "text": "$ R\nR version 3.2.0 (2015-04-16) -- \"Full of Ingredients\" \nCopyright (C) 2015 The R Foundation for Statistical Computing\nPlatform: x86_64-redhat-linux-gnu (64-bit)\n\nR is free software and comes with ABSOLUTELY NO WARRANTY.\nYou are welcome to redistribute it under certain conditions.\nType 'license()' or 'licence()' for distribution details.\n\nR is a collaborative project with many contributors. \nType 'contributors()' for more information and\n'citation()' on how to cite R or R packages in publications.\n\nType 'demo()' for some demos, 'help()' for on-line help, or\n'help.start()' for an HTML browser interface to help.\nType 'q()' to quit R.\n> \n" }, { "code": null, "e": 7446, "s": 7272, "text": "Now you can use install command at R prompt to install the required package. For example, the following command will install plotrix package which is required for 3D charts." }, { "code": null, "e": 7476, "s": 7446, "text": "> install.packages(\"plotrix\")" }, { "code": null, "e": 7719, "s": 7476, "text": "As a convention, we will start learning R programming by writing a \"Hello, World!\" program. Depending on the needs, you can program either at R command prompt or you can use an R script file to write your program. Let's check both one by one." }, { "code": null, "e": 7862, "s": 7719, "text": "Once you have R environment setup, then it’s easy to start your R command prompt by just typing the following command at your command prompt −" }, { "code": null, "e": 7867, "s": 7862, "text": "$ R\n" }, { "code": null, "e": 7979, "s": 7867, "text": "This will launch R interpreter and you will get a prompt > where you can start typing your program as follows −" }, { "code": null, "e": 8049, "s": 7979, "text": "> myString <- \"Hello, World!\"\n> print ( myString)\n[1] \"Hello, World!\"" }, { "code": null, "e": 8241, "s": 8049, "text": "Here first statement defines a string variable myString, where we assign a string \"Hello, World!\" and then next statement print() is being used to print the value stored in variable myString." }, { "code": null, "e": 8508, "s": 8241, "text": "Usually, you will do your programming by writing your programs in script files and then you execute those scripts at your command prompt with the help of R interpreter called Rscript. So let's start with writing following code in a text file called test.R as under −" }, { "code": null, "e": 8591, "s": 8508, "text": "# My first program in R Programming\nmyString <- \"Hello, World!\"\n\nprint ( myString)" }, { "code": null, "e": 8755, "s": 8591, "text": "Save the above code in a file test.R and execute it at Linux command prompt as given below. Even if you are using Windows or other system, syntax will remain same." }, { "code": null, "e": 8774, "s": 8755, "text": "$ Rscript test.R \n" }, { "code": null, "e": 8839, "s": 8774, "text": "When we run the above program, it produces the following result." }, { "code": null, "e": 8860, "s": 8839, "text": "[1] \"Hello, World!\"\n" }, { "code": null, "e": 9067, "s": 8860, "text": "Comments are like helping text in your R program and they are ignored by the interpreter while executing your actual program. Single comment is written using # in the beginning of the statement as follows −" }, { "code": null, "e": 9104, "s": 9067, "text": "# My first program in R Programming\n" }, { "code": null, "e": 9203, "s": 9104, "text": "R does not support multi-line comments but you can perform a trick which is something as follows −" }, { "code": null, "e": 9375, "s": 9203, "text": "if(FALSE) {\n \"This is a demo for multi-line comments and it should be put inside either a \n single OR double quote\"\n}\n\nmyString <- \"Hello, World!\"\nprint ( myString)" }, { "code": null, "e": 9396, "s": 9375, "text": "[1] \"Hello, World!\"\n" }, { "code": null, "e": 9571, "s": 9396, "text": "Though above comments will be executed by R interpreter, they will not interfere with your actual program. You should put such comments inside, either single or double quote." }, { "code": null, "e": 9846, "s": 9571, "text": "Generally, while doing programming in any programming language, you need to use various variables to store various information. Variables are nothing but reserved memory locations to store values. This means that, when you create a variable you reserve some space in memory." }, { "code": null, "e": 10126, "s": 9846, "text": "You may like to store information of various data types like character, wide character, integer, floating point, double floating point, Boolean etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory." }, { "code": null, "e": 10422, "s": 10126, "text": "In contrast to other programming languages like C and java in R, the variables are not declared as some data type. The variables are assigned with R-Objects and the data type of the R-object becomes the data type of the variable. There are many types of R-objects. The frequently used ones are −" }, { "code": null, "e": 10430, "s": 10422, "text": "Vectors" }, { "code": null, "e": 10436, "s": 10430, "text": "Lists" }, { "code": null, "e": 10445, "s": 10436, "text": "Matrices" }, { "code": null, "e": 10452, "s": 10445, "text": "Arrays" }, { "code": null, "e": 10460, "s": 10452, "text": "Factors" }, { "code": null, "e": 10472, "s": 10460, "text": "Data Frames" }, { "code": null, "e": 10671, "s": 10472, "text": "The simplest of these objects is the vector object and there are six data types of these atomic vectors, also termed as six classes of vectors. The other R-Objects are built upon the atomic vectors." }, { "code": null, "e": 10698, "s": 10671, "text": "v <- TRUE \nprint(class(v))" }, { "code": null, "e": 10733, "s": 10698, "text": "it produces the following result −" }, { "code": null, "e": 10749, "s": 10733, "text": "[1] \"logical\" \n" }, { "code": null, "e": 10775, "s": 10749, "text": "v <- 23.5\nprint(class(v))" }, { "code": null, "e": 10810, "s": 10775, "text": "it produces the following result −" }, { "code": null, "e": 10825, "s": 10810, "text": "[1] \"numeric\"\n" }, { "code": null, "e": 10849, "s": 10825, "text": "v <- 2L\nprint(class(v))" }, { "code": null, "e": 10884, "s": 10849, "text": "it produces the following result −" }, { "code": null, "e": 10899, "s": 10884, "text": "[1] \"integer\"\n" }, { "code": null, "e": 10925, "s": 10899, "text": "v <- 2+5i\nprint(class(v))" }, { "code": null, "e": 10960, "s": 10925, "text": "it produces the following result −" }, { "code": null, "e": 10975, "s": 10960, "text": "[1] \"complex\"\n" }, { "code": null, "e": 11003, "s": 10975, "text": "v <- \"TRUE\"\nprint(class(v))" }, { "code": null, "e": 11038, "s": 11003, "text": "it produces the following result −" }, { "code": null, "e": 11055, "s": 11038, "text": "[1] \"character\"\n" }, { "code": null, "e": 11095, "s": 11055, "text": "v <- charToRaw(\"Hello\")\nprint(class(v))" }, { "code": null, "e": 11130, "s": 11095, "text": "it produces the following result −" }, { "code": null, "e": 11142, "s": 11130, "text": "[1] \"raw\" \n" }, { "code": null, "e": 11455, "s": 11142, "text": "In R programming, the very basic data types are the R-objects called vectors which hold elements of different classes as shown above. Please note in R the number of classes is not confined to only the above six types. For example, we can use many atomic vectors and create an array whose class will become array." }, { "code": null, "e": 11593, "s": 11455, "text": "When you want to create vector with more than one element, you should use c() function which means to combine the elements into a vector." }, { "code": null, "e": 11712, "s": 11593, "text": "# Create a vector.\napple <- c('red','green',\"yellow\")\nprint(apple)\n\n# Get the class of the vector.\nprint(class(apple))" }, { "code": null, "e": 11779, "s": 11712, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 11827, "s": 11779, "text": "[1] \"red\" \"green\" \"yellow\"\n[1] \"character\"\n" }, { "code": null, "e": 11967, "s": 11827, "text": "A list is an R-object which can contain many different types of elements inside it like vectors, functions and even another list inside it." }, { "code": null, "e": 12049, "s": 11967, "text": "# Create a list.\nlist1 <- list(c(2,5,3),21.3,sin)\n\n# Print the list.\nprint(list1)" }, { "code": null, "e": 12116, "s": 12049, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 12188, "s": 12116, "text": "[[1]]\n[1] 2 5 3\n\n[[2]]\n[1] 21.3\n\n[[3]]\nfunction (x) .Primitive(\"sin\")\n" }, { "code": null, "e": 12303, "s": 12188, "text": "A matrix is a two-dimensional rectangular data set. It can be created using a vector input to the matrix function." }, { "code": null, "e": 12405, "s": 12303, "text": "# Create a matrix.\nM = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)\nprint(M)" }, { "code": null, "e": 12472, "s": 12405, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 12532, "s": 12472, "text": " [,1] [,2] [,3]\n[1,] \"a\" \"a\" \"b\" \n[2,] \"c\" \"b\" \"a\"\n" }, { "code": null, "e": 12798, "s": 12532, "text": "While matrices are confined to two dimensions, arrays can be of any number of dimensions. The array function takes a dim attribute which creates the required number of dimension. In the below example we create an array with two elements which are 3x3 matrices each." }, { "code": null, "e": 12873, "s": 12798, "text": "# Create an array.\na <- array(c('green','yellow'),dim = c(3,3,2))\nprint(a)" }, { "code": null, "e": 12940, "s": 12873, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 13214, "s": 12940, "text": ", , 1\n\n [,1] [,2] [,3] \n[1,] \"green\" \"yellow\" \"green\" \n[2,] \"yellow\" \"green\" \"yellow\"\n[3,] \"green\" \"yellow\" \"green\" \n\n, , 2\n\n [,1] [,2] [,3] \n[1,] \"yellow\" \"green\" \"yellow\"\n[2,] \"green\" \"yellow\" \"green\" \n[3,] \"yellow\" \"green\" \"yellow\" \n" }, { "code": null, "e": 13528, "s": 13214, "text": "Factors are the r-objects which are created using a vector. It stores the vector along with the distinct values of the elements in the vector as labels. The labels are always character irrespective of whether it is numeric or character or Boolean etc. in the input vector. They are useful in statistical modeling." }, { "code": null, "e": 13626, "s": 13528, "text": "Factors are created using the factor() function. The nlevels functions gives the count of levels." }, { "code": null, "e": 13849, "s": 13626, "text": "# Create a vector.\napple_colors <- c('green','green','yellow','red','red','red','green')\n\n# Create a factor object.\nfactor_apple <- factor(apple_colors)\n\n# Print the factor.\nprint(factor_apple)\nprint(nlevels(factor_apple))" }, { "code": null, "e": 13916, "s": 13849, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 14001, "s": 13916, "text": "[1] green green yellow red red red green \nLevels: green red yellow\n[1] 3\n" }, { "code": null, "e": 14265, "s": 14001, "text": "Data frames are tabular data objects. Unlike a matrix in data frame each column can contain different modes of data. The first column can be numeric while the second column can be character and third column can be logical. It is a list of vectors of equal length." }, { "code": null, "e": 14322, "s": 14265, "text": "Data Frames are created using the data.frame() function." }, { "code": null, "e": 14501, "s": 14322, "text": "# Create the data frame.\nBMI <- \tdata.frame(\n gender = c(\"Male\", \"Male\",\"Female\"), \n height = c(152, 171.5, 165), \n weight = c(81,93, 78),\n Age = c(42,38,26)\n)\nprint(BMI)" }, { "code": null, "e": 14568, "s": 14501, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 14679, "s": 14568, "text": " gender height weight Age\n1 Male 152.0 81 42\n2 Male 171.5 93 38\n3 Female 165.0 78 26 \n" }, { "code": null, "e": 15022, "s": 14679, "text": "A variable provides us with named storage that our programs can manipulate. A variable in R can store an atomic vector, group of atomic vectors or a combination of many Robjects. A valid variable name consists of letters, numbers and the dot or underline characters. The variable name starts with a letter or the dot not followed by a number." }, { "code": null, "e": 15033, "s": 15022, "text": ".var_name," }, { "code": null, "e": 15042, "s": 15033, "text": "var.name" }, { "code": null, "e": 15279, "s": 15042, "text": "The variables can be assigned values using leftward, rightward and equal to operator. The values of the variables can be printed using print() or cat() function. The cat() function combines multiple items into a continuous print output." }, { "code": null, "e": 15590, "s": 15279, "text": "# Assignment using equal operator.\nvar.1 = c(0,1,2,3) \n\n# Assignment using leftward operator.\nvar.2 <- c(\"learn\",\"R\") \n\n# Assignment using rightward operator. \nc(TRUE,1) -> var.3 \n\nprint(var.1)\ncat (\"var.1 is \", var.1 ,\"\\n\")\ncat (\"var.2 is \", var.2 ,\"\\n\")\ncat (\"var.3 is \", var.3 ,\"\\n\")" }, { "code": null, "e": 15657, "s": 15590, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 15723, "s": 15657, "text": "[1] 0 1 2 3\nvar.1 is 0 1 2 3 \nvar.2 is learn R \nvar.3 is 1 1 \n" }, { "code": null, "e": 15854, "s": 15723, "text": "Note − The vector c(TRUE,1) has a mix of logical and numeric class. So logical class is coerced to numeric class making TRUE as 1." }, { "code": null, "e": 16139, "s": 15854, "text": "In R, a variable itself is not declared of any data type, rather it gets the data type of the R - object assigned to it. So R is called a dynamically typed language, which means that we can change a variable’s data type of the same variable again and again when using it in a program." }, { "code": null, "e": 16348, "s": 16139, "text": "var_x <- \"Hello\"\ncat(\"The class of var_x is \",class(var_x),\"\\n\")\n\nvar_x <- 34.5\ncat(\" Now the class of var_x is \",class(var_x),\"\\n\")\n\nvar_x <- 27L\ncat(\" Next the class of var_x becomes \",class(var_x),\"\\n\")" }, { "code": null, "e": 16415, "s": 16348, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 16536, "s": 16415, "text": "The class of var_x is character \n Now the class of var_x is numeric \n Next the class of var_x becomes integer\n" }, { "code": null, "e": 16694, "s": 16536, "text": "To know all the variables currently available in the workspace we use the ls() function. Also the ls() function can use patterns to match the variable names." }, { "code": null, "e": 16706, "s": 16694, "text": "print(ls())" }, { "code": null, "e": 16773, "s": 16706, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 16915, "s": 16773, "text": "[1] \"my var\" \"my_new_var\" \"my_var\" \"var.1\" \n[5] \"var.2\" \"var.3\" \"var.name\" \"var_name2.\"\n[9] \"var_x\" \"varname\" \n" }, { "code": null, "e": 17006, "s": 16915, "text": "Note − It is a sample output depending on what variables are declared in your environment." }, { "code": null, "e": 17070, "s": 17006, "text": "The ls() function can use patterns to match the variable names." }, { "code": null, "e": 17154, "s": 17070, "text": "# List the variables starting with the pattern \"var\".\nprint(ls(pattern = \"var\")) " }, { "code": null, "e": 17221, "s": 17154, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 17366, "s": 17221, "text": "[1] \"my var\" \"my_new_var\" \"my_var\" \"var.1\" \n[5] \"var.2\" \"var.3\" \"var.name\" \"var_name2.\"\n[9] \"var_x\" \"varname\" \n" }, { "code": null, "e": 17484, "s": 17366, "text": "The variables starting with dot(.) are hidden, they can be listed using \"all.names = TRUE\" argument to ls() function." }, { "code": null, "e": 17511, "s": 17484, "text": "print(ls(all.name = TRUE))" }, { "code": null, "e": 17578, "s": 17511, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 17797, "s": 17578, "text": "[1] \".cars\" \".Random.seed\" \".var_name\" \".varname\" \".varname2\" \n[6] \"my var\" \"my_new_var\" \"my_var\" \"var.1\" \"var.2\" \n[11]\"var.3\" \"var.name\" \"var_name2.\" \"var_x\" \n" }, { "code": null, "e": 17941, "s": 17797, "text": "Variables can be deleted by using the rm() function. Below we delete the variable var.3. On printing the value of the variable error is thrown." }, { "code": null, "e": 17964, "s": 17941, "text": "rm(var.3)\nprint(var.3)" }, { "code": null, "e": 18031, "s": 17964, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 18093, "s": 18031, "text": "[1] \"var.3\"\nError in print(var.3) : object 'var.3' not found\n" }, { "code": null, "e": 18172, "s": 18093, "text": "All the variables can be deleted by using the rm() and ls() function together." }, { "code": null, "e": 18200, "s": 18172, "text": "rm(list = ls())\nprint(ls())" }, { "code": null, "e": 18267, "s": 18200, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 18281, "s": 18267, "text": "character(0)\n" }, { "code": null, "e": 18472, "s": 18281, "text": "An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. R language is rich in built-in operators and provides following types of operators." }, { "code": null, "e": 18532, "s": 18472, "text": "We have the following types of operators in R programming −" }, { "code": null, "e": 18553, "s": 18532, "text": "Arithmetic Operators" }, { "code": null, "e": 18574, "s": 18553, "text": "Relational Operators" }, { "code": null, "e": 18592, "s": 18574, "text": "Logical Operators" }, { "code": null, "e": 18613, "s": 18592, "text": "Assignment Operators" }, { "code": null, "e": 18637, "s": 18613, "text": "Miscellaneous Operators" }, { "code": null, "e": 18758, "s": 18637, "text": "Following table shows the arithmetic operators supported by R language. The operators act on each element of the vector." }, { "code": null, "e": 18802, "s": 18758, "text": "v <- c( 2,5.5,6)\nt <- c(8, 3, 4)\nprint(v+t)" }, { "code": null, "e": 18837, "s": 18802, "text": "it produces the following result −" }, { "code": null, "e": 18858, "s": 18837, "text": "[1] 10.0 8.5 10.0\n" }, { "code": null, "e": 18902, "s": 18858, "text": "v <- c( 2,5.5,6)\nt <- c(8, 3, 4)\nprint(v-t)" }, { "code": null, "e": 18937, "s": 18902, "text": "it produces the following result −" }, { "code": null, "e": 18957, "s": 18937, "text": "[1] -6.0 2.5 2.0\n" }, { "code": null, "e": 19001, "s": 18957, "text": "v <- c( 2,5.5,6)\nt <- c(8, 3, 4)\nprint(v*t)" }, { "code": null, "e": 19036, "s": 19001, "text": "it produces the following result −" }, { "code": null, "e": 19056, "s": 19036, "text": "[1] 16.0 16.5 24.0\n" }, { "code": null, "e": 19100, "s": 19056, "text": "v <- c( 2,5.5,6)\nt <- c(8, 3, 4)\nprint(v/t)" }, { "code": null, "e": 19167, "s": 19100, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 19199, "s": 19167, "text": "[1] 0.250000 1.833333 1.500000\n" }, { "code": null, "e": 19244, "s": 19199, "text": "v <- c( 2,5.5,6)\nt <- c(8, 3, 4)\nprint(v%%t)" }, { "code": null, "e": 19279, "s": 19244, "text": "it produces the following result −" }, { "code": null, "e": 19296, "s": 19279, "text": "[1] 2.0 2.5 2.0\n" }, { "code": null, "e": 19342, "s": 19296, "text": "v <- c( 2,5.5,6)\nt <- c(8, 3, 4)\nprint(v%/%t)" }, { "code": null, "e": 19377, "s": 19342, "text": "it produces the following result −" }, { "code": null, "e": 19388, "s": 19377, "text": "[1] 0 1 1\n" }, { "code": null, "e": 19432, "s": 19388, "text": "v <- c( 2,5.5,6)\nt <- c(8, 3, 4)\nprint(v^t)" }, { "code": null, "e": 19467, "s": 19432, "text": "it produces the following result −" }, { "code": null, "e": 19499, "s": 19467, "text": "[1] 256.000 166.375 1296.000\n" }, { "code": null, "e": 19714, "s": 19499, "text": "Following table shows the relational operators supported by R language. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value." }, { "code": null, "e": 19762, "s": 19714, "text": "v <- c(2,5.5,6,9)\nt <- c(8,2.5,14,9)\nprint(v>t)" }, { "code": null, "e": 19797, "s": 19762, "text": "it produces the following result −" }, { "code": null, "e": 19826, "s": 19797, "text": "[1] FALSE TRUE FALSE FALSE\n" }, { "code": null, "e": 19876, "s": 19826, "text": "v <- c(2,5.5,6,9)\nt <- c(8,2.5,14,9)\nprint(v < t)" }, { "code": null, "e": 19911, "s": 19876, "text": "it produces the following result −" }, { "code": null, "e": 19940, "s": 19911, "text": "[1] TRUE FALSE TRUE FALSE\n" }, { "code": null, "e": 19991, "s": 19940, "text": "v <- c(2,5.5,6,9)\nt <- c(8,2.5,14,9)\nprint(v == t)" }, { "code": null, "e": 20026, "s": 19991, "text": "it produces the following result −" }, { "code": null, "e": 20055, "s": 20026, "text": "[1] FALSE FALSE FALSE TRUE\n" }, { "code": null, "e": 20104, "s": 20055, "text": "v <- c(2,5.5,6,9)\nt <- c(8,2.5,14,9)\nprint(v<=t)" }, { "code": null, "e": 20139, "s": 20104, "text": "it produces the following result −" }, { "code": null, "e": 20168, "s": 20139, "text": "[1] TRUE FALSE TRUE TRUE\n" }, { "code": null, "e": 20217, "s": 20168, "text": "v <- c(2,5.5,6,9)\nt <- c(8,2.5,14,9)\nprint(v>=t)" }, { "code": null, "e": 20252, "s": 20217, "text": "it produces the following result −" }, { "code": null, "e": 20281, "s": 20252, "text": "[1] FALSE TRUE FALSE TRUE\n" }, { "code": null, "e": 20330, "s": 20281, "text": "v <- c(2,5.5,6,9)\nt <- c(8,2.5,14,9)\nprint(v!=t)" }, { "code": null, "e": 20365, "s": 20330, "text": "it produces the following result −" }, { "code": null, "e": 20394, "s": 20365, "text": "[1] TRUE TRUE TRUE FALSE\n" }, { "code": null, "e": 20598, "s": 20394, "text": "Following table shows the logical operators supported by R language. It is applicable only to vectors of type logical, numeric or complex. All numbers greater than 1 are considered as logical value TRUE." }, { "code": null, "e": 20741, "s": 20598, "text": "Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value." }, { "code": null, "e": 20797, "s": 20741, "text": "v <- c(3,1,TRUE,2+3i)\nt <- c(4,1,FALSE,2+3i)\nprint(v&t)" }, { "code": null, "e": 20832, "s": 20797, "text": "it produces the following result −" }, { "code": null, "e": 20861, "s": 20832, "text": "[1] TRUE TRUE FALSE TRUE\n" }, { "code": null, "e": 20917, "s": 20861, "text": "v <- c(3,0,TRUE,2+2i)\nt <- c(4,0,FALSE,2+3i)\nprint(v|t)" }, { "code": null, "e": 20952, "s": 20917, "text": "it produces the following result −" }, { "code": null, "e": 20981, "s": 20952, "text": "[1] TRUE FALSE TRUE TRUE\n" }, { "code": null, "e": 21013, "s": 20981, "text": "v <- c(3,0,TRUE,2+2i)\nprint(!v)" }, { "code": null, "e": 21048, "s": 21013, "text": "it produces the following result −" }, { "code": null, "e": 21077, "s": 21048, "text": "[1] FALSE TRUE FALSE FALSE\n" }, { "code": null, "e": 21203, "s": 21077, "text": "The logical operator && and || considers only the first element of the vectors and give a vector of single element as output." }, { "code": null, "e": 21259, "s": 21203, "text": "v <- c(3,0,TRUE,2+2i)\nt <- c(1,3,TRUE,2+3i)\nprint(v&&t)" }, { "code": null, "e": 21294, "s": 21259, "text": "it produces the following result −" }, { "code": null, "e": 21304, "s": 21294, "text": "[1] TRUE\n" }, { "code": null, "e": 21360, "s": 21304, "text": "v <- c(0,0,TRUE,2+2i)\nt <- c(0,3,TRUE,2+3i)\nprint(v||t)" }, { "code": null, "e": 21395, "s": 21360, "text": "it produces the following result −" }, { "code": null, "e": 21406, "s": 21395, "text": "[1] FALSE\n" }, { "code": null, "e": 21460, "s": 21406, "text": "These operators are used to assign values to vectors." }, { "code": null, "e": 21463, "s": 21460, "text": "<−" }, { "code": null, "e": 21466, "s": 21463, "text": "or" }, { "code": null, "e": 21468, "s": 21466, "text": "=" }, { "code": null, "e": 21471, "s": 21468, "text": "or" }, { "code": null, "e": 21475, "s": 21471, "text": "<<−" }, { "code": null, "e": 21574, "s": 21475, "text": "v1 <- c(3,1,TRUE,2+3i)\nv2 <<- c(3,1,TRUE,2+3i)\nv3 = c(3,1,TRUE,2+3i)\nprint(v1)\nprint(v2)\nprint(v3)" }, { "code": null, "e": 21609, "s": 21574, "text": "it produces the following result −" }, { "code": null, "e": 21682, "s": 21609, "text": "[1] 3+0i 1+0i 1+0i 2+3i\n[1] 3+0i 1+0i 1+0i 2+3i\n[1] 3+0i 1+0i 1+0i 2+3i\n" }, { "code": null, "e": 21685, "s": 21682, "text": "->" }, { "code": null, "e": 21688, "s": 21685, "text": "or" }, { "code": null, "e": 21692, "s": 21688, "text": "->>" }, { "code": null, "e": 21760, "s": 21692, "text": "c(3,1,TRUE,2+3i) -> v1\nc(3,1,TRUE,2+3i) ->> v2 \nprint(v1)\nprint(v2)" }, { "code": null, "e": 21795, "s": 21760, "text": "it produces the following result −" }, { "code": null, "e": 21844, "s": 21795, "text": "[1] 3+0i 1+0i 1+0i 2+3i\n[1] 3+0i 1+0i 1+0i 2+3i\n" }, { "code": null, "e": 21946, "s": 21844, "text": "These operators are used to for specific purpose and not general mathematical or logical computation." }, { "code": null, "e": 21965, "s": 21946, "text": "v <- 2:8\nprint(v) " }, { "code": null, "e": 22000, "s": 21965, "text": "it produces the following result −" }, { "code": null, "e": 22019, "s": 22000, "text": "[1] 2 3 4 5 6 7 8\n" }, { "code": null, "e": 22082, "s": 22019, "text": "v1 <- 8\nv2 <- 12\nt <- 1:10\nprint(v1 %in% t) \nprint(v2 %in% t) " }, { "code": null, "e": 22117, "s": 22082, "text": "it produces the following result −" }, { "code": null, "e": 22137, "s": 22117, "text": "[1] TRUE\n[1] FALSE\n" }, { "code": null, "e": 22222, "s": 22137, "text": "M = matrix( c(2,6,5,1,10,4), nrow = 2,ncol = 3,byrow = TRUE)\nt = M %*% t(M)\nprint(t)" }, { "code": null, "e": 22257, "s": 22222, "text": "it produces the following result −" }, { "code": null, "e": 22304, "s": 22257, "text": " [,1] [,2]\n[1,] 65 82\n[2,] 82 117\n" }, { "code": null, "e": 22617, "s": 22304, "text": "Decision making structures require the programmer to specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false." }, { "code": null, "e": 22731, "s": 22617, "text": "Following is the general form of a typical decision making structure found in most of the programming languages −" }, { "code": null, "e": 22842, "s": 22731, "text": "R provides the following types of decision making statements. Click the following links to check their detail." }, { "code": null, "e": 22927, "s": 22842, "text": "An if statement consists of a Boolean expression followed by one or more statements." }, { "code": null, "e": 23043, "s": 22927, "text": "An if statement can be followed by an optional else statement, which executes when the Boolean expression is false." }, { "code": null, "e": 23132, "s": 23043, "text": "A switch statement allows a variable to be tested for equality against a list of values." }, { "code": null, "e": 23361, "s": 23132, "text": "There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially. The first statement in a function is executed first, followed by the second, and so on." }, { "code": null, "e": 23467, "s": 23361, "text": "Programming languages provide various control structures that allow for more complicated execution paths." }, { "code": null, "e": 23652, "s": 23467, "text": "A loop statement allows us to execute a statement or group of statements multiple times and the following is the general form of a loop statement in most of the programming languages −" }, { "code": null, "e": 23793, "s": 23652, "text": "R programming language provides the following kinds of loop to handle looping requirements. Click the following links to check their detail." }, { "code": null, "e": 23899, "s": 23793, "text": "Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable." }, { "code": null, "e": 24030, "s": 23899, "text": "Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body." }, { "code": null, "e": 24118, "s": 24030, "text": "Like a while statement, except that it tests the condition at the end of the loop body." }, { "code": null, "e": 24285, "s": 24118, "text": "Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed." }, { "code": null, "e": 24379, "s": 24285, "text": "R supports the following control statements. Click the following links to check their detail." }, { "code": null, "e": 24482, "s": 24379, "text": "Terminates the loop statement and transfers execution to the statement immediately following the loop." }, { "code": null, "e": 24537, "s": 24482, "text": "The next statement simulates the behavior of R switch." }, { "code": null, "e": 24706, "s": 24537, "text": "A function is a set of statements organized together to perform a specific task. R has a large number of in-built functions and the user can create their own functions." }, { "code": null, "e": 24885, "s": 24706, "text": "In R, a function is an object so the R interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions." }, { "code": null, "e": 25023, "s": 24885, "text": "The function in turn performs its task and returns control to the interpreter as well as any result which may be stored in other objects." }, { "code": null, "e": 25140, "s": 25023, "text": "An R function is created by using the keyword function. The basic syntax of an R function definition is as follows −" }, { "code": null, "e": 25208, "s": 25140, "text": "function_name <- function(arg_1, arg_2, ...) {\n Function body \n}\n" }, { "code": null, "e": 25248, "s": 25208, "text": "The different parts of a function are −" }, { "code": null, "e": 25364, "s": 25248, "text": "Function Name − This is the actual name of the function. It is stored in R environment as an object with this name." }, { "code": null, "e": 25480, "s": 25364, "text": "Function Name − This is the actual name of the function. It is stored in R environment as an object with this name." }, { "code": null, "e": 25694, "s": 25480, "text": "Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values." }, { "code": null, "e": 25908, "s": 25694, "text": "Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values." }, { "code": null, "e": 26015, "s": 25908, "text": "Function Body − The function body contains a collection of statements that defines what the function does." }, { "code": null, "e": 26122, "s": 26015, "text": "Function Body − The function body contains a collection of statements that defines what the function does." }, { "code": null, "e": 26229, "s": 26122, "text": "Return Value − The return value of a function is the last expression in the function body to be evaluated." }, { "code": null, "e": 26336, "s": 26229, "text": "Return Value − The return value of a function is the last expression in the function body to be evaluated." }, { "code": null, "e": 26520, "s": 26336, "text": "R has many in-built functions which can be directly called in the program without defining them first. We can also create and use our own functions referred as user defined functions." }, { "code": null, "e": 26706, "s": 26520, "text": "Simple examples of in-built functions are seq(), mean(), max(), sum(x) and paste(...) etc. They are directly called by user written programs. You can refer most widely used R functions." }, { "code": null, "e": 26883, "s": 26706, "text": "# Create a sequence of numbers from 32 to 44.\nprint(seq(32,44))\n\n# Find mean of numbers from 25 to 82.\nprint(mean(25:82))\n\n# Find sum of numbers frm 41 to 68.\nprint(sum(41:68))" }, { "code": null, "e": 26950, "s": 26883, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 27012, "s": 26950, "text": "[1] 32 33 34 35 36 37 38 39 40 41 42 43 44\n[1] 53.5\n[1] 1526\n" }, { "code": null, "e": 27216, "s": 27012, "text": "We can create user-defined functions in R. They are specific to what a user wants and once created they can be used like the built-in functions. Below is an example of how a function is created and used." }, { "code": null, "e": 27364, "s": 27216, "text": "# Create a function to print squares of numbers in sequence.\nnew.function <- function(a) {\n for(i in 1:a) {\n b <- i^2\n print(b)\n }\n}\t" }, { "code": null, "e": 27589, "s": 27364, "text": "# Create a function to print squares of numbers in sequence.\nnew.function <- function(a) {\n for(i in 1:a) {\n b <- i^2\n print(b)\n }\n}\n\n# Call the function new.function supplying 6 as an argument.\nnew.function(6)" }, { "code": null, "e": 27656, "s": 27589, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 27696, "s": 27656, "text": "[1] 1\n[1] 4\n[1] 9\n[1] 16\n[1] 25\n[1] 36\n" }, { "code": null, "e": 27877, "s": 27696, "text": "# Create a function without an argument.\nnew.function <- function() {\n for(i in 1:5) {\n print(i^2)\n }\n}\t\n\n# Call the function without supplying an argument.\nnew.function()" }, { "code": null, "e": 27944, "s": 27877, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 27977, "s": 27944, "text": "[1] 1\n[1] 4\n[1] 9\n[1] 16\n[1] 25\n" }, { "code": null, "e": 28166, "s": 27977, "text": "The arguments to a function call can be supplied in the same sequence as defined in the function or they can be supplied in a different sequence but assigned to the names of the arguments." }, { "code": null, "e": 28429, "s": 28166, "text": "# Create a function with arguments.\nnew.function <- function(a,b,c) {\n result <- a * b + c\n print(result)\n}\n\n# Call the function by position of arguments.\nnew.function(5,3,11)\n\n# Call the function by names of the arguments.\nnew.function(a = 11, b = 5, c = 3)" }, { "code": null, "e": 28496, "s": 28429, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 28511, "s": 28496, "text": "[1] 26\n[1] 58\n" }, { "code": null, "e": 28763, "s": 28511, "text": "We can define the value of the arguments in the function definition and call the function without supplying any argument to get the default result. But we can also call such functions by supplying new values of the argument and get non default result." }, { "code": null, "e": 29022, "s": 28763, "text": "# Create a function with arguments.\nnew.function <- function(a = 3, b = 6) {\n result <- a * b\n print(result)\n}\n\n# Call the function without giving any argument.\nnew.function()\n\n# Call the function with giving new values of the argument.\nnew.function(9,5)" }, { "code": null, "e": 29089, "s": 29022, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 29104, "s": 29089, "text": "[1] 18\n[1] 45\n" }, { "code": null, "e": 29222, "s": 29104, "text": "Arguments to functions are evaluated lazily, which means so they are evaluated only when needed by the function body." }, { "code": null, "e": 29412, "s": 29222, "text": "# Create a function with arguments.\nnew.function <- function(a, b) {\n print(a^2)\n print(a)\n print(b)\n}\n\n# Evaluate the function without supplying one of the arguments.\nnew.function(6)" }, { "code": null, "e": 29479, "s": 29412, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 29554, "s": 29479, "text": "[1] 36\n[1] 6\nError in print(b) : argument \"b\" is missing, with no default\n" }, { "code": null, "e": 29748, "s": 29554, "text": "Any value written within a pair of single quote or double quotes in R is treated as a string. Internally R stores every string within double quotes, even when you create them with single quote." }, { "code": null, "e": 29870, "s": 29748, "text": "The quotes at the beginning and end of a string should be both double quotes or both single quote. They can not be mixed." }, { "code": null, "e": 29992, "s": 29870, "text": "The quotes at the beginning and end of a string should be both double quotes or both single quote. They can not be mixed." }, { "code": null, "e": 30075, "s": 29992, "text": "Double quotes can be inserted into a string starting and ending with single quote." }, { "code": null, "e": 30158, "s": 30075, "text": "Double quotes can be inserted into a string starting and ending with single quote." }, { "code": null, "e": 30241, "s": 30158, "text": "Single quote can be inserted into a string starting and ending with double quotes." }, { "code": null, "e": 30324, "s": 30241, "text": "Single quote can be inserted into a string starting and ending with double quotes." }, { "code": null, "e": 30412, "s": 30324, "text": "Double quotes can not be inserted into a string starting and ending with double quotes." }, { "code": null, "e": 30500, "s": 30412, "text": "Double quotes can not be inserted into a string starting and ending with double quotes." }, { "code": null, "e": 30586, "s": 30500, "text": "Single quote can not be inserted into a string starting and ending with single quote." }, { "code": null, "e": 30672, "s": 30586, "text": "Single quote can not be inserted into a string starting and ending with single quote." }, { "code": null, "e": 30739, "s": 30672, "text": "Following examples clarify the rules about creating a string in R." }, { "code": null, "e": 30951, "s": 30739, "text": "a <- 'Start and end with single quote'\nprint(a)\n\nb <- \"Start and end with double quotes\"\nprint(b)\n\nc <- \"single quote ' in between double quotes\"\nprint(c)\n\nd <- 'Double quotes \" in between single quote'\nprint(d)" }, { "code": null, "e": 31008, "s": 30951, "text": "When the above code is run we get the following output −" }, { "code": null, "e": 31177, "s": 31008, "text": "[1] \"Start and end with single quote\"\n[1] \"Start and end with double quotes\"\n[1] \"single quote ' in between double quote\"\n[1] \"Double quote \\\" in between single quote\"\n" }, { "code": null, "e": 31313, "s": 31177, "text": "e <- 'Mixed quotes\" \nprint(e)\n\nf <- 'Single quote ' inside single quote'\nprint(f)\n\ng <- \"Double quotes \" inside double quotes\"\nprint(g)" }, { "code": null, "e": 31367, "s": 31313, "text": "When we run the script it fails giving below results." }, { "code": null, "e": 31438, "s": 31367, "text": "Error: unexpected symbol in:\n\"print(e)\nf <- 'Single\"\nExecution halted\n" }, { "code": null, "e": 31558, "s": 31438, "text": "Many strings in R are combined using the paste() function. It can take any number of arguments to be combined together." }, { "code": null, "e": 31599, "s": 31558, "text": "The basic syntax for paste function is −" }, { "code": null, "e": 31639, "s": 31599, "text": "paste(..., sep = \" \", collapse = NULL)\n" }, { "code": null, "e": 31693, "s": 31639, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 31748, "s": 31693, "text": "... represents any number of arguments to be combined." }, { "code": null, "e": 31803, "s": 31748, "text": "... represents any number of arguments to be combined." }, { "code": null, "e": 31871, "s": 31803, "text": "sep represents any separator between the arguments. It is optional." }, { "code": null, "e": 31939, "s": 31871, "text": "sep represents any separator between the arguments. It is optional." }, { "code": null, "e": 32053, "s": 31939, "text": "collapse is used to eliminate the space in between two strings. But not the space within two words of one string." }, { "code": null, "e": 32167, "s": 32053, "text": "collapse is used to eliminate the space in between two strings. But not the space within two words of one string." }, { "code": null, "e": 32307, "s": 32167, "text": "a <- \"Hello\"\nb <- 'How'\nc <- \"are you? \"\n\nprint(paste(a,b,c))\n\nprint(paste(a,b,c, sep = \"-\"))\n\nprint(paste(a,b,c, sep = \"\", collapse = \"\"))" }, { "code": null, "e": 32374, "s": 32307, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 32451, "s": 32374, "text": "[1] \"Hello How are you? \"\n[1] \"Hello-How-are you? \"\n[1] \"HelloHoware you? \"\n" }, { "code": null, "e": 32533, "s": 32451, "text": "Numbers and strings can be formatted to a specific style using format() function." }, { "code": null, "e": 32575, "s": 32533, "text": "The basic syntax for format function is −" }, { "code": null, "e": 32670, "s": 32575, "text": "format(x, digits, nsmall, scientific, width, justify = c(\"left\", \"right\", \"centre\", \"none\")) \n" }, { "code": null, "e": 32724, "s": 32670, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 32747, "s": 32724, "text": "x is the vector input." }, { "code": null, "e": 32770, "s": 32747, "text": "x is the vector input." }, { "code": null, "e": 32818, "s": 32770, "text": "digits is the total number of digits displayed." }, { "code": null, "e": 32866, "s": 32818, "text": "digits is the total number of digits displayed." }, { "code": null, "e": 32940, "s": 32866, "text": "nsmall is the minimum number of digits to the right of the decimal point." }, { "code": null, "e": 33014, "s": 32940, "text": "nsmall is the minimum number of digits to the right of the decimal point." }, { "code": null, "e": 33072, "s": 33014, "text": "scientific is set to TRUE to display scientific notation." }, { "code": null, "e": 33130, "s": 33072, "text": "scientific is set to TRUE to display scientific notation." }, { "code": null, "e": 33216, "s": 33130, "text": "width indicates the minimum width to be displayed by padding blanks in the beginning." }, { "code": null, "e": 33302, "s": 33216, "text": "width indicates the minimum width to be displayed by padding blanks in the beginning." }, { "code": null, "e": 33365, "s": 33302, "text": "justify is the display of the string to left, right or center." }, { "code": null, "e": 33428, "s": 33365, "text": "justify is the display of the string to left, right or center." }, { "code": null, "e": 34142, "s": 33428, "text": "# Total number of digits displayed. Last digit rounded off.\nresult <- format(23.123456789, digits = 9)\nprint(result)\n\n# Display numbers in scientific notation.\nresult <- format(c(6, 13.14521), scientific = TRUE)\nprint(result)\n\n# The minimum number of digits to the right of the decimal point.\nresult <- format(23.47, nsmall = 5)\nprint(result)\n\n# Format treats everything as a string.\nresult <- format(6)\nprint(result)\n\n# Numbers are padded with blank in the beginning for width.\nresult <- format(13.7, width = 6)\nprint(result)\n\n# Left justify strings.\nresult <- format(\"Hello\", width = 8, justify = \"l\")\nprint(result)\n\n# Justfy string with center.\nresult <- format(\"Hello\", width = 8, justify = \"c\")\nprint(result)" }, { "code": null, "e": 34209, "s": 34142, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 34327, "s": 34209, "text": "[1] \"23.1234568\"\n[1] \"6.000000e+00\" \"1.314521e+01\"\n[1] \"23.47000\"\n[1] \"6\"\n[1] \" 13.7\"\n[1] \"Hello \"\n[1] \" Hello \"\n" }, { "code": null, "e": 34403, "s": 34327, "text": "This function counts the number of characters including spaces in a string." }, { "code": null, "e": 34446, "s": 34403, "text": "The basic syntax for nchar() function is −" }, { "code": null, "e": 34456, "s": 34446, "text": "nchar(x)\n" }, { "code": null, "e": 34510, "s": 34456, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 34533, "s": 34510, "text": "x is the vector input." }, { "code": null, "e": 34556, "s": 34533, "text": "x is the vector input." }, { "code": null, "e": 34620, "s": 34556, "text": "result <- nchar(\"Count the number of characters\")\nprint(result)" }, { "code": null, "e": 34687, "s": 34620, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 34695, "s": 34687, "text": "[1] 30\n" }, { "code": null, "e": 34754, "s": 34695, "text": "These functions change the case of characters of a string." }, { "code": null, "e": 34812, "s": 34754, "text": "The basic syntax for toupper() & tolower() function is −" }, { "code": null, "e": 34835, "s": 34812, "text": "toupper(x)\ntolower(x)\n" }, { "code": null, "e": 34889, "s": 34835, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 34912, "s": 34889, "text": "x is the vector input." }, { "code": null, "e": 34935, "s": 34912, "text": "x is the vector input." }, { "code": null, "e": 35094, "s": 34935, "text": "# Changing to Upper case.\nresult <- toupper(\"Changing To Upper\")\nprint(result)\n\n# Changing to lower case.\nresult <- tolower(\"Changing To Lower\")\nprint(result)" }, { "code": null, "e": 35161, "s": 35094, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 35210, "s": 35161, "text": "[1] \"CHANGING TO UPPER\"\n[1] \"changing to lower\"\n" }, { "code": null, "e": 35252, "s": 35210, "text": "This function extracts parts of a String." }, { "code": null, "e": 35299, "s": 35252, "text": "The basic syntax for substring() function is −" }, { "code": null, "e": 35324, "s": 35299, "text": "substring(x,first,last)\n" }, { "code": null, "e": 35378, "s": 35324, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 35411, "s": 35378, "text": "x is the character vector input." }, { "code": null, "e": 35444, "s": 35411, "text": "x is the character vector input." }, { "code": null, "e": 35506, "s": 35444, "text": "first is the position of the first character to be extracted." }, { "code": null, "e": 35568, "s": 35506, "text": "first is the position of the first character to be extracted." }, { "code": null, "e": 35628, "s": 35568, "text": "last is the position of the last character to be extracted." }, { "code": null, "e": 35688, "s": 35628, "text": "last is the position of the last character to be extracted." }, { "code": null, "e": 35786, "s": 35688, "text": "# Extract characters from 5th to 7th position.\nresult <- substring(\"Extract\", 5, 7)\nprint(result)" }, { "code": null, "e": 35853, "s": 35786, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 35864, "s": 35853, "text": "[1] \"act\"\n" }, { "code": null, "e": 36012, "s": 35864, "text": "Vectors are the most basic R data objects and there are six types of atomic vectors. They are logical, integer, double, complex, character and raw." }, { "code": null, "e": 36131, "s": 36012, "text": "Even when you write just one value in R, it becomes a vector of length 1 and belongs to one of the above vector types." }, { "code": null, "e": 36418, "s": 36131, "text": "# Atomic vector of type character.\nprint(\"abc\");\n\n# Atomic vector of type double.\nprint(12.5)\n\n# Atomic vector of type integer.\nprint(63L)\n\n# Atomic vector of type logical.\nprint(TRUE)\n\n# Atomic vector of type complex.\nprint(2+3i)\n\n# Atomic vector of type raw.\nprint(charToRaw('hello'))" }, { "code": null, "e": 36485, "s": 36418, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 36549, "s": 36485, "text": "[1] \"abc\"\n[1] 12.5\n[1] 63\n[1] TRUE\n[1] 2+3i\n[1] 68 65 6c 6c 6f\n" }, { "code": null, "e": 36588, "s": 36549, "text": "Using colon operator with numeric data" }, { "code": null, "e": 36818, "s": 36588, "text": "# Creating a sequence from 5 to 13.\nv <- 5:13\nprint(v)\n\n# Creating a sequence from 6.6 to 12.6.\nv <- 6.6:12.6\nprint(v)\n\n# If the final element specified does not belong to the sequence then it is discarded.\nv <- 3.8:11.4\nprint(v)" }, { "code": null, "e": 36885, "s": 36818, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 37000, "s": 36885, "text": "[1] 5 6 7 8 9 10 11 12 13\n[1] 6.6 7.6 8.6 9.6 10.6 11.6 12.6\n[1] 3.8 4.8 5.8 6.8 7.8 8.8 9.8 10.8\n" }, { "code": null, "e": 37031, "s": 37000, "text": "Using sequence (Seq.) operator" }, { "code": null, "e": 37121, "s": 37031, "text": "# Create vector with elements from 5 to 9 incrementing by 0.4.\nprint(seq(5, 9, by = 0.4))" }, { "code": null, "e": 37188, "s": 37121, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 37237, "s": 37188, "text": "[1] 5.0 5.4 5.8 6.2 6.6 7.0 7.4 7.8 8.2 8.6 9.0\n" }, { "code": null, "e": 37260, "s": 37237, "text": "Using the c() function" }, { "code": null, "e": 37354, "s": 37260, "text": "The non-character values are coerced to character type if one of the elements is a character." }, { "code": null, "e": 37454, "s": 37354, "text": "# The logical and numeric values are converted to characters.\ns <- c('apple','red',5,TRUE)\nprint(s)" }, { "code": null, "e": 37521, "s": 37454, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 37558, "s": 37521, "text": "[1] \"apple\" \"red\" \"5\" \"TRUE\" \n" }, { "code": null, "e": 37803, "s": 37558, "text": "Elements of a Vector are accessed using indexing. The [ ] brackets are used for indexing. Indexing starts with position 1. Giving a negative value in the index drops that element from result.TRUE, FALSE or 0 and 1 can also be used for indexing." }, { "code": null, "e": 38201, "s": 37803, "text": "# Accessing vector elements using position.\nt <- c(\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thurs\",\"Fri\",\"Sat\")\nu <- t[c(2,3,6)]\nprint(u)\n\n# Accessing vector elements using logical indexing.\nv <- t[c(TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE)]\nprint(v)\n\n# Accessing vector elements using negative indexing.\nx <- t[c(-2,-5)]\nprint(x)\n\n# Accessing vector elements using 0/1 indexing.\ny <- t[c(0,0,0,0,0,0,1)]\nprint(y)" }, { "code": null, "e": 38268, "s": 38201, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 38351, "s": 38268, "text": "[1] \"Mon\" \"Tue\" \"Fri\"\n[1] \"Sun\" \"Fri\"\n[1] \"Sun\" \"Tue\" \"Wed\" \"Fri\" \"Sat\"\n[1] \"Sun\"\n" }, { "code": null, "e": 38464, "s": 38351, "text": "Two vectors of same length can be added, subtracted, multiplied or divided giving the result as a vector output." }, { "code": null, "e": 38777, "s": 38464, "text": "# Create two vectors.\nv1 <- c(3,8,4,5,0,11)\nv2 <- c(4,11,0,8,1,2)\n\n# Vector addition.\nadd.result <- v1+v2\nprint(add.result)\n\n# Vector subtraction.\nsub.result <- v1-v2\nprint(sub.result)\n\n# Vector multiplication.\nmulti.result <- v1*v2\nprint(multi.result)\n\n# Vector division.\ndivi.result <- v1/v2\nprint(divi.result)" }, { "code": null, "e": 38844, "s": 38777, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 38975, "s": 38844, "text": "[1] 7 19 4 13 1 13\n[1] -1 -3 4 -3 -1 9\n[1] 12 88 0 40 0 22\n[1] 0.7500000 0.7272727 Inf 0.6250000 0.0000000 5.5000000\n" }, { "code": null, "e": 39124, "s": 38975, "text": "If we apply arithmetic operations to two vectors of unequal length, then the elements of the shorter vector are recycled to complete the operations." }, { "code": null, "e": 39269, "s": 39124, "text": "v1 <- c(3,8,4,5,0,11)\nv2 <- c(4,11)\n# V2 becomes c(4,11,4,11,4,11)\n\nadd.result <- v1+v2\nprint(add.result)\n\nsub.result <- v1-v2\nprint(sub.result)" }, { "code": null, "e": 39336, "s": 39269, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 39381, "s": 39336, "text": "[1] 7 19 8 16 4 22\n[1] -1 -3 0 -6 -4 0\n" }, { "code": null, "e": 39443, "s": 39381, "text": "Elements in a vector can be sorted using the sort() function." }, { "code": null, "e": 39886, "s": 39443, "text": "v <- c(3,8,4,5,0,11, -9, 304)\n\n# Sort the elements of the vector.\nsort.result <- sort(v)\nprint(sort.result)\n\n# Sort the elements in the reverse order.\nrevsort.result <- sort(v, decreasing = TRUE)\nprint(revsort.result)\n\n# Sorting character vectors.\nv <- c(\"Red\",\"Blue\",\"yellow\",\"violet\")\nsort.result <- sort(v)\nprint(sort.result)\n\n# Sorting character vectors in reverse order.\nrevsort.result <- sort(v, decreasing = TRUE)\nprint(revsort.result)" }, { "code": null, "e": 39953, "s": 39886, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 40105, "s": 39953, "text": "[1] -9 0 3 4 5 8 11 304\n[1] 304 11 8 5 4 3 0 -9\n[1] \"Blue\" \"Red\" \"violet\" \"yellow\"\n[1] \"yellow\" \"violet\" \"Red\" \"Blue\" \n" }, { "code": null, "e": 40335, "s": 40105, "text": "Lists are the R objects which contain elements of different types like − numbers, strings, vectors and another list inside it. A list can also contain a matrix or a function as its elements. List is created using list() function." }, { "code": null, "e": 40435, "s": 40335, "text": "Following is an example to create a list containing strings, numbers, vectors and a logical values." }, { "code": null, "e": 40596, "s": 40435, "text": "# Create a list containing strings, numbers, vectors and a logical\n# values.\nlist_data <- list(\"Red\", \"Green\", c(21,32,11), TRUE, 51.23, 119.1)\nprint(list_data)" }, { "code": null, "e": 40663, "s": 40596, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 40769, "s": 40663, "text": "[[1]]\n[1] \"Red\"\n\n[[2]]\n[1] \"Green\"\n\n[[3]]\n[1] 21 32 11\n\n[[4]]\n[1] TRUE\n\n[[5]]\n[1] 51.23\n\n[[6]]\n[1] 119.1\n" }, { "code": null, "e": 40850, "s": 40769, "text": "The list elements can be given names and they can be accessed using these names." }, { "code": null, "e": 41149, "s": 40850, "text": "# Create a list containing a vector, a matrix and a list.\nlist_data <- list(c(\"Jan\",\"Feb\",\"Mar\"), matrix(c(3,9,5,1,-2,8), nrow = 2),\n list(\"green\",12.3))\n\n# Give names to the elements in the list.\nnames(list_data) <- c(\"1st Quarter\", \"A_Matrix\", \"A Inner list\")\n\n# Show the list.\nprint(list_data)" }, { "code": null, "e": 41216, "s": 41149, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 41400, "s": 41216, "text": "$`1st_Quarter`\n[1] \"Jan\" \"Feb\" \"Mar\"\n\n$A_Matrix\n [,1] [,2] [,3]\n[1,] 3 5 -2\n[2,] 9 1 8\n\n$A_Inner_list\n$A_Inner_list[[1]]\n[1] \"green\"\n\n$A_Inner_list[[2]]\n[1] 12.3\n" }, { "code": null, "e": 41542, "s": 41400, "text": "Elements of the list can be accessed by the index of the element in the list. In case of named lists it can also be accessed using the names." }, { "code": null, "e": 41593, "s": 41542, "text": "We continue to use the list in the above example −" }, { "code": null, "e": 42107, "s": 41593, "text": "# Create a list containing a vector, a matrix and a list.\nlist_data <- list(c(\"Jan\",\"Feb\",\"Mar\"), matrix(c(3,9,5,1,-2,8), nrow = 2),\n list(\"green\",12.3))\n\n# Give names to the elements in the list.\nnames(list_data) <- c(\"1st Quarter\", \"A_Matrix\", \"A Inner list\")\n\n# Access the first element of the list.\nprint(list_data[1])\n\n# Access the thrid element. As it is also a list, all its elements will be printed.\nprint(list_data[3])\n\n# Access the list element using the name of the element.\nprint(list_data$A_Matrix)" }, { "code": null, "e": 42174, "s": 42107, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 42348, "s": 42174, "text": "$`1st_Quarter`\n[1] \"Jan\" \"Feb\" \"Mar\"\n\n$A_Inner_list\n$A_Inner_list[[1]]\n[1] \"green\"\n\n$A_Inner_list[[2]]\n[1] 12.3\n\n [,1] [,2] [,3]\n[1,] 3 5 -2\n[2,] 9 1 8\n" }, { "code": null, "e": 42497, "s": 42348, "text": "We can add, delete and update list elements as shown below. We can add and delete elements only at the end of a list. But we can update any element." }, { "code": null, "e": 43026, "s": 42497, "text": "# Create a list containing a vector, a matrix and a list.\nlist_data <- list(c(\"Jan\",\"Feb\",\"Mar\"), matrix(c(3,9,5,1,-2,8), nrow = 2),\n list(\"green\",12.3))\n\n# Give names to the elements in the list.\nnames(list_data) <- c(\"1st Quarter\", \"A_Matrix\", \"A Inner list\")\n\n# Add element at the end of the list.\nlist_data[4] <- \"New element\"\nprint(list_data[4])\n\n# Remove the last element.\nlist_data[4] <- NULL\n\n# Print the 4th Element.\nprint(list_data[4])\n\n# Update the 3rd Element.\nlist_data[3] <- \"updated element\"\nprint(list_data[3])" }, { "code": null, "e": 43093, "s": 43026, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 43169, "s": 43093, "text": "[[1]]\n[1] \"New element\"\n\n$<NA>\nNULL\n\n$`A Inner list`\n[1] \"updated element\"\n" }, { "code": null, "e": 43261, "s": 43169, "text": "You can merge many lists into one list by placing all the lists inside one list() function." }, { "code": null, "e": 43434, "s": 43261, "text": "# Create two lists.\nlist1 <- list(1,2,3)\nlist2 <- list(\"Sun\",\"Mon\",\"Tue\")\n\n# Merge the two lists.\nmerged.list <- c(list1,list2)\n\n# Print the merged list.\nprint(merged.list)" }, { "code": null, "e": 43501, "s": 43434, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 43591, "s": 43501, "text": "[[1]]\n[1] 1\n\n[[2]]\n[1] 2\n\n[[3]]\n[1] 3\n\n[[4]]\n[1] \"Sun\"\n\n[[5]]\n[1] \"Mon\"\n\n[[6]]\n[1] \"Tue\"\n" }, { "code": null, "e": 43901, "s": 43591, "text": "A list can be converted to a vector so that the elements of the vector can be used for further manipulation. All the arithmetic operations on vectors can be applied after the list is converted into vectors. To do this conversion, we use the unlist() function. It takes the list as input and produces a vector." }, { "code": null, "e": 44130, "s": 43901, "text": "# Create lists.\nlist1 <- list(1:5)\nprint(list1)\n\nlist2 <-list(10:14)\nprint(list2)\n\n# Convert the lists to vectors.\nv1 <- unlist(list1)\nv2 <- unlist(list2)\n\nprint(v1)\nprint(v2)\n\n# Now add the vectors\nresult <- v1+v2\nprint(result)" }, { "code": null, "e": 44197, "s": 44130, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 44297, "s": 44197, "text": "[[1]]\n[1] 1 2 3 4 5\n\n[[1]]\n[1] 10 11 12 13 14\n\n[1] 1 2 3 4 5\n[1] 10 11 12 13 14\n[1] 11 13 15 17 19\n" }, { "code": null, "e": 44640, "s": 44297, "text": "Matrices are the R objects in which the elements are arranged in a two-dimensional rectangular layout. They contain elements of the same atomic types. Though we can create a matrix containing only characters or only logical values, they are not of much use. We use matrices containing numeric elements to be used in mathematical calculations." }, { "code": null, "e": 44689, "s": 44640, "text": "A Matrix is created using the matrix() function." }, { "code": null, "e": 44738, "s": 44689, "text": "The basic syntax for creating a matrix in R is −" }, { "code": null, "e": 44781, "s": 44738, "text": "matrix(data, nrow, ncol, byrow, dimnames)\n" }, { "code": null, "e": 44835, "s": 44781, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 44907, "s": 44835, "text": "data is the input vector which becomes the data elements of the matrix." }, { "code": null, "e": 44979, "s": 44907, "text": "data is the input vector which becomes the data elements of the matrix." }, { "code": null, "e": 45021, "s": 44979, "text": "nrow is the number of rows to be created." }, { "code": null, "e": 45063, "s": 45021, "text": "nrow is the number of rows to be created." }, { "code": null, "e": 45108, "s": 45063, "text": "ncol is the number of columns to be created." }, { "code": null, "e": 45153, "s": 45108, "text": "ncol is the number of columns to be created." }, { "code": null, "e": 45238, "s": 45153, "text": "byrow is a logical clue. If TRUE then the input vector elements are arranged by row." }, { "code": null, "e": 45323, "s": 45238, "text": "byrow is a logical clue. If TRUE then the input vector elements are arranged by row." }, { "code": null, "e": 45378, "s": 45323, "text": "dimname is the names assigned to the rows and columns." }, { "code": null, "e": 45433, "s": 45378, "text": "dimname is the names assigned to the rows and columns." }, { "code": null, "e": 45486, "s": 45433, "text": "Create a matrix taking a vector of numbers as input." }, { "code": null, "e": 45899, "s": 45486, "text": "# Elements are arranged sequentially by row.\nM <- matrix(c(3:14), nrow = 4, byrow = TRUE)\nprint(M)\n\n# Elements are arranged sequentially by column.\nN <- matrix(c(3:14), nrow = 4, byrow = FALSE)\nprint(N)\n\n# Define the column and row names.\nrownames = c(\"row1\", \"row2\", \"row3\", \"row4\")\ncolnames = c(\"col1\", \"col2\", \"col3\")\n\nP <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))\nprint(P)" }, { "code": null, "e": 45966, "s": 45899, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 46267, "s": 45966, "text": " [,1] [,2] [,3]\n[1,] 3 4 5\n[2,] 6 7 8\n[3,] 9 10 11\n[4,] 12 13 14\n [,1] [,2] [,3]\n[1,] 3 7 11\n[2,] 4 8 12\n[3,] 5 9 13\n[4,] 6 10 14\n col1 col2 col3\nrow1 3 4 5\nrow2 6 7 8\nrow3 9 10 11\nrow4 12 13 14\n" }, { "code": null, "e": 46422, "s": 46267, "text": "Elements of a matrix can be accessed by using the column and row index of the element. We consider the matrix P above to find the specific elements below." }, { "code": null, "e": 46855, "s": 46422, "text": "# Define the column and row names.\nrownames = c(\"row1\", \"row2\", \"row3\", \"row4\")\ncolnames = c(\"col1\", \"col2\", \"col3\")\n\n# Create the matrix.\nP <- matrix(c(3:14), nrow = 4, byrow = TRUE, dimnames = list(rownames, colnames))\n\n# Access the element at 3rd column and 1st row.\nprint(P[1,3])\n\n# Access the element at 2nd column and 4th row.\nprint(P[4,2])\n\n# Access only the 2nd row.\nprint(P[2,])\n\n# Access only the 3rd column.\nprint(P[,3])" }, { "code": null, "e": 46922, "s": 46855, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 47010, "s": 46922, "text": "[1] 5\n[1] 13\ncol1 col2 col3 \n 6 7 8 \nrow1 row2 row3 row4 \n 5 8 11 14 \n" }, { "code": null, "e": 47141, "s": 47010, "text": "Various mathematical operations are performed on the matrices using the R operators. The result of the operation is also a matrix." }, { "code": null, "e": 47244, "s": 47141, "text": "The dimensions (number of rows and columns) should be same for the matrices involved in the operation." }, { "code": null, "e": 47596, "s": 47244, "text": "# Create two 2x3 matrices.\nmatrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)\nprint(matrix1)\n\nmatrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)\nprint(matrix2)\n\n# Add the matrices.\nresult <- matrix1 + matrix2\ncat(\"Result of addition\",\"\\n\")\nprint(result)\n\n# Subtract the matrices\nresult <- matrix1 - matrix2\ncat(\"Result of subtraction\",\"\\n\")\nprint(result)" }, { "code": null, "e": 47663, "s": 47596, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 47947, "s": 47663, "text": " [,1] [,2] [,3]\n[1,] 3 -1 2\n[2,] 9 4 6\n [,1] [,2] [,3]\n[1,] 5 0 3\n[2,] 2 9 4\nResult of addition \n [,1] [,2] [,3]\n[1,] 8 -1 5\n[2,] 11 13 10\nResult of subtraction \n [,1] [,2] [,3]\n[1,] -2 -1 -1\n[2,] 7 -5 2\n" }, { "code": null, "e": 48305, "s": 47947, "text": "# Create two 2x3 matrices.\nmatrix1 <- matrix(c(3, 9, -1, 4, 2, 6), nrow = 2)\nprint(matrix1)\n\nmatrix2 <- matrix(c(5, 2, 0, 9, 3, 4), nrow = 2)\nprint(matrix2)\n\n# Multiply the matrices.\nresult <- matrix1 * matrix2\ncat(\"Result of multiplication\",\"\\n\")\nprint(result)\n\n# Divide the matrices\nresult <- matrix1 / matrix2\ncat(\"Result of division\",\"\\n\")\nprint(result)" }, { "code": null, "e": 48372, "s": 48305, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 48689, "s": 48372, "text": " [,1] [,2] [,3]\n[1,] 3 -1 2\n[2,] 9 4 6\n [,1] [,2] [,3]\n[1,] 5 0 3\n[2,] 2 9 4\nResult of multiplication \n [,1] [,2] [,3]\n[1,] 15 0 6\n[2,] 18 36 24\nResult of division \n [,1] [,2] [,3]\n[1,] 0.6 -Inf 0.6666667\n[2,] 4.5 0.4444444 1.5000000\n" }, { "code": null, "e": 48932, "s": 48689, "text": "Arrays are the R data objects which can store data in more than two dimensions. For example − If we create an array of dimension (2, 3, 4) then it creates 4 rectangular matrices each with 2 rows and 3 columns. Arrays can store only data type." }, { "code": null, "e": 49067, "s": 48932, "text": "An array is created using the array() function. It takes vectors as input and uses the values in the dim parameter to create an array." }, { "code": null, "e": 49158, "s": 49067, "text": "The following example creates an array of two 3x3 matrices each with 3 rows and 3 columns." }, { "code": null, "e": 49363, "s": 49158, "text": "# Create two vectors of different lengths.\nvector1 <- c(5,9,3)\nvector2 <- c(10,11,12,13,14,15)\n\n# Take these vectors as input to the array.\nresult <- array(c(vector1,vector2),dim = c(3,3,2))\nprint(result)" }, { "code": null, "e": 49430, "s": 49363, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 49606, "s": 49430, "text": ", , 1\n\n [,1] [,2] [,3]\n[1,] 5 10 13\n[2,] 9 11 14\n[3,] 3 12 15\n\n, , 2\n\n [,1] [,2] [,3]\n[1,] 5 10 13\n[2,] 9 11 14\n[3,] 3 12 15\n" }, { "code": null, "e": 49704, "s": 49606, "text": "We can give names to the rows, columns and matrices in the array by using the dimnames parameter." }, { "code": null, "e": 50082, "s": 49704, "text": "# Create two vectors of different lengths.\nvector1 <- c(5,9,3)\nvector2 <- c(10,11,12,13,14,15)\ncolumn.names <- c(\"COL1\",\"COL2\",\"COL3\")\nrow.names <- c(\"ROW1\",\"ROW2\",\"ROW3\")\nmatrix.names <- c(\"Matrix1\",\"Matrix2\")\n\n# Take these vectors as input to the array.\nresult <- array(c(vector1,vector2),dim = c(3,3,2),dimnames = list(row.names,column.names,\n matrix.names))\nprint(result)" }, { "code": null, "e": 50149, "s": 50082, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 50337, "s": 50149, "text": ", , Matrix1\n\n COL1 COL2 COL3\nROW1 5 10 13\nROW2 9 11 14\nROW3 3 12 15\n\n, , Matrix2\n\n COL1 COL2 COL3\nROW1 5 10 13\nROW2 9 11 14\nROW3 3 12 15\n" }, { "code": null, "e": 50915, "s": 50337, "text": "# Create two vectors of different lengths.\nvector1 <- c(5,9,3)\nvector2 <- c(10,11,12,13,14,15)\ncolumn.names <- c(\"COL1\",\"COL2\",\"COL3\")\nrow.names <- c(\"ROW1\",\"ROW2\",\"ROW3\")\nmatrix.names <- c(\"Matrix1\",\"Matrix2\")\n\n# Take these vectors as input to the array.\nresult <- array(c(vector1,vector2),dim = c(3,3,2),dimnames = list(row.names,\n column.names, matrix.names))\n\n# Print the third row of the second matrix of the array.\nprint(result[3,,2])\n\n# Print the element in the 1st row and 3rd column of the 1st matrix.\nprint(result[1,3,1])\n\n# Print the 2nd Matrix.\nprint(result[,,2])" }, { "code": null, "e": 50982, "s": 50915, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 51102, "s": 50982, "text": "COL1 COL2 COL3 \n 3 12 15 \n[1] 13\n COL1 COL2 COL3\nROW1 5 10 13\nROW2 9 11 14\nROW3 3 12 15\n" }, { "code": null, "e": 51246, "s": 51102, "text": "As array is made up matrices in multiple dimensions, the operations on elements of array are carried out by accessing elements of the matrices." }, { "code": null, "e": 51731, "s": 51246, "text": "# Create two vectors of different lengths.\nvector1 <- c(5,9,3)\nvector2 <- c(10,11,12,13,14,15)\n\n# Take these vectors as input to the array.\narray1 <- array(c(vector1,vector2),dim = c(3,3,2))\n\n# Create two vectors of different lengths.\nvector3 <- c(9,1,0)\nvector4 <- c(6,0,11,3,14,1,2,6,9)\narray2 <- array(c(vector1,vector2),dim = c(3,3,2))\n\n# create matrices from these arrays.\nmatrix1 <- array1[,,2]\nmatrix2 <- array2[,,2]\n\n# Add the matrices.\nresult <- matrix1+matrix2\nprint(result)" }, { "code": null, "e": 51798, "s": 51731, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 51879, "s": 51798, "text": " [,1] [,2] [,3]\n[1,] 10 20 26\n[2,] 18 22 28\n[3,] 6 24 30\n" }, { "code": null, "e": 51962, "s": 51879, "text": "We can do calculations across the elements in an array using the apply() function." }, { "code": null, "e": 51985, "s": 51962, "text": "apply(x, margin, fun)\n" }, { "code": null, "e": 52039, "s": 51985, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 52054, "s": 52039, "text": "x is an array." }, { "code": null, "e": 52069, "s": 52054, "text": "x is an array." }, { "code": null, "e": 52110, "s": 52069, "text": "margin is the name of the data set used." }, { "code": null, "e": 52151, "s": 52110, "text": "margin is the name of the data set used." }, { "code": null, "e": 52219, "s": 52151, "text": "fun is the function to be applied across the elements of the array." }, { "code": null, "e": 52287, "s": 52219, "text": "fun is the function to be applied across the elements of the array." }, { "code": null, "e": 52407, "s": 52287, "text": "We use the apply() function below to calculate the sum of the elements in the rows of an array across all the matrices." }, { "code": null, "e": 52741, "s": 52407, "text": "# Create two vectors of different lengths.\nvector1 <- c(5,9,3)\nvector2 <- c(10,11,12,13,14,15)\n\n# Take these vectors as input to the array.\nnew.array <- array(c(vector1,vector2),dim = c(3,3,2))\nprint(new.array)\n\n# Use apply to calculate the sum of the rows across all the matrices.\nresult <- apply(new.array, c(1), sum)\nprint(result)" }, { "code": null, "e": 52808, "s": 52741, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 52998, "s": 52808, "text": ", , 1\n\n [,1] [,2] [,3]\n[1,] 5 10 13\n[2,] 9 11 14\n[3,] 3 12 15\n\n, , 2\n\n [,1] [,2] [,3]\n[1,] 5 10 13\n[2,] 9 11 14\n[3,] 3 12 15\n\n[1] 56 68 60\n" }, { "code": null, "e": 53309, "s": 52998, "text": "Factors are the data objects which are used to categorize the data and store it as levels. They can store both strings and integers. They are useful in the columns which have a limited number of unique values. Like \"Male, \"Female\" and True, False etc. They are useful in data analysis for statistical modeling." }, { "code": null, "e": 53387, "s": 53309, "text": "Factors are created using the factor () function by taking a vector as input." }, { "code": null, "e": 53650, "s": 53387, "text": "# Create a vector as input.\ndata <- c(\"East\",\"West\",\"East\",\"North\",\"North\",\"East\",\"West\",\"West\",\"West\",\"East\",\"North\")\n\nprint(data)\nprint(is.factor(data))\n\n# Apply the factor function.\nfactor_data <- factor(data)\n\nprint(factor_data)\nprint(is.factor(factor_data))" }, { "code": null, "e": 53717, "s": 53650, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 53922, "s": 53717, "text": "[1] \"East\" \"West\" \"East\" \"North\" \"North\" \"East\" \"West\" \"West\" \"West\" \"East\" \"North\"\n[1] FALSE\n[1] East West East North North East West West West East North\nLevels: East North West\n[1] TRUE\n" }, { "code": null, "e": 54049, "s": 53922, "text": "On creating any data frame with a column of text data, R treats the text column as categorical data and creates factors on it." }, { "code": null, "e": 54469, "s": 54049, "text": "# Create the vectors for data frame.\nheight <- c(132,151,162,139,166,147,122)\nweight <- c(48,49,66,53,67,52,40)\ngender <- c(\"male\",\"male\",\"female\",\"female\",\"male\",\"female\",\"male\")\n\n# Create the data frame.\ninput_data <- data.frame(height,weight,gender)\nprint(input_data)\n\n# Test if the gender column is a factor.\nprint(is.factor(input_data$gender))\n\n# Print the gender column so see the levels.\nprint(input_data$gender)" }, { "code": null, "e": 54536, "s": 54469, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 54803, "s": 54536, "text": " height weight gender\n1 132 48 male\n2 151 49 male\n3 162 66 female\n4 139 53 female\n5 166 67 male\n6 147 52 female\n7 122 40 male\n[1] TRUE\n[1] male male female female male female male \nLevels: female male\n" }, { "code": null, "e": 54922, "s": 54803, "text": "The order of the levels in a factor can be changed by applying the factor function again with new order of the levels." }, { "code": null, "e": 55242, "s": 54922, "text": "data <- c(\"East\",\"West\",\"East\",\"North\",\"North\",\"East\",\"West\",\n \"West\",\"West\",\"East\",\"North\")\n# Create the factors\nfactor_data <- factor(data)\nprint(factor_data)\n\n# Apply the factor function with required order of the level.\nnew_order_data <- factor(factor_data,levels = c(\"East\",\"West\",\"North\"))\nprint(new_order_data)" }, { "code": null, "e": 55309, "s": 55242, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 55500, "s": 55309, "text": " [1] East West East North North East West West West East North\nLevels: East North West\n [1] East West East North North East West West West East North\nLevels: East West North\n" }, { "code": null, "e": 55652, "s": 55500, "text": "We can generate factor levels by using the gl() function. It takes two integers as input which indicates how many levels and how many times each level." }, { "code": null, "e": 55670, "s": 55652, "text": "gl(n, k, labels)\n" }, { "code": null, "e": 55724, "s": 55670, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 55768, "s": 55724, "text": "n is a integer giving the number of levels." }, { "code": null, "e": 55812, "s": 55768, "text": "n is a integer giving the number of levels." }, { "code": null, "e": 55862, "s": 55812, "text": "k is a integer giving the number of replications." }, { "code": null, "e": 55912, "s": 55862, "text": "k is a integer giving the number of replications." }, { "code": null, "e": 55974, "s": 55912, "text": "labels is a vector of labels for the resulting factor levels." }, { "code": null, "e": 56036, "s": 55974, "text": "labels is a vector of labels for the resulting factor levels." }, { "code": null, "e": 56100, "s": 56036, "text": "v <- gl(3, 4, labels = c(\"Tampa\", \"Seattle\",\"Boston\"))\nprint(v)" }, { "code": null, "e": 56167, "s": 56100, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 56298, "s": 56167, "text": "Tampa Tampa Tampa Tampa Seattle Seattle Seattle Seattle Boston \n[10] Boston Boston Boston \nLevels: Tampa Seattle Boston\n" }, { "code": null, "e": 56475, "s": 56298, "text": "A data frame is a table or a two-dimensional array-like structure in which each column contains values of one variable and each row contains one set of values from each column." }, { "code": null, "e": 56526, "s": 56475, "text": "Following are the characteristics of a data frame." }, { "code": null, "e": 56564, "s": 56526, "text": "The column names should be non-empty." }, { "code": null, "e": 56596, "s": 56564, "text": "The row names should be unique." }, { "code": null, "e": 56673, "s": 56596, "text": "The data stored in a data frame can be of numeric, factor or character type." }, { "code": null, "e": 56727, "s": 56673, "text": "Each column should contain same number of data items." }, { "code": null, "e": 57084, "s": 56727, "text": "# Create the data frame.\nemp.data <- data.frame(\n emp_id = c (1:5), \n emp_name = c(\"Rick\",\"Dan\",\"Michelle\",\"Ryan\",\"Gary\"),\n salary = c(623.3,515.2,611.0,729.0,843.25), \n \n start_date = as.Date(c(\"2012-01-01\", \"2013-09-23\", \"2014-11-15\", \"2014-05-11\",\n \"2015-03-27\")),\n stringsAsFactors = FALSE\n)\n# Print the data frame.\t\t\t\nprint(emp.data) " }, { "code": null, "e": 57151, "s": 57084, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 57428, "s": 57151, "text": " emp_id emp_name salary start_date\n1 1 Rick 623.30 2012-01-01\n2 2 Dan 515.20 2013-09-23\n3 3 Michelle 611.00 2014-11-15\n4 4 Ryan 729.00 2014-05-11\n5 5 Gary 843.25 2015-03-27\n" }, { "code": null, "e": 57497, "s": 57428, "text": "The structure of the data frame can be seen by using str() function." }, { "code": null, "e": 57863, "s": 57497, "text": "# Create the data frame.\nemp.data <- data.frame(\n emp_id = c (1:5), \n emp_name = c(\"Rick\",\"Dan\",\"Michelle\",\"Ryan\",\"Gary\"),\n salary = c(623.3,515.2,611.0,729.0,843.25), \n \n start_date = as.Date(c(\"2012-01-01\", \"2013-09-23\", \"2014-11-15\", \"2014-05-11\",\n \"2015-03-27\")),\n stringsAsFactors = FALSE\n)\n# Get the structure of the data frame.\nstr(emp.data)" }, { "code": null, "e": 57930, "s": 57863, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 58181, "s": 57930, "text": "'data.frame': 5 obs. of 4 variables:\n $ emp_id : int 1 2 3 4 5\n $ emp_name : chr \"Rick\" \"Dan\" \"Michelle\" \"Ryan\" ...\n $ salary : num 623 515 611 729 843\n $ start_date: Date, format: \"2012-01-01\" \"2013-09-23\" \"2014-11-15\" \"2014-05-11\" ...\n" }, { "code": null, "e": 58276, "s": 58181, "text": "The statistical summary and nature of the data can be obtained by applying summary() function." }, { "code": null, "e": 58637, "s": 58276, "text": "# Create the data frame.\nemp.data <- data.frame(\n emp_id = c (1:5), \n emp_name = c(\"Rick\",\"Dan\",\"Michelle\",\"Ryan\",\"Gary\"),\n salary = c(623.3,515.2,611.0,729.0,843.25), \n \n start_date = as.Date(c(\"2012-01-01\", \"2013-09-23\", \"2014-11-15\", \"2014-05-11\",\n \"2015-03-27\")),\n stringsAsFactors = FALSE\n)\n# Print the summary.\nprint(summary(emp.data)) " }, { "code": null, "e": 58704, "s": 58637, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 59187, "s": 58704, "text": " emp_id emp_name salary start_date \n Min. :1 Length:5 Min. :515.2 Min. :2012-01-01 \n 1st Qu.:2 Class :character 1st Qu.:611.0 1st Qu.:2013-09-23 \n Median :3 Mode :character Median :623.3 Median :2014-05-11 \n Mean :3 Mean :664.4 Mean :2014-01-14 \n 3rd Qu.:4 3rd Qu.:729.0 3rd Qu.:2014-11-15 \n Max. :5 Max. :843.2 Max. :2015-03-27 \n" }, { "code": null, "e": 59248, "s": 59187, "text": "Extract specific column from a data frame using column name." }, { "code": null, "e": 59654, "s": 59248, "text": "# Create the data frame.\nemp.data <- data.frame(\n emp_id = c (1:5),\n emp_name = c(\"Rick\",\"Dan\",\"Michelle\",\"Ryan\",\"Gary\"),\n salary = c(623.3,515.2,611.0,729.0,843.25),\n \n start_date = as.Date(c(\"2012-01-01\",\"2013-09-23\",\"2014-11-15\",\"2014-05-11\",\n \"2015-03-27\")),\n stringsAsFactors = FALSE\n)\n# Extract Specific columns.\nresult <- data.frame(emp.data$emp_name,emp.data$salary)\nprint(result)" }, { "code": null, "e": 59721, "s": 59654, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 59938, "s": 59721, "text": " emp.data.emp_name emp.data.salary\n1 Rick 623.30\n2 Dan 515.20\n3 Michelle 611.00\n4 Ryan 729.00\n5 Gary 843.25\n" }, { "code": null, "e": 59986, "s": 59938, "text": "Extract the first two rows and then all columns" }, { "code": null, "e": 60362, "s": 59986, "text": "# Create the data frame.\nemp.data <- data.frame(\n emp_id = c (1:5),\n emp_name = c(\"Rick\",\"Dan\",\"Michelle\",\"Ryan\",\"Gary\"),\n salary = c(623.3,515.2,611.0,729.0,843.25),\n \n start_date = as.Date(c(\"2012-01-01\", \"2013-09-23\", \"2014-11-15\", \"2014-05-11\",\n \"2015-03-27\")),\n stringsAsFactors = FALSE\n)\n# Extract first two rows.\nresult <- emp.data[1:2,]\nprint(result)" }, { "code": null, "e": 60429, "s": 60362, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 60562, "s": 60429, "text": " emp_id emp_name salary start_date\n1 1 Rick 623.3 2012-01-01\n2 2 Dan 515.2 2013-09-23\n" }, { "code": null, "e": 60610, "s": 60562, "text": "Extract 3rd and 5th row with 2nd and 4th column" }, { "code": null, "e": 61021, "s": 60610, "text": "# Create the data frame.\nemp.data <- data.frame(\n emp_id = c (1:5), \n emp_name = c(\"Rick\",\"Dan\",\"Michelle\",\"Ryan\",\"Gary\"),\n salary = c(623.3,515.2,611.0,729.0,843.25), \n \n\tstart_date = as.Date(c(\"2012-01-01\", \"2013-09-23\", \"2014-11-15\", \"2014-05-11\",\n \"2015-03-27\")),\n stringsAsFactors = FALSE\n)\n\n# Extract 3rd and 5th row with 2nd and 4th column.\nresult <- emp.data[c(3,5),c(2,4)]\nprint(result)" }, { "code": null, "e": 61088, "s": 61021, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 61155, "s": 61088, "text": " emp_name start_date\n3 Michelle 2014-11-15\n5 Gary 2015-03-27\n" }, { "code": null, "e": 61212, "s": 61155, "text": "A data frame can be expanded by adding columns and rows." }, { "code": null, "e": 61264, "s": 61212, "text": "Just add the column vector using a new column name." }, { "code": null, "e": 61684, "s": 61264, "text": "# Create the data frame.\nemp.data <- data.frame(\n emp_id = c (1:5), \n emp_name = c(\"Rick\",\"Dan\",\"Michelle\",\"Ryan\",\"Gary\"),\n salary = c(623.3,515.2,611.0,729.0,843.25), \n \n start_date = as.Date(c(\"2012-01-01\", \"2013-09-23\", \"2014-11-15\", \"2014-05-11\",\n \"2015-03-27\")),\n stringsAsFactors = FALSE\n)\n\n# Add the \"dept\" coulmn.\nemp.data$dept <- c(\"IT\",\"Operations\",\"IT\",\"HR\",\"Finance\")\nv <- emp.data\nprint(v)" }, { "code": null, "e": 61751, "s": 61684, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 62085, "s": 61751, "text": " emp_id emp_name salary start_date dept\n1 1 Rick 623.30 2012-01-01 IT\n2 2 Dan 515.20 2013-09-23 Operations\n3 3 Michelle 611.00 2014-11-15 IT\n4 4 Ryan 729.00 2014-05-11 HR\n5 5 Gary 843.25 2015-03-27 Finance\n" }, { "code": null, "e": 62253, "s": 62085, "text": "To add more rows permanently to an existing data frame, we need to bring in the new rows in the same structure as the existing data frame and use the rbind() function." }, { "code": null, "e": 62385, "s": 62253, "text": "In the example below we create a data frame with new rows and merge it with the existing data frame to create the final data frame." }, { "code": null, "e": 63152, "s": 62385, "text": "# Create the first data frame.\nemp.data <- data.frame(\n emp_id = c (1:5), \n emp_name = c(\"Rick\",\"Dan\",\"Michelle\",\"Ryan\",\"Gary\"),\n salary = c(623.3,515.2,611.0,729.0,843.25), \n \n start_date = as.Date(c(\"2012-01-01\", \"2013-09-23\", \"2014-11-15\", \"2014-05-11\",\n \"2015-03-27\")),\n dept = c(\"IT\",\"Operations\",\"IT\",\"HR\",\"Finance\"),\n stringsAsFactors = FALSE\n)\n\n# Create the second data frame\nemp.newdata <- \tdata.frame(\n emp_id = c (6:8), \n emp_name = c(\"Rasmi\",\"Pranab\",\"Tusar\"),\n salary = c(578.0,722.5,632.8), \n start_date = as.Date(c(\"2013-05-21\",\"2013-07-30\",\"2014-06-17\")),\n dept = c(\"IT\",\"Operations\",\"Fianance\"),\n stringsAsFactors = FALSE\n)\n\n# Bind the two data frames.\nemp.finaldata <- rbind(emp.data,emp.newdata)\nprint(emp.finaldata)" }, { "code": null, "e": 63219, "s": 63152, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 63753, "s": 63219, "text": " emp_id emp_name salary start_date dept\n1 1 Rick 623.30 2012-01-01 IT\n2 2 Dan 515.20 2013-09-23 Operations\n3 3 Michelle 611.00 2014-11-15 IT\n4 4 Ryan 729.00 2014-05-11 HR\n5 5 Gary 843.25 2015-03-27 Finance\n6 6 Rasmi 578.00 2013-05-21 IT\n7 7 Pranab 722.50 2013-07-30 Operations\n8 8 Tusar 632.80 2014-06-17 Fianance\n" }, { "code": null, "e": 64250, "s": 63753, "text": "R packages are a collection of R functions, complied code and sample data. They are stored under a directory called \"library\" in the R environment. By default, R installs a set of packages during installation. More packages are added later, when they are needed for some specific purpose. When we start the R console, only the default packages are available by default. Other packages which are already installed have to be loaded explicitly to be used by the R program that is going to use them." }, { "code": null, "e": 64317, "s": 64250, "text": "All the packages available in R language are listed at R Packages." }, { "code": null, "e": 64397, "s": 64317, "text": "Below is a list of commands to be used to check, verify and use the R packages." }, { "code": null, "e": 64441, "s": 64397, "text": "Get library locations containing R packages" }, { "code": null, "e": 64453, "s": 64441, "text": ".libPaths()" }, { "code": null, "e": 64575, "s": 64453, "text": "When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc." }, { "code": null, "e": 64617, "s": 64575, "text": "[2] \"C:/Program Files/R/R-3.2.2/library\"\n" }, { "code": null, "e": 64627, "s": 64617, "text": "library()" }, { "code": null, "e": 64749, "s": 64627, "text": "When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc." }, { "code": null, "e": 66870, "s": 64749, "text": "Packages in library ‘C:/Program Files/R/R-3.2.2/library’:\n\nbase The R Base Package\nboot Bootstrap Functions (Originally by Angelo Canty\n for S)\nclass Functions for Classification\ncluster \"Finding Groups in Data\": Cluster Analysis\n Extended Rousseeuw et al.\ncodetools Code Analysis Tools for R\ncompiler The R Compiler Package\ndatasets The R Datasets Package\nforeign Read Data Stored by 'Minitab', 'S', 'SAS',\n 'SPSS', 'Stata', 'Systat', 'Weka', 'dBase', ...\ngraphics The R Graphics Package\ngrDevices The R Graphics Devices and Support for Colours\n and Fonts\ngrid The Grid Graphics Package\nKernSmooth Functions for Kernel Smoothing Supporting Wand\n & Jones (1995)\nlattice Trellis Graphics for R\nMASS Support Functions and Datasets for Venables and\n Ripley's MASS\nMatrix Sparse and Dense Matrix Classes and Methods\nmethods Formal Methods and Classes\nmgcv Mixed GAM Computation Vehicle with GCV/AIC/REML\n Smoothness Estimation\nnlme Linear and Nonlinear Mixed Effects Models\nnnet Feed-Forward Neural Networks and Multinomial\n Log-Linear Models\nparallel Support for Parallel computation in R\nrpart Recursive Partitioning and Regression Trees\nspatial Functions for Kriging and Point Pattern\n Analysis\nsplines Regression Spline Functions and Classes\nstats The R Stats Package\nstats4 Statistical Functions using S4 Classes\nsurvival Survival Analysis\ntcltk Tcl/Tk Interface\ntools Tools for Package Development\nutils The R Utils Package\n" }, { "code": null, "e": 66925, "s": 66870, "text": "Get all packages currently loaded in the R environment" }, { "code": null, "e": 66934, "s": 66925, "text": "search()" }, { "code": null, "e": 67056, "s": 66934, "text": "When we execute the above code, it produces the following result. It may vary depending on the local settings of your pc." }, { "code": null, "e": 67245, "s": 67056, "text": "[1] \".GlobalEnv\" \"package:stats\" \"package:graphics\" \n[4] \"package:grDevices\" \"package:utils\" \"package:datasets\" \n[7] \"package:methods\" \"Autoloads\" \"package:base\" \n" }, { "code": null, "e": 67426, "s": 67245, "text": "There are two ways to add new R packages. One is installing directly from the CRAN directory and another is downloading the package to your local system and installing it manually." }, { "code": null, "e": 67633, "s": 67426, "text": "The following command gets the packages directly from CRAN webpage and installs the package in the R environment. You may be prompted to choose a nearest mirror. Choose the one appropriate to your location." }, { "code": null, "e": 67730, "s": 67633, "text": " install.packages(\"Package Name\")\n \n# Install the package named \"XML\".\n install.packages(\"XML\")\n" }, { "code": null, "e": 67864, "s": 67730, "text": "Go to the link R Packages to download the package needed. Save the package as a .zip file in a suitable location in the local system." }, { "code": null, "e": 67948, "s": 67864, "text": "Now you can run the following command to install this package in the R environment." }, { "code": null, "e": 68123, "s": 67948, "text": "install.packages(file_name_with_path, repos = NULL, type = \"source\")\n\n# Install the package named \"XML\"\ninstall.packages(\"E:/XML_3.98-1.3.zip\", repos = NULL, type = \"source\")" }, { "code": null, "e": 68328, "s": 68123, "text": "Before a package can be used in the code, it must be loaded to the current R environment. You also need to load a package that is already installed previously but not available in the current environment." }, { "code": null, "e": 68378, "s": 68328, "text": "A package is loaded using the following command −" }, { "code": null, "e": 68535, "s": 68378, "text": "library(\"package Name\", lib.loc = \"path to library\")\n\n# Load the package named \"XML\"\ninstall.packages(\"E:/XML_3.98-1.3.zip\", repos = NULL, type = \"source\")\n" }, { "code": null, "e": 68999, "s": 68535, "text": "Data Reshaping in R is about changing the way data is organized into rows and columns. Most of the time data processing in R is done by taking the input data as a data frame. It is easy to extract data from the rows and columns of a data frame but there are situations when we need the data frame in a format that is different from format in which we received it. R has many functions to split, merge and change the rows to columns and vice-versa in a data frame." }, { "code": null, "e": 69136, "s": 68999, "text": "We can join multiple vectors to create a data frame using the cbind()function. Also we can merge two data frames using rbind() function." }, { "code": null, "e": 69961, "s": 69136, "text": "# Create vector objects.\ncity <- c(\"Tampa\",\"Seattle\",\"Hartford\",\"Denver\")\nstate <- c(\"FL\",\"WA\",\"CT\",\"CO\")\nzipcode <- c(33602,98104,06161,80294)\n\n# Combine above three vectors into one data frame.\naddresses <- cbind(city,state,zipcode)\n\n# Print a header.\ncat(\"# # # # The First data frame\\n\") \n\n# Print the data frame.\nprint(addresses)\n\n# Create another data frame with similar columns\nnew.address <- data.frame(\n city = c(\"Lowry\",\"Charlotte\"),\n state = c(\"CO\",\"FL\"),\n zipcode = c(\"80230\",\"33949\"),\n stringsAsFactors = FALSE\n)\n\n# Print a header.\ncat(\"# # # The Second data frame\\n\") \n\n# Print the data frame.\nprint(new.address)\n\n# Combine rows form both the data frames.\nall.addresses <- rbind(addresses,new.address)\n\n# Print a header.\ncat(\"# # # The combined data frame\\n\") \n\n# Print the result.\nprint(all.addresses)" }, { "code": null, "e": 70028, "s": 69961, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 70572, "s": 70028, "text": "# # # # The First data frame\n city state zipcode\n[1,] \"Tampa\" \"FL\" \"33602\"\n[2,] \"Seattle\" \"WA\" \"98104\"\n[3,] \"Hartford\" \"CT\" \"6161\" \n[4,] \"Denver\" \"CO\" \"80294\"\n\n# # # The Second data frame\n city state zipcode\n1 Lowry CO 80230\n2 Charlotte FL 33949\n\n# # # The combined data frame\n city state zipcode\n1 Tampa FL 33602\n2 Seattle WA 98104\n3 Hartford CT 6161\n4 Denver CO 80294\n5 Lowry CO 80230\n6 Charlotte FL 33949\n" }, { "code": null, "e": 70706, "s": 70572, "text": "We can merge two data frames by using the merge() function. The data frames must have same column names on which the merging happens." }, { "code": null, "e": 71094, "s": 70706, "text": "In the example below, we consider the data sets about Diabetes in Pima Indian Women available in the library names \"MASS\". we merge the two data sets based on the values of blood pressure(\"bp\") and body mass index(\"bmi\"). On choosing these two columns for merging, the records where values of these two variables match in both data sets are combined together to form a single data frame." }, { "code": null, "e": 71245, "s": 71094, "text": "library(MASS)\nmerged.Pima <- merge(x = Pima.te, y = Pima.tr,\n by.x = c(\"bp\", \"bmi\"),\n by.y = c(\"bp\", \"bmi\")\n)\nprint(merged.Pima)\nnrow(merged.Pima)" }, { "code": null, "e": 71312, "s": 71245, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 73012, "s": 71312, "text": " bp bmi npreg.x glu.x skin.x ped.x age.x type.x npreg.y glu.y skin.y ped.y\n1 60 33.8 1 117 23 0.466 27 No 2 125 20 0.088\n2 64 29.7 2 75 24 0.370 33 No 2 100 23 0.368\n3 64 31.2 5 189 33 0.583 29 Yes 3 158 13 0.295\n4 64 33.2 4 117 27 0.230 24 No 1 96 27 0.289\n5 66 38.1 3 115 39 0.150 28 No 1 114 36 0.289\n6 68 38.5 2 100 25 0.324 26 No 7 129 49 0.439\n7 70 27.4 1 116 28 0.204 21 No 0 124 20 0.254\n8 70 33.1 4 91 32 0.446 22 No 9 123 44 0.374\n9 70 35.4 9 124 33 0.282 34 No 6 134 23 0.542\n10 72 25.6 1 157 21 0.123 24 No 4 99 17 0.294\n11 72 37.7 5 95 33 0.370 27 No 6 103 32 0.324\n12 74 25.9 9 134 33 0.460 81 No 8 126 38 0.162\n13 74 25.9 1 95 21 0.673 36 No 8 126 38 0.162\n14 78 27.6 5 88 30 0.258 37 No 6 125 31 0.565\n15 78 27.6 10 122 31 0.512 45 No 6 125 31 0.565\n16 78 39.4 2 112 50 0.175 24 No 4 112 40 0.236\n17 88 34.5 1 117 24 0.403 40 Yes 4 127 11 0.598\n age.y type.y\n1 31 No\n2 21 No\n3 24 No\n4 21 No\n5 21 No\n6 43 Yes\n7 36 Yes\n8 40 No\n9 29 Yes\n10 28 No\n11 55 No\n12 39 No\n13 39 No\n14 49 Yes\n15 49 Yes\n16 38 No\n17 28 No\n[1] 17\n" }, { "code": null, "e": 73207, "s": 73012, "text": "One of the most interesting aspects of R programming is about changing the shape of the data in multiple steps to get a desired shape. The functions used to do this are called melt() and cast()." }, { "code": null, "e": 73282, "s": 73207, "text": "We consider the dataset called ships present in the library called \"MASS\"." }, { "code": null, "e": 73309, "s": 73282, "text": "library(MASS)\nprint(ships)" }, { "code": null, "e": 73376, "s": 73309, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 73999, "s": 73376, "text": " type year period service incidents\n1 A 60 60 127 0\n2 A 60 75 63 0\n3 A 65 60 1095 3\n4 A 65 75 1095 4\n5 A 70 60 1512 6\n.............\n.............\n8 A 75 75 2244 11\n9 B 60 60 44882 39\n10 B 60 75 17176 29\n11 B 65 60 28609 58\n............\n............\n17 C 60 60 1179 1\n18 C 60 75 552 1\n19 C 65 60 781 0\n............\n............\n" }, { "code": null, "e": 74104, "s": 73999, "text": "Now we melt the data to organize it, converting all columns other than type and year into multiple rows." }, { "code": null, "e": 74175, "s": 74104, "text": "molten.ships <- melt(ships, id = c(\"type\",\"year\"))\nprint(molten.ships)" }, { "code": null, "e": 74242, "s": 74175, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 75166, "s": 74242, "text": " type year variable value\n1 A 60 period 60\n2 A 60 period 75\n3 A 65 period 60\n4 A 65 period 75\n............\n............\n9 B 60 period 60\n10 B 60 period 75\n11 B 65 period 60\n12 B 65 period 75\n13 B 70 period 60\n...........\n...........\n41 A 60 service 127\n42 A 60 service 63\n43 A 65 service 1095\n...........\n...........\n70 D 70 service 1208\n71 D 75 service 0\n72 D 75 service 2051\n73 E 60 service 45\n74 E 60 service 0\n75 E 65 service 789\n...........\n...........\n101 C 70 incidents 6\n102 C 70 incidents 2\n103 C 75 incidents 0\n104 C 75 incidents 1\n105 D 60 incidents 0\n106 D 60 incidents 0\n...........\n...........\n" }, { "code": null, "e": 75315, "s": 75166, "text": "We can cast the molten data into a new form where the aggregate of each type of ship for each year is created. It is done using the cast() function." }, { "code": null, "e": 75396, "s": 75315, "text": "recasted.ship <- cast(molten.ships, type+year~variable,sum)\nprint(recasted.ship)" }, { "code": null, "e": 75463, "s": 75396, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 76247, "s": 75463, "text": " type year period service incidents\n1 A 60 135 190 0\n2 A 65 135 2190 7\n3 A 70 135 4865 24\n4 A 75 135 2244 11\n5 B 60 135 62058 68\n6 B 65 135 48979 111\n7 B 70 135 20163 56\n8 B 75 135 7117 18\n9 C 60 135 1731 2\n10 C 65 135 1457 1\n11 C 70 135 2731 8\n12 C 75 135 274 1\n13 D 60 135 356 0\n14 D 65 135 480 0\n15 D 70 135 1557 13\n16 D 75 135 2051 4\n17 E 60 135 45 0\n18 E 65 135 1226 14\n19 E 70 135 3318 17\n20 E 75 135 542 1\n" }, { "code": null, "e": 76481, "s": 76247, "text": "In R, we can read data from files stored outside the R environment. We can also write data into files which will be stored and accessed by the operating system. R can read and write into various file formats like csv, excel, xml etc." }, { "code": null, "e": 76727, "s": 76481, "text": "In this chapter we will learn to read data from a csv file and then write data into a csv file. The file should be present in current working directory so that R can read it. Of course we can also set our own directory and read files from there." }, { "code": null, "e": 76880, "s": 76727, "text": "You can check which directory the R workspace is pointing to using the getwd() function. You can also set a new working directory using setwd()function." }, { "code": null, "e": 77049, "s": 76880, "text": "# Get and print current working directory.\nprint(getwd())\n\n# Set current working directory.\nsetwd(\"/web/com\")\n\n# Get and print current working directory.\nprint(getwd())" }, { "code": null, "e": 77116, "s": 77049, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 77163, "s": 77116, "text": "[1] \"/web/com/1441086124_2016\"\n[1] \"/web/com\"\n" }, { "code": null, "e": 77244, "s": 77163, "text": "This result depends on your OS and your current directory where you are working." }, { "code": null, "e": 77404, "s": 77244, "text": "The csv file is a text file in which the values in the columns are separated by a comma. Let's consider the following data present in the file named input.csv." }, { "code": null, "e": 77564, "s": 77404, "text": "You can create this file using windows notepad by copying and pasting this data. Save the file as input.csv using the save As All files(*.*) option in notepad." }, { "code": null, "e": 77836, "s": 77564, "text": "id,name,salary,start_date,dept\n1,Rick,623.3,2012-01-01,IT\n2,Dan,515.2,2013-09-23,Operations\n3,Michelle,611,2014-11-15,IT\n4,Ryan,729,2014-05-11,HR\n5,Gary,843.25,2015-03-27,Finance\n6,Nina,578,2013-05-21,IT\n7,Simon,632.8,2013-07-30,Operations\n8,Guru,722.5,2014-06-17,Finance" }, { "code": null, "e": 77954, "s": 77836, "text": "Following is a simple example of read.csv() function to read a CSV file available in your current working directory −" }, { "code": null, "e": 77996, "s": 77954, "text": "data <- read.csv(\"input.csv\")\nprint(data)" }, { "code": null, "e": 78063, "s": 77996, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 78542, "s": 78063, "text": " id, name, salary, start_date, dept\n1 1 Rick 623.30 2012-01-01 IT\n2 2 Dan 515.20 2013-09-23 Operations\n3 3 Michelle 611.00 2014-11-15 IT\n4 4 Ryan 729.00 2014-05-11 HR\n5 NA Gary 843.25 2015-03-27 Finance\n6 6 Nina 578.00 2013-05-21 IT\n7 7 Simon 632.80 2013-07-30 Operations\n8 8 Guru 722.50 2014-06-17 Finance\n" }, { "code": null, "e": 78700, "s": 78542, "text": "By default the read.csv() function gives the output as a data frame. This can be easily checked as follows. Also we can check the number of columns and rows." }, { "code": null, "e": 78794, "s": 78700, "text": "data <- read.csv(\"input.csv\")\n\nprint(is.data.frame(data))\nprint(ncol(data))\nprint(nrow(data))" }, { "code": null, "e": 78861, "s": 78794, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 78883, "s": 78861, "text": "[1] TRUE\n[1] 5\n[1] 8\n" }, { "code": null, "e": 79011, "s": 78883, "text": "Once we read data in a data frame, we can apply all the functions applicable to data frames as explained in subsequent section." }, { "code": null, "e": 79138, "s": 79011, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\n\n# Get the max salary from data frame.\nsal <- max(data$salary)\nprint(sal)" }, { "code": null, "e": 79205, "s": 79138, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 79217, "s": 79205, "text": "[1] 843.25\n" }, { "code": null, "e": 79299, "s": 79217, "text": "We can fetch rows meeting specific filter criteria similar to a SQL where clause." }, { "code": null, "e": 79519, "s": 79299, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\n\n# Get the max salary from data frame.\nsal <- max(data$salary)\n\n# Get the person detail having max salary.\nretval <- subset(data, salary == max(salary))\nprint(retval)" }, { "code": null, "e": 79586, "s": 79519, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 79680, "s": 79586, "text": " id name salary start_date dept\n5 NA Gary 843.25 2015-03-27 Finance\n" }, { "code": null, "e": 79786, "s": 79680, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\n\nretval <- subset( data, dept == \"IT\")\nprint(retval)" }, { "code": null, "e": 79853, "s": 79786, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 80044, "s": 79853, "text": " id name salary start_date dept\n1 1 Rick 623.3 2012-01-01 IT\n3 3 Michelle 611.0 2014-11-15 IT\n6 6 Nina 578.0 2013-05-21 IT\n" }, { "code": null, "e": 80160, "s": 80044, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\n\ninfo <- subset(data, salary > 600 & dept == \"IT\")\nprint(info)" }, { "code": null, "e": 80227, "s": 80160, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 80371, "s": 80227, "text": " id name salary start_date dept\n1 1 Rick 623.3 2012-01-01 IT\n3 3 Michelle 611.0 2014-11-15 IT\n" }, { "code": null, "e": 80507, "s": 80371, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\n\nretval <- subset(data, as.Date(start_date) > as.Date(\"2014-01-01\"))\nprint(retval)" }, { "code": null, "e": 80574, "s": 80507, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 80822, "s": 80574, "text": " id name salary start_date dept\n3 3 Michelle 611.00 2014-11-15 IT\n4 4 Ryan 729.00 2014-05-11 HR\n5 NA Gary 843.25 2015-03-27 Finance\n8 8 Guru 722.50 2014-06-17 Finance\n" }, { "code": null, "e": 80976, "s": 80822, "text": "R can create csv file form existing data frame. The write.csv() function is used to create the csv file. This file gets created in the working directory." }, { "code": null, "e": 81217, "s": 80976, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\nretval <- subset(data, as.Date(start_date) > as.Date(\"2014-01-01\"))\n\n# Write filtered data into a new file.\nwrite.csv(retval,\"output.csv\")\nnewdata <- read.csv(\"output.csv\")\nprint(newdata)" }, { "code": null, "e": 81284, "s": 81217, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 81547, "s": 81284, "text": " X id name salary start_date dept\n1 3 3 Michelle 611.00 2014-11-15 IT\n2 4 4 Ryan 729.00 2014-05-11 HR\n3 5 NA Gary 843.25 2015-03-27 Finance\n4 8 8 Guru 722.50 2014-06-17 Finance\n" }, { "code": null, "e": 81669, "s": 81547, "text": "Here the column X comes from the data set newper. This can be dropped using additional parameters while writing the file." }, { "code": null, "e": 81929, "s": 81669, "text": "# Create a data frame.\ndata <- read.csv(\"input.csv\")\nretval <- subset(data, as.Date(start_date) > as.Date(\"2014-01-01\"))\n\n# Write filtered data into a new file.\nwrite.csv(retval,\"output.csv\", row.names = FALSE)\nnewdata <- read.csv(\"output.csv\")\nprint(newdata)" }, { "code": null, "e": 81996, "s": 81929, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 82249, "s": 81996, "text": " id name salary start_date dept\n1 3 Michelle 611.00 2014-11-15 IT\n2 4 Ryan 729.00 2014-05-11 HR\n3 NA Gary 843.25 2015-03-27 Finance\n4 8 Guru 722.50 2014-06-17 Finance\n" }, { "code": null, "e": 82565, "s": 82249, "text": "Microsoft Excel is the most widely used spreadsheet program which stores data in the .xls or .xlsx format. R can read directly from these files using some excel specific packages. Few such packages are - XLConnect, xlsx, gdata etc. We will be using xlsx package. R can also write into excel file using this package." }, { "code": null, "e": 82817, "s": 82565, "text": "You can use the following command in the R console to install the \"xlsx\" package. It may ask to install some additional packages on which this package is dependent. Follow the same command with required package name to install the additional packages." }, { "code": null, "e": 82843, "s": 82817, "text": "install.packages(\"xlsx\")\n" }, { "code": null, "e": 82908, "s": 82843, "text": "Use the following command to verify and load the \"xlsx\" package." }, { "code": null, "e": 83037, "s": 82908, "text": "# Verify the package is installed.\nany(grepl(\"xlsx\",installed.packages()))\n\n# Load the library into R workspace.\nlibrary(\"xlsx\")" }, { "code": null, "e": 83089, "s": 83037, "text": "When the script is run we get the following output." }, { "code": null, "e": 83200, "s": 83089, "text": "[1] TRUE\nLoading required package: rJava\nLoading required package: methods\nLoading required package: xlsxjars\n" }, { "code": null, "e": 83291, "s": 83200, "text": "Open Microsoft excel. Copy and paste the following data in the work sheet named as sheet1." }, { "code": null, "e": 83644, "s": 83291, "text": "id\tname salary start_date\tdept\n1\tRick\t 623.3\t 1/1/2012\t IT\n2\tDan 515.2 9/23/2013 Operations\n3\tMichelle 611\t 11/15/2014\tIT\n4\tRyan\t 729\t 5/11/2014\t HR\n5\tGary\t 43.25 3/27/2015 \tFinance\n6\tNina\t 578 5/21/2013\t IT\n7\tSimon\t 632.8\t 7/30/2013\t Operations\n8\tGuru\t 722.5\t 6/17/2014\t Finance\n" }, { "code": null, "e": 83741, "s": 83644, "text": "Also copy and paste the following data to another worksheet and rename this worksheet to \"city\"." }, { "code": null, "e": 83890, "s": 83741, "text": "name\t city\nRick\t Seattle\nDan Tampa\nMichelle Chicago\nRyan\t Seattle\nGary\t Houston\nNina\t Boston\nSimon\t Mumbai\nGuru\t Dallas\n" }, { "code": null, "e": 83999, "s": 83890, "text": "Save the Excel file as \"input.xlsx\". You should save it in the current working directory of the R workspace." }, { "code": null, "e": 84131, "s": 83999, "text": "The input.xlsx is read by using the read.xlsx() function as shown below. The result is stored as a data frame in the R environment." }, { "code": null, "e": 84242, "s": 84131, "text": "# Read the first worksheet in the file input.xlsx.\ndata <- read.xlsx(\"input.xlsx\", sheetIndex = 1)\nprint(data)" }, { "code": null, "e": 84309, "s": 84242, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 84779, "s": 84309, "text": " id, name, salary, start_date, dept\n1 1 Rick 623.30 2012-01-01 IT\n2 2 Dan 515.20 2013-09-23 Operations\n3 3 Michelle 611.00 2014-11-15 IT\n4 4 Ryan 729.00 2014-05-11 HR\n5 NA Gary 843.25 2015-03-27 Finance\n6 6 Nina 578.00 2013-05-21 IT\n7 7 Simon 632.80 2013-07-30 Operations\n8 8 Guru 722.50 2014-06-17 Finance\n" }, { "code": null, "e": 85106, "s": 84779, "text": "A binary file is a file that contains information stored only in form of bits and bytes.(0’s and 1’s). They are not human readable as the bytes in it translate to characters and symbols which contain many other non-printable characters. Attempting to read a binary file using any text editor will show characters like Ø and ð." }, { "code": null, "e": 85636, "s": 85106, "text": "The binary file has to be read by specific programs to be useable. For example, the binary file of a Microsoft Word program can be read to a human readable form only by the Word program. Which indicates that, besides the human readable text, there is a lot more information like formatting of characters and page numbers etc., which are also stored along with alphanumeric characters. And finally a binary file is a continuous sequence of bytes. The line break we see in a text file is a character joining first line to the next." }, { "code": null, "e": 85819, "s": 85636, "text": "Sometimes, the data generated by other programs are required to be processed by R as a binary file. Also R is required to create binary files which can be shared with other programs." }, { "code": null, "e": 85897, "s": 85819, "text": "R has two functions WriteBin() and readBin() to create and read binary files." }, { "code": null, "e": 85943, "s": 85897, "text": "writeBin(object, con)\nreadBin(con, what, n )\n" }, { "code": null, "e": 85997, "s": 85943, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 86060, "s": 85997, "text": "con is the connection object to read or write the binary file." }, { "code": null, "e": 86123, "s": 86060, "text": "con is the connection object to read or write the binary file." }, { "code": null, "e": 86170, "s": 86123, "text": "object is the binary file which to be written." }, { "code": null, "e": 86217, "s": 86170, "text": "object is the binary file which to be written." }, { "code": null, "e": 86298, "s": 86217, "text": "what is the mode like character, integer etc. representing the bytes to be read." }, { "code": null, "e": 86379, "s": 86298, "text": "what is the mode like character, integer etc. representing the bytes to be read." }, { "code": null, "e": 86434, "s": 86379, "text": "n is the number of bytes to read from the binary file." }, { "code": null, "e": 86489, "s": 86434, "text": "n is the number of bytes to read from the binary file." }, { "code": null, "e": 86670, "s": 86489, "text": "We consider the R inbuilt data \"mtcars\". First we create a csv file from it and convert it to a binary file and store it as a OS file. Next we read this binary file created into R." }, { "code": null, "e": 86762, "s": 86670, "text": "We read the data frame \"mtcars\" as a csv file and then write it as a binary file to the OS." }, { "code": null, "e": 87560, "s": 86762, "text": "# Read the \"mtcars\" data frame as a csv file and store only the columns \n \"cyl\", \"am\" and \"gear\".\nwrite.table(mtcars, file = \"mtcars.csv\",row.names = FALSE, na = \"\", \n col.names = TRUE, sep = \",\")\n\n# Store 5 records from the csv file as a new data frame.\nnew.mtcars <- read.table(\"mtcars.csv\",sep = \",\",header = TRUE,nrows = 5)\n\n# Create a connection object to write the binary file using mode \"wb\".\nwrite.filename = file(\"/web/com/binmtcars.dat\", \"wb\")\n\n# Write the column names of the data frame to the connection object.\nwriteBin(colnames(new.mtcars), write.filename)\n\n# Write the records in each of the column to the file.\nwriteBin(c(new.mtcars$cyl,new.mtcars$am,new.mtcars$gear), write.filename)\n\n# Close the file for writing so that it can be read by other program.\nclose(write.filename)" }, { "code": null, "e": 87727, "s": 87560, "text": "The binary file created above stores all the data as continuous bytes. So we will read it by choosing appropriate values of column names as well as the column values." }, { "code": null, "e": 88666, "s": 87727, "text": "# Create a connection object to read the file in binary mode using \"rb\".\nread.filename <- file(\"/web/com/binmtcars.dat\", \"rb\")\n\n# First read the column names. n = 3 as we have 3 columns.\ncolumn.names <- readBin(read.filename, character(), n = 3)\n\n# Next read the column values. n = 18 as we have 3 column names and 15 values.\nread.filename <- file(\"/web/com/binmtcars.dat\", \"rb\")\nbindata <- readBin(read.filename, integer(), n = 18)\n\n# Print the data.\nprint(bindata)\n\n# Read the values from 4th byte to 8th byte which represents \"cyl\".\ncyldata = bindata[4:8]\nprint(cyldata)\n\n# Read the values form 9th byte to 13th byte which represents \"am\".\namdata = bindata[9:13]\nprint(amdata)\n\n# Read the values form 9th byte to 13th byte which represents \"gear\".\ngeardata = bindata[14:18]\nprint(geardata)\n\n# Combine all the read values to a dat frame.\nfinaldata = cbind(cyldata, amdata, geardata)\ncolnames(finaldata) = column.names\nprint(finaldata)" }, { "code": null, "e": 88743, "s": 88666, "text": "When we execute the above code, it produces the following result and chart −" }, { "code": null, "e": 89105, "s": 88743, "text": " [1] 7108963 1728081249 7496037 6 6 4\n [7] 6 8 1 1 1 0\n[13] 0 4 4 4 3 3\n\n[1] 6 6 4 6 8\n\n[1] 1 1 1 0 0\n\n[1] 4 4 4 3 3\n\n cyl am gear\n[1,] 6 1 4\n[2,] 6 1 4\n[3,] 4 1 4\n[4,] 6 0 3\n[5,] 8 0 3\n" }, { "code": null, "e": 89183, "s": 89105, "text": "As we can see, we got the original data back by reading the binary file in R." }, { "code": null, "e": 89565, "s": 89183, "text": "XML is a file format which shares both the file format and the data on the World Wide Web, intranets, and elsewhere using standard ASCII text. It stands for Extensible Markup Language (XML). Similar to HTML it contains markup tags. But unlike HTML where the markup tag describes structure of the page, in xml the markup tags describe the meaning of the data contained into he file." }, { "code": null, "e": 89674, "s": 89565, "text": "You can read a xml file in R using the \"XML\" package. This package can be installed using following command." }, { "code": null, "e": 89699, "s": 89674, "text": "install.packages(\"XML\")\n" }, { "code": null, "e": 89858, "s": 89699, "text": "Create a XMl file by copying the below data into a text editor like notepad. Save the file with a .xml extension and choosing the file type as all files(*.*)." }, { "code": null, "e": 91212, "s": 89858, "text": "<RECORDS>\n <EMPLOYEE>\n <ID>1</ID>\n <NAME>Rick</NAME>\n <SALARY>623.3</SALARY>\n <STARTDATE>1/1/2012</STARTDATE>\n <DEPT>IT</DEPT>\n </EMPLOYEE>\n\t\n <EMPLOYEE>\n <ID>2</ID>\n <NAME>Dan</NAME>\n <SALARY>515.2</SALARY>\n <STARTDATE>9/23/2013</STARTDATE>\n <DEPT>Operations</DEPT>\n </EMPLOYEE>\n \n <EMPLOYEE>\n <ID>3</ID>\n <NAME>Michelle</NAME>\n <SALARY>611</SALARY>\n <STARTDATE>11/15/2014</STARTDATE>\n <DEPT>IT</DEPT>\n </EMPLOYEE>\n \n <EMPLOYEE>\n <ID>4</ID>\n <NAME>Ryan</NAME>\n <SALARY>729</SALARY>\n <STARTDATE>5/11/2014</STARTDATE>\n <DEPT>HR</DEPT>\n </EMPLOYEE>\n \n <EMPLOYEE>\n <ID>5</ID>\n <NAME>Gary</NAME>\n <SALARY>843.25</SALARY>\n <STARTDATE>3/27/2015</STARTDATE>\n <DEPT>Finance</DEPT>\n </EMPLOYEE>\n \n <EMPLOYEE>\n <ID>6</ID>\n <NAME>Nina</NAME>\n <SALARY>578</SALARY>\n <STARTDATE>5/21/2013</STARTDATE>\n <DEPT>IT</DEPT>\n </EMPLOYEE>\n \n <EMPLOYEE>\n <ID>7</ID>\n <NAME>Simon</NAME>\n <SALARY>632.8</SALARY>\n <STARTDATE>7/30/2013</STARTDATE>\n <DEPT>Operations</DEPT>\n </EMPLOYEE>\n \n <EMPLOYEE>\n <ID>8</ID>\n <NAME>Guru</NAME>\n <SALARY>722.5</SALARY>\n <STARTDATE>6/17/2014</STARTDATE>\n <DEPT>Finance</DEPT>\n </EMPLOYEE>\n\t\n</RECORDS>" }, { "code": null, "e": 91298, "s": 91212, "text": "The xml file is read by R using the function xmlParse(). It is stored as a list in R." }, { "code": null, "e": 91539, "s": 91298, "text": "# Load the package required to read XML files.\nlibrary(\"XML\")\n\n# Also load the other required package.\nlibrary(\"methods\")\n\n# Give the input file name to the function.\nresult <- xmlParse(file = \"input.xml\")\n\n# Print the result.\nprint(result)" }, { "code": null, "e": 91606, "s": 91539, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 91847, "s": 91606, "text": "1\nRick\n623.3\n1/1/2012\nIT\n\n2\nDan\n515.2\n9/23/2013\nOperations\n\n3\nMichelle\n611\n11/15/2014\nIT\n\n4\nRyan\n729\n5/11/2014\nHR\n\n5\nGary\n843.25\n3/27/2015\nFinance\n\n6\nNina\n578\n5/21/2013\nIT\n\n7\nSimon\n632.8\n7/30/2013\nOperations\n\n8\nGuru\n722.5\n6/17/2014\nFinance\n" }, { "code": null, "e": 92188, "s": 91847, "text": "# Load the packages required to read XML files.\nlibrary(\"XML\")\nlibrary(\"methods\")\n\n# Give the input file name to the function.\nresult <- xmlParse(file = \"input.xml\")\n\n# Exract the root node form the xml file.\nrootnode <- xmlRoot(result)\n\n# Find number of nodes in the root.\nrootsize <- xmlSize(rootnode)\n\n# Print the result.\nprint(rootsize)" }, { "code": null, "e": 92255, "s": 92188, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 92269, "s": 92255, "text": "output\n[1] 8\n" }, { "code": null, "e": 92399, "s": 92269, "text": "Let's look at the first record of the parsed file. It will give us an idea of the various elements present in the top level node." }, { "code": null, "e": 92676, "s": 92399, "text": "# Load the packages required to read XML files.\nlibrary(\"XML\")\nlibrary(\"methods\")\n\n# Give the input file name to the function.\nresult <- xmlParse(file = \"input.xml\")\n\n# Exract the root node form the xml file.\nrootnode <- xmlRoot(result)\n\n# Print the result.\nprint(rootnode[1])" }, { "code": null, "e": 92743, "s": 92676, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 92853, "s": 92743, "text": "$EMPLOYEE\n 1\n Rick\n 623.3\n 1/1/2012\n IT\n \n\nattr(,\"class\")\n[1] \"XMLInternalNodeList\" \"XMLNodeList\" \n" }, { "code": null, "e": 93301, "s": 92853, "text": "# Load the packages required to read XML files.\nlibrary(\"XML\")\nlibrary(\"methods\")\n\n# Give the input file name to the function.\nresult <- xmlParse(file = \"input.xml\")\n\n# Exract the root node form the xml file.\nrootnode <- xmlRoot(result)\n\n# Get the first element of the first node.\nprint(rootnode[[1]][[1]])\n\n# Get the fifth element of the first node.\nprint(rootnode[[1]][[5]])\n\n# Get the second element of the third node.\nprint(rootnode[[3]][[2]])" }, { "code": null, "e": 93368, "s": 93301, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 93386, "s": 93368, "text": "1 \nIT \nMichelle \n" }, { "code": null, "e": 93529, "s": 93386, "text": "To handle the data effectively in large files we read the data in the xml file as a data frame. Then process the data frame for data analysis." }, { "code": null, "e": 93722, "s": 93529, "text": "# Load the packages required to read XML files.\nlibrary(\"XML\")\nlibrary(\"methods\")\n\n# Convert the input xml file to a data frame.\nxmldataframe <- xmlToDataFrame(\"input.xml\")\nprint(xmldataframe)" }, { "code": null, "e": 93789, "s": 93722, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 94269, "s": 93789, "text": " ID NAME SALARY STARTDATE DEPT \n1 1 Rick 623.30 2012-01-01 IT\n2 2 Dan 515.20 2013-09-23 Operations\n3 3 Michelle 611.00 2014-11-15 IT\n4 4 Ryan 729.00 2014-05-11 HR\n5 NA Gary 843.25 2015-03-27 Finance\n6 6 Nina 578.00 2013-05-21 IT\n7 7 Simon 632.80 2013-07-30 Operations\n8 8 Guru 722.50 2014-06-17 Finance\n" }, { "code": null, "e": 94385, "s": 94269, "text": "As the data is now available as a dataframe we can use data frame related function to read and manipulate the file." }, { "code": null, "e": 94532, "s": 94385, "text": "JSON file stores data as text in human-readable format. Json stands for JavaScript Object Notation. R can read JSON files using the rjson package." }, { "code": null, "e": 94616, "s": 94532, "text": "In the R console, you can issue the following command to install the rjson package." }, { "code": null, "e": 94643, "s": 94616, "text": "install.packages(\"rjson\")\n" }, { "code": null, "e": 94804, "s": 94643, "text": "Create a JSON file by copying the below data into a text editor like notepad. Save the file with a .json extension and choosing the file type as all files(*.*)." }, { "code": null, "e": 95207, "s": 94804, "text": "{ \n \"ID\":[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\" ],\n \"Name\":[\"Rick\",\"Dan\",\"Michelle\",\"Ryan\",\"Gary\",\"Nina\",\"Simon\",\"Guru\" ],\n \"Salary\":[\"623.3\",\"515.2\",\"611\",\"729\",\"843.25\",\"578\",\"632.8\",\"722.5\" ],\n \n \"StartDate\":[ \"1/1/2012\",\"9/23/2013\",\"11/15/2014\",\"5/11/2014\",\"3/27/2015\",\"5/21/2013\",\n \"7/30/2013\",\"6/17/2014\"],\n \"Dept\":[ \"IT\",\"Operations\",\"IT\",\"HR\",\"Finance\",\"IT\",\"Operations\",\"Finance\"]\n}" }, { "code": null, "e": 95295, "s": 95207, "text": "The JSON file is read by R using the function from JSON(). It is stored as a list in R." }, { "code": null, "e": 95480, "s": 95295, "text": "# Load the package required to read JSON files.\nlibrary(\"rjson\")\n\n# Give the input file name to the function.\nresult <- fromJSON(file = \"input.json\")\n\n# Print the result.\nprint(result)" }, { "code": null, "e": 95547, "s": 95480, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 96009, "s": 95547, "text": "$ID\n[1] \"1\" \"2\" \"3\" \"4\" \"5\" \"6\" \"7\" \"8\"\n\n$Name\n[1] \"Rick\" \"Dan\" \"Michelle\" \"Ryan\" \"Gary\" \"Nina\" \"Simon\" \"Guru\"\n\n$Salary\n[1] \"623.3\" \"515.2\" \"611\" \"729\" \"843.25\" \"578\" \"632.8\" \"722.5\"\n\n$StartDate\n[1] \"1/1/2012\" \"9/23/2013\" \"11/15/2014\" \"5/11/2014\" \"3/27/2015\" \"5/21/2013\"\n \"7/30/2013\" \"6/17/2014\"\n\n$Dept\n[1] \"IT\" \"Operations\" \"IT\" \"HR\" \"Finance\" \"IT\"\n \"Operations\" \"Finance\"\n" }, { "code": null, "e": 96124, "s": 96009, "text": "We can convert the extracted data above to a R data frame for further analysis using the as.data.frame() function." }, { "code": null, "e": 96377, "s": 96124, "text": "# Load the package required to read JSON files.\nlibrary(\"rjson\")\n\n# Give the input file name to the function.\nresult <- fromJSON(file = \"input.json\")\n\n# Convert JSON file to a data frame.\njson_data_frame <- as.data.frame(result)\n\nprint(json_data_frame)" }, { "code": null, "e": 96444, "s": 96377, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 96923, "s": 96444, "text": " id, name, salary, start_date, dept\n1 1 Rick 623.30 2012-01-01 IT\n2 2 Dan 515.20 2013-09-23 Operations\n3 3 Michelle 611.00 2014-11-15 IT\n4 4 Ryan 729.00 2014-05-11 HR\n5 NA Gary 843.25 2015-03-27 Finance\n6 6 Nina 578.00 2013-05-21 IT\n7 7 Simon 632.80 2013-07-30 Operations\n8 8 Guru 722.50 2014-06-17 Finance\n" }, { "code": null, "e": 97418, "s": 96923, "text": "Many websites provide data for consumption by its users. For example the World Health Organization(WHO) provides reports on health and medical information in the form of CSV, txt and XML files. Using R programs, we can programmatically extract specific data from such websites. Some packages in R which are used to scrap data form the web are − \"RCurl\",XML\", and \"stringr\". They are used to connect to the URL’s, identify required links for the files and download them to the local environment." }, { "code": null, "e": 97599, "s": 97418, "text": "The following packages are required for processing the URL’s and links to the files. If they are not available in your R Environment, you can install them using following commands." }, { "code": null, "e": 97703, "s": 97599, "text": "install.packages(\"RCurl\")\ninstall.packages(\"XML\")\ninstall.packages(\"stringr\")\ninstall.packages(\"plyr\")\n" }, { "code": null, "e": 97792, "s": 97703, "text": "We will visit the URL weather data and download the CSV files using R for the year 2015." }, { "code": null, "e": 98162, "s": 97792, "text": "We will use the function getHTMLLinks() to gather the URLs of the files. Then we will use the function download.file() to save the files to the local system. As we will be applying the same code again and again for multiple files, we will create a function to be called multiple times. The filenames are passed as parameters in form of a R list object to this function." }, { "code": null, "e": 98875, "s": 98162, "text": "# Read the URL.\nurl <- \"http://www.geos.ed.ac.uk/~weather/jcmb_ws/\"\n\n# Gather the html links present in the webpage.\nlinks <- getHTMLLinks(url)\n\n# Identify only the links which point to the JCMB 2015 files. \nfilenames <- links[str_detect(links, \"JCMB_2015\")]\n\n# Store the file names as a list.\nfilenames_list <- as.list(filenames)\n\n# Create a function to download the files by passing the URL and filename list.\ndownloadcsv <- function (mainurl,filename) {\n filedetails <- str_c(mainurl,filename)\n download.file(filedetails,filename)\n}\n\n# Now apply the l_ply function and save the files into the current R working directory.\nl_ply(filenames,downloadcsv,mainurl = \"http://www.geos.ed.ac.uk/~weather/jcmb_ws/\")" }, { "code": null, "e": 98976, "s": 98875, "text": "After running the above code, you can locate the following files in the current R working directory." }, { "code": null, "e": 99076, "s": 98976, "text": "\"JCMB_2015.csv\" \"JCMB_2015_Apr.csv\" \"JCMB_2015_Feb.csv\" \"JCMB_2015_Jan.csv\"\n \"JCMB_2015_Mar.csv\"\n" }, { "code": null, "e": 99539, "s": 99076, "text": "The data is Relational database systems are stored in a normalized format. So, to carry out statistical computing we will need very advanced and complex Sql queries. But R can connect easily to many relational databases like MySql, Oracle, Sql server etc. and fetch records from them as a data frame. Once the data is available in the R environment, it becomes a normal R data set and can be manipulated or analyzed using all the powerful packages and functions." }, { "code": null, "e": 99626, "s": 99539, "text": "In this tutorial we will be using MySql as our reference database for connecting to R." }, { "code": null, "e": 99809, "s": 99626, "text": "R has a built-in package named \"RMySQL\" which provides native connectivity between with MySql database. You can install this package in the R environment using the following command." }, { "code": null, "e": 99836, "s": 99809, "text": "install.packages(\"RMySQL\")" }, { "code": null, "e": 100000, "s": 99836, "text": "Once the package is installed we create a connection object in R to connect to the database. It takes the username, password, database name and host name as input." }, { "code": null, "e": 100327, "s": 100000, "text": "# Create a connection Object to MySQL database.\n# We will connect to the sampel database named \"sakila\" that comes with MySql installation.\nmysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'sakila',\n host = 'localhost')\n\n# List the tables available in this database.\n dbListTables(mysqlconnection)" }, { "code": null, "e": 100394, "s": 100327, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 101122, "s": 100394, "text": " [1] \"actor\" \"actor_info\" \n [3] \"address\" \"category\" \n [5] \"city\" \"country\" \n [7] \"customer\" \"customer_list\" \n [9] \"film\" \"film_actor\" \n[11] \"film_category\" \"film_list\" \n[13] \"film_text\" \"inventory\" \n[15] \"language\" \"nicer_but_slower_film_list\"\n[17] \"payment\" \"rental\" \n[19] \"sales_by_film_category\" \"sales_by_store\" \n[21] \"staff\" \"staff_list\" \n[23] \"store\" \n" }, { "code": null, "e": 101335, "s": 101122, "text": "We can query the database tables in MySql using the function dbSendQuery(). The query gets executed in MySql and the result set is returned using the R fetch() function. Finally it is stored as a data frame in R." }, { "code": null, "e": 101578, "s": 101335, "text": "# Query the \"actor\" tables to get all the rows.\nresult = dbSendQuery(mysqlconnection, \"select * from actor\")\n\n# Store the result in a R data frame object. n = 5 is used to fetch first 5 rows.\ndata.frame = fetch(result, n = 5)\nprint(data.fame)" }, { "code": null, "e": 101645, "s": 101578, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 102064, "s": 101645, "text": " actor_id first_name last_name last_update\n1 1 PENELOPE GUINESS 2006-02-15 04:34:33\n2 2 NICK WAHLBERG 2006-02-15 04:34:33\n3 3 ED CHASE 2006-02-15 04:34:33\n4 4 JENNIFER DAVIS 2006-02-15 04:34:33\n5 5 JOHNNY LOLLOBRIGIDA 2006-02-15 04:34:33\n" }, { "code": null, "e": 102118, "s": 102064, "text": "We can pass any valid select query to get the result." }, { "code": null, "e": 102319, "s": 102118, "text": "result = dbSendQuery(mysqlconnection, \"select * from actor where last_name = 'TORN'\")\n\n# Fetch all the records(with n = -1) and store it as a data frame.\ndata.frame = fetch(result, n = -1)\nprint(data)" }, { "code": null, "e": 102386, "s": 102319, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 102671, "s": 102386, "text": " actor_id first_name last_name last_update\n1 18 DAN TORN 2006-02-15 04:34:33\n2 94 KENNETH TORN 2006-02-15 04:34:33\n3 102 WALTER TORN 2006-02-15 04:34:33\n" }, { "code": null, "e": 102770, "s": 102671, "text": "We can update the rows in a Mysql table by passing the update query to the dbSendQuery() function." }, { "code": null, "e": 102848, "s": 102770, "text": "dbSendQuery(mysqlconnection, \"update mtcars set disp = 168.5 where hp = 110\")" }, { "code": null, "e": 102934, "s": 102848, "text": "After executing the above code we can see the table updated in the MySql Environment." }, { "code": null, "e": 103137, "s": 102934, "text": "dbSendQuery(mysqlconnection,\n \"insert into mtcars(row_names, mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb)\n values('New Mazda RX4 Wag', 21, 6, 168.5, 110, 3.9, 2.875, 17.02, 0, 1, 4, 4)\"\n)" }, { "code": null, "e": 103237, "s": 103137, "text": "After executing the above code we can see the row inserted into the table in the MySql Environment." }, { "code": null, "e": 103384, "s": 103237, "text": "We can create tables in the MySql using the function dbWriteTable(). It overwrites the table if it already exists and takes a data frame as input." }, { "code": null, "e": 103756, "s": 103384, "text": "# Create the connection object to the database where we want to create the table.\nmysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'sakila', \n host = 'localhost')\n\n# Use the R data frame \"mtcars\" to create the table in MySql.\n# All the rows of mtcars are taken inot MySql.\ndbWriteTable(mysqlconnection, \"mtcars\", mtcars[, ], overwrite = TRUE)" }, { "code": null, "e": 103842, "s": 103756, "text": "After executing the above code we can see the table created in the MySql Environment." }, { "code": null, "e": 103997, "s": 103842, "text": "We can drop the tables in MySql database passing the drop table statement into the dbSendQuery() in the same way we used it for querying data from tables." }, { "code": null, "e": 104057, "s": 103997, "text": "dbSendQuery(mysqlconnection, 'drop table if exists mtcars')" }, { "code": null, "e": 104146, "s": 104057, "text": "After executing the above code we can see the table is dropped in the MySql Environment." }, { "code": null, "e": 104409, "s": 104146, "text": "R Programming language has numerous libraries to create charts and graphs. A pie-chart is a representation of values as slices of a circle with different colors. The slices are labeled and the numbers corresponding to each slice is also represented in the chart." }, { "code": null, "e": 104584, "s": 104409, "text": "In R the pie chart is created using the pie() function which takes positive numbers as a vector input. The additional parameters are used to control labels, color, title etc." }, { "code": null, "e": 104643, "s": 104584, "text": "The basic syntax for creating a pie-chart using the R is −" }, { "code": null, "e": 104689, "s": 104643, "text": "pie(x, labels, radius, main, col, clockwise)\n" }, { "code": null, "e": 104743, "s": 104689, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 104810, "s": 104743, "text": "x is a vector containing the numeric values used in the pie chart." }, { "code": null, "e": 104877, "s": 104810, "text": "x is a vector containing the numeric values used in the pie chart." }, { "code": null, "e": 104927, "s": 104877, "text": "labels is used to give description to the slices." }, { "code": null, "e": 104977, "s": 104927, "text": "labels is used to give description to the slices." }, { "code": null, "e": 105063, "s": 104977, "text": "radius indicates the radius of the circle of the pie chart.(value between −1 and +1)." }, { "code": null, "e": 105149, "s": 105063, "text": "radius indicates the radius of the circle of the pie chart.(value between −1 and +1)." }, { "code": null, "e": 105188, "s": 105149, "text": "main indicates the title of the chart." }, { "code": null, "e": 105227, "s": 105188, "text": "main indicates the title of the chart." }, { "code": null, "e": 105260, "s": 105227, "text": "col indicates the color palette." }, { "code": null, "e": 105293, "s": 105260, "text": "col indicates the color palette." }, { "code": null, "e": 105386, "s": 105293, "text": "clockwise is a logical value indicating if the slices are drawn clockwise or anti clockwise." }, { "code": null, "e": 105479, "s": 105386, "text": "clockwise is a logical value indicating if the slices are drawn clockwise or anti clockwise." }, { "code": null, "e": 105642, "s": 105479, "text": "A very simple pie-chart is created using just the input vector and labels. The below script will create and save the pie chart in the current R working directory." }, { "code": null, "e": 105866, "s": 105642, "text": "# Create data for the graph.\nx <- c(21, 62, 10, 53)\nlabels <- c(\"London\", \"New York\", \"Singapore\", \"Mumbai\")\n\n# Give the chart file a name.\npng(file = \"city.png\")\n\n# Plot the chart.\npie(x,labels)\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 105933, "s": 105866, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 106281, "s": 105933, "text": "We can expand the features of the chart by adding more parameters to the function. We will use parameter main to add a title to the chart and another parameter is col which will make use of rainbow colour pallet while drawing the chart. The length of the pallet should be same as the number of values we have for the chart. Hence we use length(x)." }, { "code": null, "e": 106369, "s": 106281, "text": "The below script will create and save the pie chart in the current R working directory." }, { "code": null, "e": 106695, "s": 106369, "text": "# Create data for the graph.\nx <- c(21, 62, 10, 53)\nlabels <- c(\"London\", \"New York\", \"Singapore\", \"Mumbai\")\n\n# Give the chart file a name.\npng(file = \"city_title_colours.jpg\")\n\n# Plot the chart with title and rainbow color pallet.\npie(x, labels, main = \"City pie chart\", col = rainbow(length(x)))\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 106762, "s": 106695, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 106849, "s": 106762, "text": "We can add slice percentage and a chart legend by creating additional chart variables." }, { "code": null, "e": 107296, "s": 106849, "text": "# Create data for the graph.\nx <- c(21, 62, 10,53)\nlabels <- c(\"London\",\"New York\",\"Singapore\",\"Mumbai\")\n\npiepercent<- round(100*x/sum(x), 1)\n\n# Give the chart file a name.\npng(file = \"city_percentage_legends.jpg\")\n\n# Plot the chart.\npie(x, labels = piepercent, main = \"City pie chart\",col = rainbow(length(x)))\nlegend(\"topright\", c(\"London\",\"New York\",\"Singapore\",\"Mumbai\"), cex = 0.8,\n fill = rainbow(length(x)))\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 107363, "s": 107296, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 107506, "s": 107363, "text": "A pie chart with 3 dimensions can be drawn using additional packages. The package plotrix has a function called pie3D() that is used for this." }, { "code": null, "e": 107826, "s": 107506, "text": "# Get the library.\nlibrary(plotrix)\n\n# Create data for the graph.\nx <- c(21, 62, 10,53)\nlbl <- c(\"London\",\"New York\",\"Singapore\",\"Mumbai\")\n\n# Give the chart file a name.\npng(file = \"3d_pie_chart.jpg\")\n\n# Plot the chart.\npie3D(x,labels = lbl,explode = 0.1, main = \"Pie Chart of Countries \")\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 107893, "s": 107826, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 108184, "s": 107893, "text": "A bar chart represents data in rectangular bars with length of the bar proportional to the value of the variable. R uses the function barplot() to create bar charts.\n R can draw both vertical and Horizontal bars in the bar chart.\nIn bar chart each of the bars can be given different colors." }, { "code": null, "e": 108233, "s": 108184, "text": "The basic syntax to create a bar-chart in R is −" }, { "code": null, "e": 108275, "s": 108233, "text": "barplot(H,xlab,ylab,main, names.arg,col)\n" }, { "code": null, "e": 108329, "s": 108275, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 108398, "s": 108329, "text": "H is a vector or matrix containing numeric values used in bar chart." }, { "code": null, "e": 108428, "s": 108398, "text": "xlab is the label for x axis." }, { "code": null, "e": 108458, "s": 108428, "text": "ylab is the label for y axis." }, { "code": null, "e": 108494, "s": 108458, "text": "main is the title of the bar chart." }, { "code": null, "e": 108551, "s": 108494, "text": "names.arg is a vector of names appearing under each bar." }, { "code": null, "e": 108604, "s": 108551, "text": "col is used to give colors to the bars in the graph." }, { "code": null, "e": 108688, "s": 108604, "text": "A simple bar chart is created using just the input vector and the name of each bar." }, { "code": null, "e": 108777, "s": 108688, "text": " The below script will create and save the bar chart in the current R working directory." }, { "code": null, "e": 108948, "s": 108777, "text": "# Create the data for the chart\nH <- c(7,12,28,3,41)\n\n# Give the chart file a name\npng(file = \"barchart.png\")\n\n# Plot the bar chart \nbarplot(H)\n\n# Save the file\ndev.off()" }, { "code": null, "e": 109007, "s": 108948, "text": "When we execute above code, it produces following result −" }, { "code": null, "e": 109287, "s": 109007, "text": "The features of the bar chart can be expanded by adding more parameters. The main parameter is used to add title. The col parameter is used to add colors to the bars. The args.name is a vector having same number of values as the input vector to describe the meaning of each bar." }, { "code": null, "e": 109375, "s": 109287, "text": "The below script will create and save the bar chart in the current R working directory." }, { "code": null, "e": 109685, "s": 109375, "text": "# Create the data for the chart\nH <- c(7,12,28,3,41)\nM <- c(\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\")\n\n# Give the chart file a name\npng(file = \"barchart_months_revenue.png\")\n\n# Plot the bar chart \nbarplot(H,names.arg=M,xlab=\"Month\",ylab=\"Revenue\",col=\"blue\",\nmain=\"Revenue chart\",border=\"red\")\n\n# Save the file\ndev.off()" }, { "code": null, "e": 109744, "s": 109685, "text": "When we execute above code, it produces following result −" }, { "code": null, "e": 109846, "s": 109744, "text": "We can create bar chart with groups of bars and stacks in each bar by using a matrix as input values." }, { "code": null, "e": 109966, "s": 109846, "text": " More than two variables are represented as a matrix which is used to create the group bar chart and stacked bar chart." }, { "code": null, "e": 110543, "s": 109966, "text": "# Create the input vectors.\ncolors = c(\"green\",\"orange\",\"brown\")\nmonths <- c(\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\")\nregions <- c(\"East\",\"West\",\"North\")\n\n# Create the matrix of the values.\nValues <- matrix(c(2,9,3,11,9,4,8,7,3,12,5,2,8,10,11), nrow = 3, ncol = 5, byrow = TRUE)\n\n# Give the chart file a name\npng(file = \"barchart_stacked.png\")\n\n# Create the bar chart\nbarplot(Values, main = \"total revenue\", names.arg = months, xlab = \"month\", ylab = \"revenue\", col = colors)\n\n# Add the legend to the chart\nlegend(\"topleft\", regions, cex = 1.3, fill = colors)\n\n# Save the file\ndev.off()" }, { "code": null, "e": 110877, "s": 110543, "text": "Boxplots are a measure of how well distributed is the data in a data set. It divides the data set into three quartiles. This graph represents the minimum, maximum, median, first quartile and third quartile in the data set. It is also useful in comparing the distribution of data across data sets by drawing boxplots for each of them." }, { "code": null, "e": 110936, "s": 110877, "text": "Boxplots are created in R by using the boxplot() function." }, { "code": null, "e": 110984, "s": 110936, "text": "The basic syntax to create a boxplot in R is −" }, { "code": null, "e": 111032, "s": 110984, "text": "boxplot(x, data, notch, varwidth, names, main)\n" }, { "code": null, "e": 111086, "s": 111032, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 111114, "s": 111086, "text": "x is a vector or a formula." }, { "code": null, "e": 111142, "s": 111114, "text": "x is a vector or a formula." }, { "code": null, "e": 111166, "s": 111142, "text": "data is the data frame." }, { "code": null, "e": 111190, "s": 111166, "text": "data is the data frame." }, { "code": null, "e": 111245, "s": 111190, "text": "notch is a logical value. Set as TRUE to draw a notch." }, { "code": null, "e": 111300, "s": 111245, "text": "notch is a logical value. Set as TRUE to draw a notch." }, { "code": null, "e": 111400, "s": 111300, "text": "varwidth is a logical value. Set as true to draw width of the box proportionate to the sample size." }, { "code": null, "e": 111500, "s": 111400, "text": "varwidth is a logical value. Set as true to draw width of the box proportionate to the sample size." }, { "code": null, "e": 111569, "s": 111500, "text": "names are the group labels which will be printed under each boxplot." }, { "code": null, "e": 111638, "s": 111569, "text": "names are the group labels which will be printed under each boxplot." }, { "code": null, "e": 111681, "s": 111638, "text": "main is used to give a title to the graph." }, { "code": null, "e": 111724, "s": 111681, "text": "main is used to give a title to the graph." }, { "code": null, "e": 111864, "s": 111724, "text": "We use the data set \"mtcars\" available in the R environment to create a basic boxplot. Let's look at the columns \"mpg\" and \"cyl\" in mtcars." }, { "code": null, "e": 111916, "s": 111864, "text": "input <- mtcars[,c('mpg','cyl')]\nprint(head(input))" }, { "code": null, "e": 111975, "s": 111916, "text": "When we execute above code, it produces following result −" }, { "code": null, "e": 112166, "s": 111975, "text": " mpg cyl\nMazda RX4 21.0 6\nMazda RX4 Wag 21.0 6\nDatsun 710 22.8 4\nHornet 4 Drive 21.4 6\nHornet Sportabout 18.7 8\nValiant 18.1 6\n" }, { "code": null, "e": 112290, "s": 112166, "text": "The below script will create a boxplot graph for the relation between mpg (miles per gallon) and cyl (number of cylinders)." }, { "code": null, "e": 112510, "s": 112290, "text": "# Give the chart file a name.\npng(file = \"boxplot.png\")\n\n# Plot the chart.\nboxplot(mpg ~ cyl, data = mtcars, xlab = \"Number of Cylinders\",\n ylab = \"Miles Per Gallon\", main = \"Mileage Data\")\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 112577, "s": 112510, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 112684, "s": 112577, "text": "We can draw boxplot with notch to find out how the medians of different data groups match with each other." }, { "code": null, "e": 112768, "s": 112684, "text": "The below script will create a boxplot graph with notch for each of the data group." }, { "code": null, "e": 113122, "s": 112768, "text": "# Give the chart file a name.\npng(file = \"boxplot_with_notch.png\")\n\n# Plot the chart.\nboxplot(mpg ~ cyl, data = mtcars, \n xlab = \"Number of Cylinders\",\n ylab = \"Miles Per Gallon\", \n main = \"Mileage Data\",\n notch = TRUE, \n varwidth = TRUE, \n col = c(\"green\",\"yellow\",\"purple\"),\n names = c(\"High\",\"Medium\",\"Low\")\n)\n# Save the file.\ndev.off()" }, { "code": null, "e": 113189, "s": 113122, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 113465, "s": 113189, "text": "A histogram represents the frequencies of values of a variable bucketed into ranges. Histogram is similar to bar chat but the difference is it groups the values into continuous ranges. Each bar in histogram represents the height of the number of values present in that range." }, { "code": null, "e": 113599, "s": 113465, "text": "R creates histogram using hist() function. This function takes a vector as an input and uses some more parameters to plot histograms." }, { "code": null, "e": 113654, "s": 113599, "text": "The basic syntax for creating a histogram using R is −" }, { "code": null, "e": 113701, "s": 113654, "text": "hist(v,main,xlab,xlim,ylim,breaks,col,border)\n" }, { "code": null, "e": 113755, "s": 113701, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 113814, "s": 113755, "text": "v is a vector containing numeric values used in histogram." }, { "code": null, "e": 113873, "s": 113814, "text": "v is a vector containing numeric values used in histogram." }, { "code": null, "e": 113908, "s": 113873, "text": "main indicates title of the chart." }, { "code": null, "e": 113943, "s": 113908, "text": "main indicates title of the chart." }, { "code": null, "e": 113981, "s": 113943, "text": "col is used to set color of the bars." }, { "code": null, "e": 114019, "s": 113981, "text": "col is used to set color of the bars." }, { "code": null, "e": 114067, "s": 114019, "text": "border is used to set border color of each bar." }, { "code": null, "e": 114115, "s": 114067, "text": "border is used to set border color of each bar." }, { "code": null, "e": 114159, "s": 114115, "text": "xlab is used to give description of x-axis." }, { "code": null, "e": 114203, "s": 114159, "text": "xlab is used to give description of x-axis." }, { "code": null, "e": 114262, "s": 114203, "text": "xlim is used to specify the range of values on the x-axis." }, { "code": null, "e": 114321, "s": 114262, "text": "xlim is used to specify the range of values on the x-axis." }, { "code": null, "e": 114380, "s": 114321, "text": "ylim is used to specify the range of values on the y-axis." }, { "code": null, "e": 114439, "s": 114380, "text": "ylim is used to specify the range of values on the y-axis." }, { "code": null, "e": 114488, "s": 114439, "text": "breaks is used to mention the width of each bar." }, { "code": null, "e": 114537, "s": 114488, "text": "breaks is used to mention the width of each bar." }, { "code": null, "e": 114621, "s": 114537, "text": "A simple histogram is created using input vector, label, col and border parameters." }, { "code": null, "e": 114715, "s": 114621, "text": "The script given below will create and save the histogram in the current R working directory." }, { "code": null, "e": 114951, "s": 114715, "text": "# Create data for the graph.\nv <- c(9,13,21,8,36,22,12,41,31,33,19)\n\n# Give the chart file a name.\npng(file = \"histogram.png\")\n\n# Create the histogram.\nhist(v,xlab = \"Weight\",col = \"yellow\",border = \"blue\")\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 115018, "s": 114951, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 115120, "s": 115018, "text": "To specify the range of values allowed in X axis and Y axis, we can use the xlim and ylim parameters." }, { "code": null, "e": 115181, "s": 115120, "text": "The width of each of the bar can be decided by using breaks." }, { "code": null, "e": 115471, "s": 115181, "text": "# Create data for the graph.\nv <- c(9,13,21,8,36,22,12,41,31,33,19)\n\n# Give the chart file a name.\npng(file = \"histogram_lim_breaks.png\")\n\n# Create the histogram.\nhist(v,xlab = \"Weight\",col = \"green\",border = \"red\", xlim = c(0,40), ylim = c(0,5),\n breaks = 5)\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 115538, "s": 115471, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 115784, "s": 115538, "text": "A line chart is a graph that connects a series of points by drawing line segments between them. These points are ordered in one of their coordinate (usually the x-coordinate) value. Line charts are usually used in identifying the trends in data." }, { "code": null, "e": 115843, "s": 115784, "text": "The plot() function in R is used to create the line graph." }, { "code": null, "e": 115893, "s": 115843, "text": "The basic syntax to create a line chart in R is −" }, { "code": null, "e": 115921, "s": 115893, "text": "plot(v,type,col,xlab,ylab)\n" }, { "code": null, "e": 115975, "s": 115921, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 116020, "s": 115975, "text": "v is a vector containing the numeric values." }, { "code": null, "e": 116065, "s": 116020, "text": "v is a vector containing the numeric values." }, { "code": null, "e": 116181, "s": 116065, "text": "type takes the value \"p\" to draw only the points, \"l\" to draw only the lines and \"o\" to draw both points and lines." }, { "code": null, "e": 116297, "s": 116181, "text": "type takes the value \"p\" to draw only the points, \"l\" to draw only the lines and \"o\" to draw both points and lines." }, { "code": null, "e": 116327, "s": 116297, "text": "xlab is the label for x axis." }, { "code": null, "e": 116357, "s": 116327, "text": "xlab is the label for x axis." }, { "code": null, "e": 116387, "s": 116357, "text": "ylab is the label for y axis." }, { "code": null, "e": 116417, "s": 116387, "text": "ylab is the label for y axis." }, { "code": null, "e": 116449, "s": 116417, "text": "main is the Title of the chart." }, { "code": null, "e": 116481, "s": 116449, "text": "main is the Title of the chart." }, { "code": null, "e": 116538, "s": 116481, "text": "col is used to give colors to both the points and lines." }, { "code": null, "e": 116595, "s": 116538, "text": "col is used to give colors to both the points and lines." }, { "code": null, "e": 116767, "s": 116595, "text": "A simple line chart is created using the input vector and the type parameter as \"O\". The below script will create and save a line chart in the current R working directory." }, { "code": null, "e": 116952, "s": 116767, "text": "# Create the data for the chart.\nv <- c(7,12,28,3,41)\n\n# Give the chart file a name.\npng(file = \"line_chart.jpg\")\n\n# Plot the bar chart. \nplot(v,type = \"o\")\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 117019, "s": 116952, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 117190, "s": 117019, "text": "The features of the line chart can be expanded by using additional parameters. We add color to the points and lines, give a title to the chart and add labels to the axes." }, { "code": null, "e": 117466, "s": 117190, "text": "# Create the data for the chart.\nv <- c(7,12,28,3,41)\n\n# Give the chart file a name.\npng(file = \"line_chart_label_colored.jpg\")\n\n# Plot the bar chart.\nplot(v,type = \"o\", col = \"red\", xlab = \"Month\", ylab = \"Rain fall\",\n main = \"Rain fall chart\")\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 117533, "s": 117466, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 117613, "s": 117533, "text": "More than one line can be drawn on the same chart by using the lines()function." }, { "code": null, "e": 117743, "s": 117613, "text": "After the first line is plotted, the lines() function can use an additional vector as input to draw the second line in the chart," }, { "code": null, "e": 118069, "s": 117743, "text": "# Create the data for the chart.\nv <- c(7,12,28,3,41)\nt <- c(14,7,6,19,3)\n\n# Give the chart file a name.\npng(file = \"line_chart_2_lines.jpg\")\n\n# Plot the bar chart.\nplot(v,type = \"o\",col = \"red\", xlab = \"Month\", ylab = \"Rain fall\", \n main = \"Rain fall chart\")\n\nlines(t, type = \"o\", col = \"blue\")\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 118136, "s": 118069, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 118329, "s": 118136, "text": "Scatterplots show many points plotted in the Cartesian plane. Each point represents the values of two variables. One variable is chosen in the horizontal axis and another in the vertical axis." }, { "code": null, "e": 118390, "s": 118329, "text": "The simple scatterplot is created using the plot() function." }, { "code": null, "e": 118442, "s": 118390, "text": "The basic syntax for creating scatterplot in R is −" }, { "code": null, "e": 118490, "s": 118442, "text": "plot(x, y, main, xlab, ylab, xlim, ylim, axes)\n" }, { "code": null, "e": 118544, "s": 118490, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 118607, "s": 118544, "text": "x is the data set whose values are the horizontal coordinates." }, { "code": null, "e": 118670, "s": 118607, "text": "x is the data set whose values are the horizontal coordinates." }, { "code": null, "e": 118731, "s": 118670, "text": "y is the data set whose values are the vertical coordinates." }, { "code": null, "e": 118792, "s": 118731, "text": "y is the data set whose values are the vertical coordinates." }, { "code": null, "e": 118823, "s": 118792, "text": "main is the tile of the graph." }, { "code": null, "e": 118854, "s": 118823, "text": "main is the tile of the graph." }, { "code": null, "e": 118896, "s": 118854, "text": "xlab is the label in the horizontal axis." }, { "code": null, "e": 118938, "s": 118896, "text": "xlab is the label in the horizontal axis." }, { "code": null, "e": 118978, "s": 118938, "text": "ylab is the label in the vertical axis." }, { "code": null, "e": 119018, "s": 118978, "text": "ylab is the label in the vertical axis." }, { "code": null, "e": 119075, "s": 119018, "text": "xlim is the limits of the values of x used for plotting." }, { "code": null, "e": 119132, "s": 119075, "text": "xlim is the limits of the values of x used for plotting." }, { "code": null, "e": 119189, "s": 119132, "text": "ylim is the limits of the values of y used for plotting." }, { "code": null, "e": 119246, "s": 119189, "text": "ylim is the limits of the values of y used for plotting." }, { "code": null, "e": 119308, "s": 119246, "text": "axes indicates whether both axes should be drawn on the plot." }, { "code": null, "e": 119370, "s": 119308, "text": "axes indicates whether both axes should be drawn on the plot." }, { "code": null, "e": 119509, "s": 119370, "text": "We use the data set \"mtcars\" available in the R environment to create a basic scatterplot. Let's use the columns \"wt\" and \"mpg\" in mtcars." }, { "code": null, "e": 119560, "s": 119509, "text": "input <- mtcars[,c('wt','mpg')]\nprint(head(input))" }, { "code": null, "e": 119627, "s": 119560, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 119858, "s": 119627, "text": " wt mpg\nMazda RX4 2.620 21.0\nMazda RX4 Wag 2.875 21.0\nDatsun 710 2.320 22.8\nHornet 4 Drive 3.215 21.4\nHornet Sportabout 3.440 18.7\nValiant 3.460 18.1\n" }, { "code": null, "e": 119970, "s": 119858, "text": "The below script will create a scatterplot graph for the relation between wt(weight) and mpg(miles per gallon)." }, { "code": null, "e": 120351, "s": 119970, "text": "# Get the input values.\ninput <- mtcars[,c('wt','mpg')]\n\n# Give the chart file a name.\npng(file = \"scatterplot.png\")\n\n# Plot the chart for cars with weight between 2.5 to 5 and mileage between 15 and 30.\nplot(x = input$wt,y = input$mpg,\n xlab = \"Weight\",\n ylab = \"Milage\",\n xlim = c(2.5,5),\n ylim = c(15,30),\t\t \n main = \"Weight vs Milage\"\n)\n\t \n# Save the file.\ndev.off()" }, { "code": null, "e": 120418, "s": 120351, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 120625, "s": 120418, "text": "When we have more than two variables and we want to find the correlation between one variable versus the remaining ones we use scatterplot matrix. We use pairs() function to create matrices of scatterplots." }, { "code": null, "e": 120686, "s": 120625, "text": "The basic syntax for creating scatterplot matrices in R is −" }, { "code": null, "e": 120708, "s": 120686, "text": "pairs(formula, data)\n" }, { "code": null, "e": 120762, "s": 120708, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 120820, "s": 120762, "text": "formula represents the series of variables used in pairs." }, { "code": null, "e": 120878, "s": 120820, "text": "formula represents the series of variables used in pairs." }, { "code": null, "e": 120947, "s": 120878, "text": "data represents the data set from which the variables will be taken." }, { "code": null, "e": 121016, "s": 120947, "text": "data represents the data set from which the variables will be taken." }, { "code": null, "e": 121120, "s": 121016, "text": "Each variable is paired up with each of the remaining variable. A scatterplot is plotted for each pair." }, { "code": null, "e": 121399, "s": 121120, "text": "# Give the chart file a name.\npng(file = \"scatterplot_matrices.png\")\n\n# Plot the matrices between 4 variables giving 12 plots.\n\n# One variable with 3 others and total 4 variables.\n\npairs(~wt+mpg+disp+cyl,data = mtcars,\n main = \"Scatterplot Matrix\")\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 121460, "s": 121399, "text": "When the above code is executed we get the following output." }, { "code": null, "e": 121677, "s": 121460, "text": "Statistical analysis in R is performed by using many in-built functions. Most of these functions are part of the R base package. These functions take R vector as an input along with the arguments and give the result." }, { "code": null, "e": 121752, "s": 121677, "text": "The functions we are discussing in this chapter are mean, median and mode." }, { "code": null, "e": 121858, "s": 121752, "text": "It is calculated by taking the sum of the values and dividing with the number of values in a data series." }, { "code": null, "e": 121910, "s": 121858, "text": "The function mean() is used to calculate this in R." }, { "code": null, "e": 121958, "s": 121910, "text": "The basic syntax for calculating mean in R is −" }, { "code": null, "e": 121997, "s": 121958, "text": "mean(x, trim = 0, na.rm = FALSE, ...)\n" }, { "code": null, "e": 122051, "s": 121997, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 122074, "s": 122051, "text": "x is the input vector." }, { "code": null, "e": 122097, "s": 122074, "text": "x is the input vector." }, { "code": null, "e": 122172, "s": 122097, "text": "trim is used to drop some observations from both end of the sorted vector." }, { "code": null, "e": 122247, "s": 122172, "text": "trim is used to drop some observations from both end of the sorted vector." }, { "code": null, "e": 122313, "s": 122247, "text": "na.rm is used to remove the missing values from the input vector." }, { "code": null, "e": 122379, "s": 122313, "text": "na.rm is used to remove the missing values from the input vector." }, { "code": null, "e": 122491, "s": 122379, "text": "# Create a vector. \nx <- c(12,7,3,4.2,18,2,54,-21,8,-5)\n\n# Find Mean.\nresult.mean <- mean(x)\nprint(result.mean)" }, { "code": null, "e": 122558, "s": 122491, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 122568, "s": 122558, "text": "[1] 8.22\n" }, { "code": null, "e": 122722, "s": 122568, "text": "When trim parameter is supplied, the values in the vector get sorted and then the required numbers of observations are dropped from calculating the mean." }, { "code": null, "e": 122814, "s": 122722, "text": "When trim = 0.3, 3 values from each end will be dropped from the calculations to find mean." }, { "code": null, "e": 122999, "s": 122814, "text": "In this case the sorted vector is (−21, −5, 2, 3, 4.2, 7, 8, 12, 18, 54) and the values removed from the vector for calculating mean are (−21,−5,2) from left and (12,18,54) from right." }, { "code": null, "e": 123122, "s": 122999, "text": "# Create a vector.\nx <- c(12,7,3,4.2,18,2,54,-21,8,-5)\n\n# Find Mean.\nresult.mean <- mean(x,trim = 0.3)\nprint(result.mean)" }, { "code": null, "e": 123189, "s": 123122, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 123199, "s": 123189, "text": "[1] 5.55\n" }, { "code": null, "e": 123263, "s": 123199, "text": "If there are missing values, then the mean function returns NA." }, { "code": null, "e": 123363, "s": 123263, "text": "To drop the missing values from the calculation use na.rm = TRUE. which means remove the NA values." }, { "code": null, "e": 123568, "s": 123363, "text": "# Create a vector. \nx <- c(12,7,3,4.2,18,2,54,-21,8,-5,NA)\n\n# Find mean.\nresult.mean <- mean(x)\nprint(result.mean)\n\n# Find mean dropping NA values.\nresult.mean <- mean(x,na.rm = TRUE)\nprint(result.mean)" }, { "code": null, "e": 123635, "s": 123568, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 123652, "s": 123635, "text": "[1] NA\n[1] 8.22\n" }, { "code": null, "e": 123773, "s": 123652, "text": "The middle most value in a data series is called the median. The median() function is used in R to calculate this value." }, { "code": null, "e": 123823, "s": 123773, "text": "The basic syntax for calculating median in R is −" }, { "code": null, "e": 123849, "s": 123823, "text": "median(x, na.rm = FALSE)\n" }, { "code": null, "e": 123903, "s": 123849, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 123926, "s": 123903, "text": "x is the input vector." }, { "code": null, "e": 123949, "s": 123926, "text": "x is the input vector." }, { "code": null, "e": 124015, "s": 123949, "text": "na.rm is used to remove the missing values from the input vector." }, { "code": null, "e": 124081, "s": 124015, "text": "na.rm is used to remove the missing values from the input vector." }, { "code": null, "e": 124206, "s": 124081, "text": "# Create the vector.\nx <- c(12,7,3,4.2,18,2,54,-21,8,-5)\n\n# Find the median.\nmedian.result <- median(x)\nprint(median.result)" }, { "code": null, "e": 124273, "s": 124206, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 124282, "s": 124273, "text": "[1] 5.6\n" }, { "code": null, "e": 124431, "s": 124282, "text": "The mode is the value that has highest number of occurrences in a set of data. Unike mean and median, mode can have both numeric and character data." }, { "code": null, "e": 124638, "s": 124431, "text": "R does not have a standard in-built function to calculate mode. So we create a user function to calculate mode of a data set in R. This function takes the vector as input and gives the mode value as output." }, { "code": null, "e": 125071, "s": 124638, "text": "# Create the function.\ngetmode <- function(v) {\n uniqv <- unique(v)\n uniqv[which.max(tabulate(match(v, uniqv)))]\n}\n\n# Create the vector with numbers.\nv <- c(2,1,2,3,1,2,3,4,1,5,5,3,2,3)\n\n# Calculate the mode using the user function.\nresult <- getmode(v)\nprint(result)\n\n# Create the vector with characters.\ncharv <- c(\"o\",\"it\",\"the\",\"it\",\"it\")\n\n# Calculate the mode using the user function.\nresult <- getmode(charv)\nprint(result)" }, { "code": null, "e": 125138, "s": 125071, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 125154, "s": 125138, "text": "[1] 2\n[1] \"it\"\n" }, { "code": null, "e": 125465, "s": 125154, "text": "Regression analysis is a very widely used statistical tool to establish a relationship model between two variables. One of these variable is called predictor variable whose value is gathered through experiments. The other variable is called response variable whose value is derived from the predictor variable." }, { "code": null, "e": 125777, "s": 125465, "text": "In Linear Regression these two variables are related through an equation, where exponent (power) of both these variables is 1. Mathematically a linear relationship represents a straight line when plotted as a graph. A non-linear relationship where the exponent of any variable is not equal to 1 creates a curve." }, { "code": null, "e": 125840, "s": 125777, "text": "The general mathematical equation for a linear regression is −" }, { "code": null, "e": 125852, "s": 125840, "text": "y = ax + b\n" }, { "code": null, "e": 125906, "s": 125852, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 125934, "s": 125906, "text": "y is the response variable." }, { "code": null, "e": 125962, "s": 125934, "text": "y is the response variable." }, { "code": null, "e": 125991, "s": 125962, "text": "x is the predictor variable." }, { "code": null, "e": 126020, "s": 125991, "text": "x is the predictor variable." }, { "code": null, "e": 126077, "s": 126020, "text": "a and b are constants which are called the coefficients." }, { "code": null, "e": 126134, "s": 126077, "text": "a and b are constants which are called the coefficients." }, { "code": null, "e": 126307, "s": 126134, "text": "A simple example of regression is predicting weight of a person when his height is known. To do this we need to have the relationship between height and weight of a person." }, { "code": null, "e": 126349, "s": 126307, "text": "The steps to create the relationship is −" }, { "code": null, "e": 126451, "s": 126349, "text": "Carry out the experiment of gathering a sample of observed values of height and corresponding weight." }, { "code": null, "e": 126553, "s": 126451, "text": "Carry out the experiment of gathering a sample of observed values of height and corresponding weight." }, { "code": null, "e": 126612, "s": 126553, "text": "Create a relationship model using the lm() functions in R." }, { "code": null, "e": 126671, "s": 126612, "text": "Create a relationship model using the lm() functions in R." }, { "code": null, "e": 126765, "s": 126671, "text": "Find the coefficients from the model created and create the mathematical equation using these" }, { "code": null, "e": 126859, "s": 126765, "text": "Find the coefficients from the model created and create the mathematical equation using these" }, { "code": null, "e": 126963, "s": 126859, "text": "Get a summary of the relationship model to know the average error in prediction. Also called residuals." }, { "code": null, "e": 127067, "s": 126963, "text": "Get a summary of the relationship model to know the average error in prediction. Also called residuals." }, { "code": null, "e": 127138, "s": 127067, "text": "To predict the weight of new persons, use the predict() function in R." }, { "code": null, "e": 127209, "s": 127138, "text": "To predict the weight of new persons, use the predict() function in R." }, { "code": null, "e": 127266, "s": 127209, "text": "Below is the sample data representing the observations −" }, { "code": null, "e": 127395, "s": 127266, "text": "# Values of height\n151, 174, 138, 186, 128, 136, 179, 163, 152, 131\n\n# Values of weight.\n63, 81, 56, 91, 47, 57, 76, 72, 62, 48\n" }, { "code": null, "e": 127489, "s": 127395, "text": "This function creates the relationship model between the predictor and the response variable." }, { "code": null, "e": 127550, "s": 127489, "text": "The basic syntax for lm() function in linear regression is −" }, { "code": null, "e": 127568, "s": 127550, "text": "lm(formula,data)\n" }, { "code": null, "e": 127622, "s": 127568, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 127683, "s": 127622, "text": "formula is a symbol presenting the relation between x and y." }, { "code": null, "e": 127744, "s": 127683, "text": "formula is a symbol presenting the relation between x and y." }, { "code": null, "e": 127801, "s": 127744, "text": "data is the vector on which the formula will be applied." }, { "code": null, "e": 127858, "s": 127801, "text": "data is the vector on which the formula will be applied." }, { "code": null, "e": 128027, "s": 127858, "text": "x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)\ny <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)\n\n# Apply the lm() function.\nrelation <- lm(y~x)\n\nprint(relation)" }, { "code": null, "e": 128094, "s": 128027, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 128192, "s": 128094, "text": "Call:\nlm(formula = y ~ x)\n\nCoefficients:\n(Intercept) x \n -38.4551 0.6746 \n" }, { "code": null, "e": 128370, "s": 128192, "text": "x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)\ny <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)\n\n# Apply the lm() function.\nrelation <- lm(y~x)\n\nprint(summary(relation))" }, { "code": null, "e": 128437, "s": 128370, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 128981, "s": 128437, "text": "Call:\nlm(formula = y ~ x)\n\nResiduals:\n Min 1Q Median 3Q Max \n-6.3002 -1.6629 0.0412 1.8944 3.9775 \n\nCoefficients:\n Estimate Std. Error t value Pr(>|t|) \n(Intercept) -38.45509 8.04901 -4.778 0.00139 ** \nx 0.67461 0.05191 12.997 1.16e-06 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\nResidual standard error: 3.253 on 8 degrees of freedom\nMultiple R-squared: 0.9548, Adjusted R-squared: 0.9491 \nF-statistic: 168.9 on 1 and 8 DF, p-value: 1.164e-06\n" }, { "code": null, "e": 129038, "s": 128981, "text": "The basic syntax for predict() in linear regression is −" }, { "code": null, "e": 129064, "s": 129038, "text": "predict(object, newdata)\n" }, { "code": null, "e": 129118, "s": 129064, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 129190, "s": 129118, "text": "object is the formula which is already created using the lm() function." }, { "code": null, "e": 129262, "s": 129190, "text": "object is the formula which is already created using the lm() function." }, { "code": null, "e": 129333, "s": 129262, "text": "newdata is the vector containing the new value for predictor variable." }, { "code": null, "e": 129404, "s": 129333, "text": "newdata is the vector containing the new value for predictor variable." }, { "code": null, "e": 129718, "s": 129404, "text": "# The predictor vector.\nx <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)\n\n# The resposne vector.\ny <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)\n\n# Apply the lm() function.\nrelation <- lm(y~x)\n\n# Find weight of a person with height 170.\na <- data.frame(x = 170)\nresult <- predict(relation,a)\nprint(result)" }, { "code": null, "e": 129785, "s": 129718, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 129806, "s": 129785, "text": " 1 \n76.22869 \n" }, { "code": null, "e": 130228, "s": 129806, "text": "# Create the predictor and response variable.\nx <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)\ny <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)\nrelation <- lm(y~x)\n\n# Give the chart file a name.\npng(file = \"linearregression.png\")\n\n# Plot the chart.\nplot(y,x,col = \"blue\",main = \"Height & Weight Regression\",\nabline(lm(x~y)),cex = 1.3,pch = 16,xlab = \"Weight in Kg\",ylab = \"Height in cm\")\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 130295, "s": 130228, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 130573, "s": 130295, "text": "Multiple regression is an extension of linear regression into relationship between more than two variables. In simple linear relation we have one predictor and one response variable, but in multiple regression we have more than one predictor variable and one response variable." }, { "code": null, "e": 130636, "s": 130573, "text": "The general mathematical equation for multiple regression is −" }, { "code": null, "e": 130666, "s": 130636, "text": "y = a + b1x1 + b2x2 +...bnxn\n" }, { "code": null, "e": 130720, "s": 130666, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 130748, "s": 130720, "text": "y is the response variable." }, { "code": null, "e": 130776, "s": 130748, "text": "y is the response variable." }, { "code": null, "e": 130813, "s": 130776, "text": "a, b1, b2...bn are the coefficients." }, { "code": null, "e": 130850, "s": 130813, "text": "a, b1, b2...bn are the coefficients." }, { "code": null, "e": 130893, "s": 130850, "text": "x1, x2, ...xn are the predictor variables." }, { "code": null, "e": 130936, "s": 130893, "text": "x1, x2, ...xn are the predictor variables." }, { "code": null, "e": 131190, "s": 130936, "text": "We create the regression model using the lm() function in R. The model determines the value of the coefficients using the input data. Next we can predict the value of the response variable for a given set of predictor variables using these coefficients." }, { "code": null, "e": 131284, "s": 131190, "text": "This function creates the relationship model between the predictor and the response variable." }, { "code": null, "e": 131347, "s": 131284, "text": "The basic syntax for lm() function in multiple regression is −" }, { "code": null, "e": 131373, "s": 131347, "text": "lm(y ~ x1+x2+x3...,data)\n" }, { "code": null, "e": 131427, "s": 131373, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 131526, "s": 131427, "text": "formula is a symbol presenting the relation between the response variable and predictor variables." }, { "code": null, "e": 131625, "s": 131526, "text": "formula is a symbol presenting the relation between the response variable and predictor variables." }, { "code": null, "e": 131682, "s": 131625, "text": "data is the vector on which the formula will be applied." }, { "code": null, "e": 131739, "s": 131682, "text": "data is the vector on which the formula will be applied." }, { "code": null, "e": 131991, "s": 131739, "text": "Consider the data set \"mtcars\" available in the R environment. It gives a comparison between different car models in terms of mileage per gallon (mpg), cylinder displacement(\"disp\"), horse power(\"hp\"), weight of the car(\"wt\") and some more parameters." }, { "code": null, "e": 132214, "s": 131991, "text": "The goal of the model is to establish the relationship between \"mpg\" as a response variable with \"disp\",\"hp\" and \"wt\" as predictor variables. We create a subset of these variables from the mtcars data set for this purpose." }, { "code": null, "e": 132277, "s": 132214, "text": "input <- mtcars[,c(\"mpg\",\"disp\",\"hp\",\"wt\")]\nprint(head(input))" }, { "code": null, "e": 132344, "s": 132277, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 132650, "s": 132344, "text": " mpg disp hp wt\nMazda RX4 21.0 160 110 2.620\nMazda RX4 Wag 21.0 160 110 2.875\nDatsun 710 22.8 108 93 2.320\nHornet 4 Drive 21.4 258 110 3.215\nHornet Sportabout 18.7 360 175 3.440\nValiant 18.1 225 105 3.460\n" }, { "code": null, "e": 133045, "s": 132650, "text": "input <- mtcars[,c(\"mpg\",\"disp\",\"hp\",\"wt\")]\n\n# Create the relationship model.\nmodel <- lm(mpg~disp+hp+wt, data = input)\n\n# Show the model.\nprint(model)\n\n# Get the Intercept and coefficients as vector elements.\ncat(\"# # # # The Coefficient Values # # # \",\"\\n\")\n\na <- coef(model)[1]\nprint(a)\n\nXdisp <- coef(model)[2]\nXhp <- coef(model)[3]\nXwt <- coef(model)[4]\n\nprint(Xdisp)\nprint(Xhp)\nprint(Xwt)" }, { "code": null, "e": 133112, "s": 133045, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 133438, "s": 133112, "text": "Call:\nlm(formula = mpg ~ disp + hp + wt, data = input)\n\nCoefficients:\n(Intercept) disp hp wt \n 37.105505 -0.000937 -0.031157 -3.800891 \n\n# # # # The Coefficient Values # # # \n(Intercept) \n 37.10551 \n disp \n-0.0009370091 \n hp \n-0.03115655 \n wt \n-3.800891 \n" }, { "code": null, "e": 133528, "s": 133438, "text": "Based on the above intercept and coefficient values, we create the mathematical equation." }, { "code": null, "e": 133612, "s": 133528, "text": "Y = a+Xdisp.x1+Xhp.x2+Xwt.x3\nor\nY = 37.15+(-0.000937)*x1+(-0.0311)*x2+(-3.8008)*x3\n" }, { "code": null, "e": 133763, "s": 133612, "text": "We can use the regression equation created above to predict the mileage when a new set of values for displacement, horse power and weight is provided." }, { "code": null, "e": 133840, "s": 133763, "text": "For a car with disp = 221, hp = 102 and wt = 2.91 the predicted mileage is −" }, { "code": null, "e": 133906, "s": 133840, "text": "Y = 37.15+(-0.000937)*221+(-0.0311)*102+(-3.8008)*2.91 = 22.7104\n" }, { "code": null, "e": 134223, "s": 133906, "text": "The Logistic Regression is a regression model in which the response variable (dependent variable) has categorical values such as True/False or 0/1. It actually measures the probability of a binary response as the value of response variable based on the mathematical equation relating it with the predictor variables." }, { "code": null, "e": 134286, "s": 134223, "text": "The general mathematical equation for logistic regression is −" }, { "code": null, "e": 134323, "s": 134286, "text": "y = 1/(1+e^-(a+b1x1+b2x2+b3x3+...))\n" }, { "code": null, "e": 134377, "s": 134323, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 134405, "s": 134377, "text": "y is the response variable." }, { "code": null, "e": 134433, "s": 134405, "text": "y is the response variable." }, { "code": null, "e": 134462, "s": 134433, "text": "x is the predictor variable." }, { "code": null, "e": 134491, "s": 134462, "text": "x is the predictor variable." }, { "code": null, "e": 134549, "s": 134491, "text": "a and b are the coefficients which are numeric constants." }, { "code": null, "e": 134607, "s": 134549, "text": "a and b are the coefficients which are numeric constants." }, { "code": null, "e": 134679, "s": 134607, "text": "The function used to create the regression model is the glm() function." }, { "code": null, "e": 134743, "s": 134679, "text": "The basic syntax for glm() function in logistic regression is −" }, { "code": null, "e": 134769, "s": 134743, "text": "glm(formula,data,family)\n" }, { "code": null, "e": 134823, "s": 134769, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 134896, "s": 134823, "text": "formula is the symbol presenting the relationship between the variables." }, { "code": null, "e": 134969, "s": 134896, "text": "formula is the symbol presenting the relationship between the variables." }, { "code": null, "e": 135028, "s": 134969, "text": "data is the data set giving the values of these variables." }, { "code": null, "e": 135087, "s": 135028, "text": "data is the data set giving the values of these variables." }, { "code": null, "e": 135191, "s": 135087, "text": "family is R object to specify the details of the model. It's value is binomial for logistic regression." }, { "code": null, "e": 135295, "s": 135191, "text": "family is R object to specify the details of the model. It's value is binomial for logistic regression." }, { "code": null, "e": 135639, "s": 135295, "text": "The in-built data set \"mtcars\" describes different models of a car with their various engine specifications. In \"mtcars\" data set, the transmission mode (automatic or manual) is described by the column am which is a binary value (0 or 1). We can create a logistic regression model between the columns \"am\" and 3 other columns - hp, wt and cyl." }, { "code": null, "e": 135736, "s": 135639, "text": "# Select some columns form mtcars.\ninput <- mtcars[,c(\"am\",\"cyl\",\"hp\",\"wt\")]\n\nprint(head(input))" }, { "code": null, "e": 135803, "s": 135736, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 136081, "s": 135803, "text": " am cyl hp wt\nMazda RX4 1 6 110 2.620\nMazda RX4 Wag 1 6 110 2.875\nDatsun 710 1 4 93 2.320\nHornet 4 Drive 0 6 110 3.215\nHornet Sportabout 0 8 175 3.440\nValiant 0 6 105 3.460\n" }, { "code": null, "e": 136172, "s": 136081, "text": "We use the glm() function to create the regression model and get its summary for analysis." }, { "code": null, "e": 136317, "s": 136172, "text": "input <- mtcars[,c(\"am\",\"cyl\",\"hp\",\"wt\")]\n\nam.data = glm(formula = am ~ cyl + hp + wt, data = input, family = binomial)\n\nprint(summary(am.data))" }, { "code": null, "e": 136384, "s": 136317, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 137145, "s": 136384, "text": "Call:\nglm(formula = am ~ cyl + hp + wt, family = binomial, data = input)\n\nDeviance Residuals: \n Min 1Q Median 3Q Max \n-2.17272 -0.14907 -0.01464 0.14116 1.27641 \n\nCoefficients:\n Estimate Std. Error z value Pr(>|z|) \n(Intercept) 19.70288 8.11637 2.428 0.0152 *\ncyl 0.48760 1.07162 0.455 0.6491 \nhp 0.03259 0.01886 1.728 0.0840 .\nwt -9.14947 4.15332 -2.203 0.0276 *\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\n(Dispersion parameter for binomial family taken to be 1)\n\n Null deviance: 43.2297 on 31 degrees of freedom\nResidual deviance: 9.8415 on 28 degrees of freedom\nAIC: 17.841\n\nNumber of Fisher Scoring iterations: 8\n" }, { "code": null, "e": 137400, "s": 137145, "text": "In the summary as the p-value in the last column is more than 0.05 for the variables \"cyl\" and \"hp\", we consider them to be insignificant in contributing to the value of the variable \"am\". Only weight (wt) impacts the \"am\" value in this regression model." }, { "code": null, "e": 137927, "s": 137400, "text": "In a random collection of data from independent sources, it is generally observed that the distribution of data is normal. Which means, on plotting a graph with the value of the variable in the horizontal axis and the count of the values in the vertical axis we get a bell shape curve. The center of the curve represents the mean of the data set. In the graph, fifty percent of values lie to the left of the mean and the other fifty percent lie to the right of the graph. This is referred as normal distribution in statistics." }, { "code": null, "e": 138016, "s": 137927, "text": "R has four in built functions to generate normal distribution. They are described below." }, { "code": null, "e": 138093, "s": 138016, "text": "dnorm(x, mean, sd)\npnorm(x, mean, sd)\nqnorm(p, mean, sd)\nrnorm(n, mean, sd)\n" }, { "code": null, "e": 138166, "s": 138093, "text": "Following is the description of the parameters used in above functions −" }, { "code": null, "e": 138192, "s": 138166, "text": "x is a vector of numbers." }, { "code": null, "e": 138218, "s": 138192, "text": "x is a vector of numbers." }, { "code": null, "e": 138250, "s": 138218, "text": "p is a vector of probabilities." }, { "code": null, "e": 138282, "s": 138250, "text": "p is a vector of probabilities." }, { "code": null, "e": 138324, "s": 138282, "text": "n is number of observations(sample size)." }, { "code": null, "e": 138366, "s": 138324, "text": "n is number of observations(sample size)." }, { "code": null, "e": 138437, "s": 138366, "text": "mean is the mean value of the sample data. It's default value is zero." }, { "code": null, "e": 138508, "s": 138437, "text": "mean is the mean value of the sample data. It's default value is zero." }, { "code": null, "e": 138563, "s": 138508, "text": "sd is the standard deviation. It's default value is 1." }, { "code": null, "e": 138618, "s": 138563, "text": "sd is the standard deviation. It's default value is 1." }, { "code": null, "e": 138732, "s": 138618, "text": "This function gives height of the probability distribution at each point for a given mean and standard deviation." }, { "code": null, "e": 139017, "s": 138732, "text": "# Create a sequence of numbers between -10 and 10 incrementing by 0.1.\nx <- seq(-10, 10, by = .1)\n\n# Choose the mean as 2.5 and standard deviation as 0.5.\ny <- dnorm(x, mean = 2.5, sd = 0.5)\n\n# Give the chart file a name.\npng(file = \"dnorm.png\")\n\nplot(x,y)\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 139084, "s": 139017, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 139259, "s": 139084, "text": "This function gives the probability of a normally distributed random number to be less that the value of a given number. It is also called \"Cumulative Distribution Function\"." }, { "code": null, "e": 139558, "s": 139259, "text": "# Create a sequence of numbers between -10 and 10 incrementing by 0.2.\nx <- seq(-10,10,by = .2)\n \n# Choose the mean as 2.5 and standard deviation as 2. \ny <- pnorm(x, mean = 2.5, sd = 2)\n\n# Give the chart file a name.\npng(file = \"pnorm.png\")\n\n# Plot the graph.\nplot(x,y)\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 139625, "s": 139558, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 139740, "s": 139625, "text": "This function takes the probability value and gives a number whose cumulative value matches the probability value." }, { "code": null, "e": 140027, "s": 139740, "text": "# Create a sequence of probability values incrementing by 0.02.\nx <- seq(0, 1, by = 0.02)\n\n# Choose the mean as 2 and standard deviation as 3.\ny <- qnorm(x, mean = 2, sd = 1)\n\n# Give the chart file a name.\npng(file = \"qnorm.png\")\n\n# Plot the graph.\nplot(x,y)\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 140094, "s": 140027, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 140318, "s": 140094, "text": "This function is used to generate random numbers whose distribution is normal. It takes the sample size as input and generates that many random numbers. We draw a histogram to show the distribution of the generated numbers." }, { "code": null, "e": 140557, "s": 140318, "text": "# Create a sample of 50 numbers which are normally distributed.\ny <- rnorm(50)\n\n# Give the chart file a name.\npng(file = \"rnorm.png\")\n\n# Plot the histogram for this sample.\nhist(y, main = \"Normal DIstribution\")\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 140624, "s": 140557, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 140973, "s": 140624, "text": "The binomial distribution model deals with finding the probability of success of an event which has only two possible outcomes in a series of experiments. For example, tossing of a coin always gives a head or a tail. The probability of finding exactly 3 heads in tossing a coin repeatedly for 10 times is estimated during the binomial distribution." }, { "code": null, "e": 141064, "s": 140973, "text": "R has four in-built functions to generate binomial distribution. They are described below." }, { "code": null, "e": 141153, "s": 141064, "text": "dbinom(x, size, prob)\npbinom(x, size, prob)\nqbinom(p, size, prob)\nrbinom(n, size, prob)\n" }, { "code": null, "e": 141207, "s": 141153, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 141233, "s": 141207, "text": "x is a vector of numbers." }, { "code": null, "e": 141259, "s": 141233, "text": "x is a vector of numbers." }, { "code": null, "e": 141291, "s": 141259, "text": "p is a vector of probabilities." }, { "code": null, "e": 141323, "s": 141291, "text": "p is a vector of probabilities." }, { "code": null, "e": 141352, "s": 141323, "text": "n is number of observations." }, { "code": null, "e": 141381, "s": 141352, "text": "n is number of observations." }, { "code": null, "e": 141411, "s": 141381, "text": "size is the number of trials." }, { "code": null, "e": 141441, "s": 141411, "text": "size is the number of trials." }, { "code": null, "e": 141491, "s": 141441, "text": "prob is the probability of success of each trial." }, { "code": null, "e": 141541, "s": 141491, "text": "prob is the probability of success of each trial." }, { "code": null, "e": 141613, "s": 141541, "text": "This function gives the probability density distribution at each point." }, { "code": null, "e": 141883, "s": 141613, "text": "# Create a sample of 50 numbers which are incremented by 1.\nx <- seq(0,50,by = 1)\n\n# Create the binomial distribution.\ny <- dbinom(x,50,0.5)\n\n# Give the chart file a name.\npng(file = \"dbinom.png\")\n\n# Plot the graph for this sample.\nplot(x,y)\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 141950, "s": 141883, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 142061, "s": 141950, "text": "This function gives the cumulative probability of an event. It is a single value representing the probability." }, { "code": null, "e": 142164, "s": 142061, "text": "# Probability of getting 26 or less heads from a 51 tosses of a coin.\nx <- pbinom(26,51,0.5)\n\nprint(x)" }, { "code": null, "e": 142231, "s": 142164, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 142245, "s": 142231, "text": "[1] 0.610116\n" }, { "code": null, "e": 142360, "s": 142245, "text": "This function takes the probability value and gives a number whose cumulative value matches the probability value." }, { "code": null, "e": 142492, "s": 142360, "text": "# How many heads will have a probability of 0.25 will come out when a coin\n# is tossed 51 times.\nx <- qbinom(0.25,51,1/2)\n\nprint(x)" }, { "code": null, "e": 142559, "s": 142492, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 142567, "s": 142559, "text": "[1] 23\n" }, { "code": null, "e": 142666, "s": 142567, "text": "This function generates required number of random values of given probability from a given sample." }, { "code": null, "e": 142767, "s": 142666, "text": "# Find 8 random values from a sample of 150 with probability of 0.4.\nx <- rbinom(8,150,.4)\n\nprint(x)" }, { "code": null, "e": 142834, "s": 142767, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 142863, "s": 142834, "text": "[1] 58 61 59 66 55 60 61 67\n" }, { "code": null, "e": 143155, "s": 142863, "text": "Poisson Regression involves regression models in which the response variable is in the form of counts and not fractional numbers. For example, the count of number of births or number of wins in a football match series. Also the values of the response variables follow a Poisson distribution." }, { "code": null, "e": 143217, "s": 143155, "text": "The general mathematical equation for Poisson regression is −" }, { "code": null, "e": 143255, "s": 143217, "text": "log(y) = a + b1x1 + b2x2 + bnxn.....\n" }, { "code": null, "e": 143309, "s": 143255, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 143337, "s": 143309, "text": "y is the response variable." }, { "code": null, "e": 143365, "s": 143337, "text": "y is the response variable." }, { "code": null, "e": 143403, "s": 143365, "text": "a and b are the numeric coefficients." }, { "code": null, "e": 143441, "s": 143403, "text": "a and b are the numeric coefficients." }, { "code": null, "e": 143470, "s": 143441, "text": "x is the predictor variable." }, { "code": null, "e": 143499, "s": 143470, "text": "x is the predictor variable." }, { "code": null, "e": 143579, "s": 143499, "text": "The function used to create the Poisson regression model is the glm() function." }, { "code": null, "e": 143642, "s": 143579, "text": "The basic syntax for glm() function in Poisson regression is −" }, { "code": null, "e": 143668, "s": 143642, "text": "glm(formula,data,family)\n" }, { "code": null, "e": 143741, "s": 143668, "text": "Following is the description of the parameters used in above functions −" }, { "code": null, "e": 143814, "s": 143741, "text": "formula is the symbol presenting the relationship between the variables." }, { "code": null, "e": 143887, "s": 143814, "text": "formula is the symbol presenting the relationship between the variables." }, { "code": null, "e": 143946, "s": 143887, "text": "data is the data set giving the values of these variables." }, { "code": null, "e": 144005, "s": 143946, "text": "data is the data set giving the values of these variables." }, { "code": null, "e": 144110, "s": 144005, "text": "family is R object to specify the details of the model. It's value is 'Poisson' for Logistic Regression." }, { "code": null, "e": 144215, "s": 144110, "text": "family is R object to specify the details of the model. It's value is 'Poisson' for Logistic Regression." }, { "code": null, "e": 144531, "s": 144215, "text": "We have the in-built data set \"warpbreaks\" which describes the effect of wool type (A or B) and tension (low, medium or high) on the number of warp breaks per loom. Let's consider \"breaks\" as the response variable which is a count of number of breaks. The wool \"type\" and \"tension\" are taken as predictor variables." }, { "code": null, "e": 144542, "s": 144531, "text": "Input Data" }, { "code": null, "e": 144581, "s": 144542, "text": "input <- warpbreaks\nprint(head(input))" }, { "code": null, "e": 144648, "s": 144581, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 144816, "s": 144648, "text": " breaks wool tension\n1 26 A L\n2 30 A L\n3 54 A L\n4 25 A L\n5 70 A L\n6 52 A L\n" }, { "code": null, "e": 144925, "s": 144816, "text": "output <-glm(formula = breaks ~ wool+tension, data = warpbreaks,\n family = poisson)\nprint(summary(output))" }, { "code": null, "e": 144992, "s": 144925, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 145758, "s": 144992, "text": "Call:\nglm(formula = breaks ~ wool + tension, family = poisson, data = warpbreaks)\n\nDeviance Residuals: \n Min 1Q Median 3Q Max \n -3.6871 -1.6503 -0.4269 1.1902 4.2616 \n\nCoefficients:\n Estimate Std. Error z value Pr(>|z|) \n(Intercept) 3.69196 0.04541 81.302 < 2e-16 ***\nwoolB -0.20599 0.05157 -3.994 6.49e-05 ***\ntensionM -0.32132 0.06027 -5.332 9.73e-08 ***\ntensionH -0.51849 0.06396 -8.107 5.21e-16 ***\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\n(Dispersion parameter for poisson family taken to be 1)\n\n Null deviance: 297.37 on 53 degrees of freedom\nResidual deviance: 210.39 on 50 degrees of freedom\nAIC: 493.06\n\nNumber of Fisher Scoring iterations: 4\n" }, { "code": null, "e": 145998, "s": 145758, "text": "In the summary we look for the p-value in the last column to be less than 0.05 to consider an impact of the predictor variable on the response variable. As seen the wooltype B having tension type M and H have impact on the count of breaks." }, { "code": null, "e": 146588, "s": 145998, "text": "We use Regression analysis to create models which describe the effect of variation in predictor variables on the response variable. Sometimes, if we have a categorical variable with values like Yes/No or Male/Female etc. The simple regression analysis gives multiple results for each value of the categorical variable. In such scenario, we can study the effect of the categorical variable by using it along with the predictor variable and comparing the regression lines for each level of the categorical variable. Such an analysis is termed as Analysis of Covariance also called as ANCOVA." }, { "code": null, "e": 146874, "s": 146588, "text": "Consider the R built in data set mtcars. In it we observer that the field \"am\" represents the type of transmission (auto or manual). It is a categorical variable with values 0 and 1. The miles per gallon value(mpg) of a car can also depend on it besides the value of horse power(\"hp\")." }, { "code": null, "e": 147066, "s": 146874, "text": "We study the effect of the value of \"am\" on the regression between \"mpg\" and \"hp\". It is done by using the aov() function followed by the anova() function to compare the multiple regressions." }, { "code": null, "e": 147269, "s": 147066, "text": "Create a data frame containing the fields \"mpg\", \"hp\" and \"am\" from the data set mtcars. Here we take \"mpg\" as the response variable, \"hp\" as the predictor variable and \"am\" as the categorical variable." }, { "code": null, "e": 147325, "s": 147269, "text": "input <- mtcars[,c(\"am\",\"mpg\",\"hp\")]\nprint(head(input))" }, { "code": null, "e": 147392, "s": 147325, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 147630, "s": 147392, "text": " am mpg hp\nMazda RX4 1 21.0 110\nMazda RX4 Wag 1 21.0 110\nDatsun 710 1 22.8 93\nHornet 4 Drive 0 21.4 110\nHornet Sportabout 0 18.7 175\nValiant 0 18.1 105\n" }, { "code": null, "e": 147791, "s": 147630, "text": "We create a regression model taking \"hp\" as the predictor variable and \"mpg\" as the response variable taking into account the interaction between \"am\" and \"hp\"." }, { "code": null, "e": 147919, "s": 147791, "text": "# Get the dataset.\ninput <- mtcars\n\n# Create the regression model.\nresult <- aov(mpg~hp*am,data = input)\nprint(summary(result))" }, { "code": null, "e": 147986, "s": 147919, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 148309, "s": 147986, "text": " Df Sum Sq Mean Sq F value Pr(>F) \nhp 1 678.4 678.4 77.391 1.50e-09 ***\nam 1 202.2 202.2 23.072 4.75e-05 ***\nhp:am 1 0.0 0.0 0.001 0.981 \nResiduals 28 245.4 8.8 \n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n" }, { "code": null, "e": 148563, "s": 148309, "text": "This result shows that both horse power and transmission type has significant effect on miles per gallon as the p value in both cases is less than 0.05. But the interaction between these two variables is not significant as the p-value is more than 0.05." }, { "code": null, "e": 148691, "s": 148563, "text": "# Get the dataset.\ninput <- mtcars\n\n# Create the regression model.\nresult <- aov(mpg~hp+am,data = input)\nprint(summary(result))" }, { "code": null, "e": 148758, "s": 148691, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 149034, "s": 148758, "text": " Df Sum Sq Mean Sq F value Pr(>F) \nhp 1 678.4 678.4 80.15 7.63e-10 ***\nam 1 202.2 202.2 23.89 3.46e-05 ***\nResiduals 29 245.4 8.5 \n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n" }, { "code": null, "e": 149187, "s": 149034, "text": "This result shows that both horse power and transmission type has significant effect on miles per gallon as the p value in both cases is less than 0.05." }, { "code": null, "e": 149332, "s": 149187, "text": "Now we can compare the two models to conclude if the interaction of the variables is truly in-significant. For this we use the anova() function." }, { "code": null, "e": 149535, "s": 149332, "text": "# Get the dataset.\ninput <- mtcars\n\n# Create the regression models.\nresult1 <- aov(mpg~hp*am,data = input)\nresult2 <- aov(mpg~hp+am,data = input)\n\n# Compare the two models.\nprint(anova(result1,result2))" }, { "code": null, "e": 149602, "s": 149535, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 149778, "s": 149602, "text": "Model 1: mpg ~ hp * am\nModel 2: mpg ~ hp + am\n Res.Df RSS Df Sum of Sq F Pr(>F)\n1 28 245.43 \n2 29 245.44 -1 -0.0052515 6e-04 0.9806\n" }, { "code": null, "e": 150040, "s": 149778, "text": "As the p-value is greater than 0.05 we conclude that the interaction between horse power and transmission type is not significant. So the mileage per gallon will depend in a similar manner on the horse power of the car in both auto and manual transmission mode." }, { "code": null, "e": 150549, "s": 150040, "text": "Time series is a series of data points in which each data point is associated with a timestamp. A simple example is the price of a stock in the stock market at different points of time on a given day. Another example is the amount of rainfall in a region at different months of the year. R language uses many functions to create, manipulate and plot the time series data. The data for the time series is stored in an R object called time-series object. It is also a R data object like a vector or data frame." }, { "code": null, "e": 150611, "s": 150549, "text": "The time series object is created by using the ts() function." }, { "code": null, "e": 150675, "s": 150611, "text": "The basic syntax for ts() function in time series analysis is −" }, { "code": null, "e": 150735, "s": 150675, "text": "timeseries.object.name <- ts(data, start, end, frequency)\n" }, { "code": null, "e": 150789, "s": 150735, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 150863, "s": 150789, "text": "data is a vector or matrix containing the values used in the time series." }, { "code": null, "e": 150937, "s": 150863, "text": "data is a vector or matrix containing the values used in the time series." }, { "code": null, "e": 151010, "s": 150937, "text": "start specifies the start time for the first observation in time series." }, { "code": null, "e": 151083, "s": 151010, "text": "start specifies the start time for the first observation in time series." }, { "code": null, "e": 151151, "s": 151083, "text": "end specifies the end time for the last observation in time series." }, { "code": null, "e": 151219, "s": 151151, "text": "end specifies the end time for the last observation in time series." }, { "code": null, "e": 151281, "s": 151219, "text": "frequency specifies the number of observations per unit time." }, { "code": null, "e": 151343, "s": 151281, "text": "frequency specifies the number of observations per unit time." }, { "code": null, "e": 151406, "s": 151343, "text": "Except the parameter \"data\" all other parameters are optional." }, { "code": null, "e": 151555, "s": 151406, "text": "Consider the annual rainfall details at a place starting from January 2012. We create an R time series object for a period of 12 months and plot it." }, { "code": null, "e": 151997, "s": 151555, "text": "# Get the data points in form of a R vector.\nrainfall <- c(799,1174.8,865.1,1334.6,635.4,918.5,685.5,998.6,784.2,985,882.8,1071)\n\n# Convert it to a time series object.\nrainfall.timeseries <- ts(rainfall,start = c(2012,1),frequency = 12)\n\n# Print the timeseries data.\nprint(rainfall.timeseries)\n\n# Give the chart file a name.\npng(file = \"rainfall.png\")\n\n# Plot a graph of the time series.\nplot(rainfall.timeseries)\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 152074, "s": 151997, "text": "When we execute the above code, it produces the following result and chart −" }, { "code": null, "e": 152258, "s": 152074, "text": "Jan Feb Mar Apr May Jun Jul Aug Sep\n2012 799.0 1174.8 865.1 1334.6 635.4 918.5 685.5 998.6 784.2\n Oct Nov Dec\n2012 985.0 882.8 1071.0\n" }, { "code": null, "e": 152282, "s": 152258, "text": "The Time series chart −" }, { "code": null, "e": 152512, "s": 152282, "text": "The value of the frequency parameter in the ts() function decides the time intervals at which the data points are measured. A value of 12 indicates that the time series is for 12 months. Other values and its meaning is as below −" }, { "code": null, "e": 152575, "s": 152512, "text": "frequency = 12 pegs the data points for every month of a year." }, { "code": null, "e": 152638, "s": 152575, "text": "frequency = 12 pegs the data points for every month of a year." }, { "code": null, "e": 152702, "s": 152638, "text": "frequency = 4 pegs the data points for every quarter of a year." }, { "code": null, "e": 152766, "s": 152702, "text": "frequency = 4 pegs the data points for every quarter of a year." }, { "code": null, "e": 152834, "s": 152766, "text": "frequency = 6 pegs the data points for every 10 minutes of an hour." }, { "code": null, "e": 152902, "s": 152834, "text": "frequency = 6 pegs the data points for every 10 minutes of an hour." }, { "code": null, "e": 152971, "s": 152902, "text": "frequency = 24*6 pegs the data points for every 10 minutes of a day." }, { "code": null, "e": 153040, "s": 152971, "text": "frequency = 24*6 pegs the data points for every 10 minutes of a day." }, { "code": null, "e": 153130, "s": 153040, "text": "We can plot multiple time series in one chart by combining both the series into a matrix." }, { "code": null, "e": 153817, "s": 153130, "text": "# Get the data points in form of a R vector.\nrainfall1 <- c(799,1174.8,865.1,1334.6,635.4,918.5,685.5,998.6,784.2,985,882.8,1071)\nrainfall2 <- \n c(655,1306.9,1323.4,1172.2,562.2,824,822.4,1265.5,799.6,1105.6,1106.7,1337.8)\n\n# Convert them to a matrix.\ncombined.rainfall <- matrix(c(rainfall1,rainfall2),nrow = 12)\n\n# Convert it to a time series object.\nrainfall.timeseries <- ts(combined.rainfall,start = c(2012,1),frequency = 12)\n\n# Print the timeseries data.\nprint(rainfall.timeseries)\n\n# Give the chart file a name.\npng(file = \"rainfall_combined.png\")\n\n# Plot a graph of the time series.\nplot(rainfall.timeseries, main = \"Multiple Time Series\")\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 153894, "s": 153817, "text": "When we execute the above code, it produces the following result and chart −" }, { "code": null, "e": 154249, "s": 153894, "text": " Series 1 Series 2\nJan 2012 799.0 655.0\nFeb 2012 1174.8 1306.9\nMar 2012 865.1 1323.4\nApr 2012 1334.6 1172.2\nMay 2012 635.4 562.2\nJun 2012 918.5 824.0\nJul 2012 685.5 822.4\nAug 2012 998.6 1265.5\nSep 2012 784.2 799.6\nOct 2012 985.0 1105.6\nNov 2012 882.8 1106.7\nDec 2012 1071.0 1337.8\n" }, { "code": null, "e": 154282, "s": 154249, "text": "The Multiple Time series chart −" }, { "code": null, "e": 154932, "s": 154282, "text": "When modeling real world data for regression analysis, we observe that it is rarely the case that the equation of the model is a linear equation giving a linear graph. Most of the time, the equation of the model of real world data involves mathematical functions of higher degree like an exponent of 3 or a sin function. In such a scenario, the plot of the model gives a curve rather than a line. The goal of both linear and non-linear regression is to adjust the values of the model's parameters to find the line or curve that comes closest to your data. On finding these values we will be able to estimate the response variable with good accuracy." }, { "code": null, "e": 155302, "s": 154932, "text": "In Least Square regression, we establish a regression model in which the sum of the squares of the vertical distances of different points from the regression curve is minimized. We generally start with a defined model and assume some values for the coefficients. We then apply the nls() function of R to get the more accurate values along with the confidence intervals." }, { "code": null, "e": 155372, "s": 155302, "text": "The basic syntax for creating a nonlinear least square test in R is −" }, { "code": null, "e": 155399, "s": 155372, "text": "nls(formula, data, start)\n" }, { "code": null, "e": 155453, "s": 155399, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 155526, "s": 155453, "text": "formula is a nonlinear model formula including variables and parameters." }, { "code": null, "e": 155599, "s": 155526, "text": "formula is a nonlinear model formula including variables and parameters." }, { "code": null, "e": 155667, "s": 155599, "text": "data is a data frame used to evaluate the variables in the formula." }, { "code": null, "e": 155735, "s": 155667, "text": "data is a data frame used to evaluate the variables in the formula." }, { "code": null, "e": 155804, "s": 155735, "text": "start is a named list or named numeric vector of starting estimates." }, { "code": null, "e": 155873, "s": 155804, "text": "start is a named list or named numeric vector of starting estimates." }, { "code": null, "e": 156100, "s": 155873, "text": "We will consider a nonlinear model with assumption of initial values of its coefficients. Next we will see what is the confidence intervals of these assumed values so that we can judge how well these values fir into the model." }, { "code": null, "e": 156156, "s": 156100, "text": "So let's consider the below equation for this purpose −" }, { "code": null, "e": 156171, "s": 156156, "text": "a = b1*x^2+b2\n" }, { "code": null, "e": 156265, "s": 156171, "text": "Let's assume the initial coefficients to be 1 and 3 and fit these values into nls() function." }, { "code": null, "e": 157018, "s": 156265, "text": "xvalues <- c(1.6,2.1,2,2.23,3.71,3.25,3.4,3.86,1.19,2.21)\nyvalues <- c(5.19,7.43,6.94,8.11,18.75,14.88,16.06,19.12,3.21,7.58)\n\n# Give the chart file a name.\npng(file = \"nls.png\")\n\n\n# Plot these values.\nplot(xvalues,yvalues)\n\n\n# Take the assumed values and fit into the model.\nmodel <- nls(yvalues ~ b1*xvalues^2+b2,start = list(b1 = 1,b2 = 3))\n\n# Plot the chart with new data by fitting it to a prediction from 100 data points.\nnew.data <- data.frame(xvalues = seq(min(xvalues),max(xvalues),len = 100))\nlines(new.data$xvalues,predict(model,newdata = new.data))\n\n# Save the file.\ndev.off()\n\n# Get the sum of the squared residuals.\nprint(sum(resid(model)^2))\n\n# Get the confidence intervals on the chosen values of the coefficients.\nprint(confint(model))" }, { "code": null, "e": 157085, "s": 157018, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 157198, "s": 157085, "text": "[1] 1.081935\nWaiting for profiling to be done...\n 2.5% 97.5%\nb1 1.137708 1.253135\nb2 1.497364 2.496484\n" }, { "code": null, "e": 157306, "s": 157198, "text": "We can conclude that the value of b1 is more close to 1 while the value of b2 is more close to 2 and not 3." }, { "code": null, "e": 157588, "s": 157306, "text": "Decision tree is a graph to represent choices and their results in form of a tree. The nodes in the graph represent an event or choice and the edges of the graph represent the decision rules or conditions. It is mostly used in Machine Learning and Data Mining applications using R." }, { "code": null, "e": 158139, "s": 157588, "text": "Examples of use of decision tress is − predicting an email as spam or not spam, predicting of a tumor is cancerous or predicting a loan as a good or bad credit risk based on the factors in each of these. Generally, a model is created with observed data also called training data. Then a set of validation data is used to verify and improve the model. R has packages which are used to create and visualize decision trees. For new set of predictor variable, we use this model to arrive at a decision on the category (yes/No, spam/not spam) of the data." }, { "code": null, "e": 158195, "s": 158139, "text": "The R package \"party\" is used to create decision trees." }, { "code": null, "e": 158310, "s": 158195, "text": "Use the below command in R console to install the package. You also have to install the dependent packages if any." }, { "code": null, "e": 158337, "s": 158310, "text": "install.packages(\"party\")\n" }, { "code": null, "e": 158432, "s": 158337, "text": "The package \"party\" has the function ctree() which is used to create and analyze decison tree." }, { "code": null, "e": 158488, "s": 158432, "text": "The basic syntax for creating a decision tree in R is −" }, { "code": null, "e": 158510, "s": 158488, "text": "ctree(formula, data)\n" }, { "code": null, "e": 158564, "s": 158510, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 158634, "s": 158564, "text": "formula is a formula describing the predictor and response variables." }, { "code": null, "e": 158704, "s": 158634, "text": "formula is a formula describing the predictor and response variables." }, { "code": null, "e": 158743, "s": 158704, "text": "data is the name of the data set used." }, { "code": null, "e": 158782, "s": 158743, "text": "data is the name of the data set used." }, { "code": null, "e": 159016, "s": 158782, "text": "We will use the R in-built data set named readingSkills to create a decision tree. It describes the score of someone's readingSkills if we know the variables \"age\",\"shoesize\",\"score\" and whether the person is a native speaker or not." }, { "code": null, "e": 159041, "s": 159016, "text": "Here is the sample data." }, { "code": null, "e": 159215, "s": 159041, "text": "# Load the party package. It will automatically load other\n# dependent packages.\nlibrary(party)\n\n# Print some records from data set readingSkills.\nprint(head(readingSkills))" }, { "code": null, "e": 159292, "s": 159215, "text": "When we execute the above code, it produces the following result and chart −" }, { "code": null, "e": 159730, "s": 159292, "text": " nativeSpeaker age shoeSize score\n1 yes 5 24.83189 32.29385\n2 yes 6 25.95238 36.63105\n3 no 11 30.42170 49.60593\n4 yes 7 28.66450 40.28456\n5 yes 11 31.88207 55.46085\n6 yes 10 30.07843 52.83124\nLoading required package: methods\nLoading required package: grid\n...............................\n...............................\n" }, { "code": null, "e": 159810, "s": 159730, "text": "We will use the ctree() function to create the decision tree and see its graph." }, { "code": null, "e": 160210, "s": 159810, "text": "# Load the party package. It will automatically load other\n# dependent packages.\nlibrary(party)\n\n# Create the input data frame.\ninput.dat <- readingSkills[c(1:105),]\n\n# Give the chart file a name.\npng(file = \"decision_tree.png\")\n\n# Create the tree.\n output.tree <- ctree(\n nativeSpeaker ~ age + shoeSize + score, \n data = input.dat)\n\n# Plot the tree.\nplot(output.tree)\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 160277, "s": 160210, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 160687, "s": 160277, "text": "null device \n 1 \nLoading required package: methods\nLoading required package: grid\nLoading required package: mvtnorm\nLoading required package: modeltools\nLoading required package: stats4\nLoading required package: strucchange\nLoading required package: zoo\n\nAttaching package: ‘zoo’\n\nThe following objects are masked from ‘package:base’:\n\n as.Date, as.Date.numeric\n\nLoading required package: sandwich\n" }, { "code": null, "e": 160842, "s": 160687, "text": "From the decision tree shown above we can conclude that anyone whose readingSkills score is less than 38.3 and age is more than 6 is not a native Speaker." }, { "code": null, "e": 161146, "s": 160842, "text": "In the random forest approach, a large number of decision trees are created. Every observation is fed into every decision tree. The most common outcome for each observation is used as the final output. A new observation is fed into all the trees and taking a majority vote for each classification model." }, { "code": null, "e": 161317, "s": 161146, "text": "An error estimate is made for the cases which were not used while building the tree. That is called an OOB (Out-of-bag) error estimate which is mentioned as a percentage." }, { "code": null, "e": 161380, "s": 161317, "text": "The R package \"randomForest\" is used to create random forests." }, { "code": null, "e": 161495, "s": 161380, "text": "Use the below command in R console to install the package. You also have to install the dependent packages if any." }, { "code": null, "e": 161528, "s": 161495, "text": "install.packages(\"randomForest)\n" }, { "code": null, "e": 161639, "s": 161528, "text": "The package \"randomForest\" has the function randomForest() which is used to create and analyze random forests." }, { "code": null, "e": 161695, "s": 161639, "text": "The basic syntax for creating a random forest in R is −" }, { "code": null, "e": 161724, "s": 161695, "text": "randomForest(formula, data)\n" }, { "code": null, "e": 161778, "s": 161724, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 161848, "s": 161778, "text": "formula is a formula describing the predictor and response variables." }, { "code": null, "e": 161918, "s": 161848, "text": "formula is a formula describing the predictor and response variables." }, { "code": null, "e": 161957, "s": 161918, "text": "data is the name of the data set used." }, { "code": null, "e": 161996, "s": 161957, "text": "data is the name of the data set used." }, { "code": null, "e": 162223, "s": 161996, "text": "We will use the R in-built data set named readingSkills to create a decision tree. It describes the score of someone's readingSkills if we know the variables \"age\",\"shoesize\",\"score\" and whether the person is a native speaker." }, { "code": null, "e": 162248, "s": 162223, "text": "Here is the sample data." }, { "code": null, "e": 162421, "s": 162248, "text": "# Load the party package. It will automatically load other\n# required packages.\nlibrary(party)\n\n# Print some records from data set readingSkills.\nprint(head(readingSkills))" }, { "code": null, "e": 162498, "s": 162421, "text": "When we execute the above code, it produces the following result and chart −" }, { "code": null, "e": 162936, "s": 162498, "text": " nativeSpeaker age shoeSize score\n1 yes 5 24.83189 32.29385\n2 yes 6 25.95238 36.63105\n3 no 11 30.42170 49.60593\n4 yes 7 28.66450 40.28456\n5 yes 11 31.88207 55.46085\n6 yes 10 30.07843 52.83124\nLoading required package: methods\nLoading required package: grid\n...............................\n...............................\n" }, { "code": null, "e": 163024, "s": 162936, "text": "We will use the randomForest() function to create the decision tree and see it's graph." }, { "code": null, "e": 163383, "s": 163024, "text": "# Load the party package. It will automatically load other\n# required packages.\nlibrary(party)\nlibrary(randomForest)\n\n# Create the forest.\noutput.forest <- randomForest(nativeSpeaker ~ age + shoeSize + score, \n data = readingSkills)\n\n# View the forest results.\nprint(output.forest) \n\n# Importance of each predictor.\nprint(importance(fit,type = 2)) " }, { "code": null, "e": 163450, "s": 163383, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 163932, "s": 163450, "text": "Call:\n randomForest(formula = nativeSpeaker ~ age + shoeSize + score, \n data = readingSkills)\n Type of random forest: classification\n Number of trees: 500\nNo. of variables tried at each split: 1\n\n OOB estimate of error rate: 1%\nConfusion matrix:\n no yes class.error\nno 99 1 0.01\nyes 1 99 0.01\n MeanDecreaseGini\nage 13.95406\nshoeSize 18.91006\nscore 56.73051\n" }, { "code": null, "e": 164164, "s": 163932, "text": "From the random forest shown above we can conclude that the shoesize and score are the important factors deciding if someone is a native speaker or not. Also the model has only 1% error which means we can predict with 99% accuracy." }, { "code": null, "e": 164468, "s": 164164, "text": "Survival analysis deals with predicting the time when a specific event is going to occur. It is also known as failure time analysis or analysis of time to death. For example predicting the number of days a person with cancer will survive or predicting the time when a mechanical system is going to fail." }, { "code": null, "e": 164762, "s": 164468, "text": "The R package named survival is used to carry out survival analysis. This package contains the function Surv() which takes the input data as a R formula and creates a survival object among the chosen variables for analysis. Then we use the function survfit() to create a plot for the analysis." }, { "code": null, "e": 164792, "s": 164762, "text": "install.packages(\"survival\")\n" }, { "code": null, "e": 164850, "s": 164792, "text": "The basic syntax for creating survival analysis in R is −" }, { "code": null, "e": 164885, "s": 164850, "text": "Surv(time,event)\nsurvfit(formula)\n" }, { "code": null, "e": 164939, "s": 164885, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 164990, "s": 164939, "text": "time is the follow up time until the event occurs." }, { "code": null, "e": 165041, "s": 164990, "text": "time is the follow up time until the event occurs." }, { "code": null, "e": 165105, "s": 165041, "text": "event indicates the status of occurrence of the expected event." }, { "code": null, "e": 165169, "s": 165105, "text": "event indicates the status of occurrence of the expected event." }, { "code": null, "e": 165230, "s": 165169, "text": "formula is the relationship between the predictor variables." }, { "code": null, "e": 165291, "s": 165230, "text": "formula is the relationship between the predictor variables." }, { "code": null, "e": 165775, "s": 165291, "text": "We will consider the data set named \"pbc\" present in the survival packages installed above. It describes the survival data points about people affected with primary biliary cirrhosis (PBC) of the liver. Among the many columns present in the data set we are primarily concerned with the fields \"time\" and \"status\". Time represents the number of days between registration of the patient and earlier of the event between the patient receiving a liver transplant or death of the patient." }, { "code": null, "e": 165857, "s": 165775, "text": "# Load the library.\nlibrary(\"survival\")\n\n# Print first few rows.\nprint(head(pbc))" }, { "code": null, "e": 165934, "s": 165857, "text": "When we execute the above code, it produces the following result and chart −" }, { "code": null, "e": 166873, "s": 165934, "text": " id time status trt age sex ascites hepato spiders edema bili chol\n1 1 400 2 1 58.76523 f 1 1 1 1.0 14.5 261\n2 2 4500 0 1 56.44627 f 0 1 1 0.0 1.1 302\n3 3 1012 2 1 70.07255 m 0 0 0 0.5 1.4 176\n4 4 1925 2 1 54.74059 f 0 1 1 0.5 1.8 244\n5 5 1504 1 2 38.10541 f 0 1 1 0.0 3.4 279\n6 6 2503 2 2 66.25873 f 0 1 0 0.0 0.8 248\n albumin copper alk.phos ast trig platelet protime stage\n1 2.60 156 1718.0 137.95 172 190 12.2 4\n2 4.14 54 7394.8 113.52 88 221 10.6 3\n3 3.48 210 516.0 96.10 55 151 12.0 4\n4 2.54 64 6121.8 60.63 92 183 10.3 4\n5 3.53 143 671.0 113.15 72 136 10.9 3\n6 3.98 50 944.0 93.00 63 NA 11.0 3\n" }, { "code": null, "e": 166946, "s": 166873, "text": "From the above data we are considering time and status for our analysis." }, { "code": null, "e": 167056, "s": 166946, "text": "Now we proceed to apply the Surv() function to the above data set and create a plot that will show the trend." }, { "code": null, "e": 167324, "s": 167056, "text": "# Load the library.\nlibrary(\"survival\")\n\n# Create the survival object. \nsurvfit(Surv(pbc$time,pbc$status == 2)~1)\n\n# Give the chart file a name.\npng(file = \"survival.png\")\n\n# Plot the graph. \nplot(survfit(Surv(pbc$time,pbc$status == 2)~1))\n\n# Save the file.\ndev.off()" }, { "code": null, "e": 167401, "s": 167324, "text": "When we execute the above code, it produces the following result and chart −" }, { "code": null, "e": 167546, "s": 167401, "text": "Call: survfit(formula = Surv(pbc$time, pbc$status == 2) ~ 1)\n\n n events median 0.95LCL 0.95UCL \n 418 161 3395 3090 3853 \n" }, { "code": null, "e": 167663, "s": 167546, "text": "The trend in the above graph helps us predicting the probability of survival at the end of a certain number of days." }, { "code": null, "e": 167916, "s": 167663, "text": "Chi-Square test is a statistical method to determine if two categorical variables have a significant correlation between them. Both those variables should be from same population and they should be categorical like − Yes/No, Male/Female, Red/Green etc." }, { "code": null, "e": 168221, "s": 167916, "text": "For example, we can build a data set with observations on people's ice-cream buying pattern and try to correlate the gender of a person with the flavor of the ice-cream they prefer. If a correlation is found we can plan for appropriate stock of flavors by knowing the number of gender of people visiting." }, { "code": null, "e": 168287, "s": 168221, "text": "The function used for performing chi-Square test is chisq.test()." }, { "code": null, "e": 168345, "s": 168287, "text": "The basic syntax for creating a chi-square test in R is −" }, { "code": null, "e": 168363, "s": 168345, "text": "chisq.test(data)\n" }, { "code": null, "e": 168417, "s": 168363, "text": "Following is the description of the parameters used −" }, { "code": null, "e": 168517, "s": 168417, "text": "data is the data in form of a table containing the count value of the variables in the observation." }, { "code": null, "e": 168617, "s": 168517, "text": "data is the data in form of a table containing the count value of the variables in the observation." }, { "code": null, "e": 168740, "s": 168617, "text": "We will take the Cars93 data in the \"MASS\" library which represents the sales of different models of car in the year 1993." }, { "code": null, "e": 168775, "s": 168740, "text": "library(\"MASS\")\nprint(str(Cars93))" }, { "code": null, "e": 168842, "s": 168775, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 170976, "s": 168842, "text": "'data.frame': 93 obs. of 27 variables: \n $ Manufacturer : Factor w/ 32 levels \"Acura\",\"Audi\",..: 1 1 2 2 3 4 4 4 4 5 ... \n $ Model : Factor w/ 93 levels \"100\",\"190E\",\"240\",..: 49 56 9 1 6 24 54 74 73 35 ... \n $ Type : Factor w/ 6 levels \"Compact\",\"Large\",..: 4 3 1 3 3 3 2 2 3 2 ... \n $ Min.Price : num 12.9 29.2 25.9 30.8 23.7 14.2 19.9 22.6 26.3 33 ... \n $ Price : num 15.9 33.9 29.1 37.7 30 15.7 20.8 23.7 26.3 34.7 ... \n $ Max.Price : num 18.8 38.7 32.3 44.6 36.2 17.3 21.7 24.9 26.3 36.3 ... \n $ MPG.city : int 25 18 20 19 22 22 19 16 19 16 ... \n $ MPG.highway : int 31 25 26 26 30 31 28 25 27 25 ... \n $ AirBags : Factor w/ 3 levels \"Driver & Passenger\",..: 3 1 2 1 2 2 2 2 2 2 ... \n $ DriveTrain : Factor w/ 3 levels \"4WD\",\"Front\",..: 2 2 2 2 3 2 2 3 2 2 ... \n $ Cylinders : Factor w/ 6 levels \"3\",\"4\",\"5\",\"6\",..: 2 4 4 4 2 2 4 4 4 5 ... \n $ EngineSize : num 1.8 3.2 2.8 2.8 3.5 2.2 3.8 5.7 3.8 4.9 ... \n $ Horsepower : int 140 200 172 172 208 110 170 180 170 200 ... \n $ RPM : int 6300 5500 5500 5500 5700 5200 4800 4000 4800 4100 ... \n $ Rev.per.mile : int 2890 2335 2280 2535 2545 2565 1570 1320 1690 1510 ... \n $ Man.trans.avail : Factor w/ 2 levels \"No\",\"Yes\": 2 2 2 2 2 1 1 1 1 1 ... \n $ Fuel.tank.capacity: num 13.2 18 16.9 21.1 21.1 16.4 18 23 18.8 18 ... \n $ Passengers : int 5 5 5 6 4 6 6 6 5 6 ... \n $ Length : int 177 195 180 193 186 189 200 216 198 206 ... \n $ Wheelbase : int 102 115 102 106 109 105 111 116 108 114 ... \n $ Width : int 68 71 67 70 69 69 74 78 73 73 ... \n $ Turn.circle : int 37 38 37 37 39 41 42 45 41 43 ... \n $ Rear.seat.room : num 26.5 30 28 31 27 28 30.5 30.5 26.5 35 ... \n $ Luggage.room : int 11 15 14 17 13 16 17 21 14 18 ... \n $ Weight : int 2705 3560 3375 3405 3640 2880 3470 4105 3495 3620 ... \n $ Origin : Factor w/ 2 levels \"USA\",\"non-USA\": 2 2 2 2 2 1 1 1 1 1 ... \n $ Make : Factor w/ 93 levels \"Acura Integra\",..: 1 2 4 3 5 6 7 9 8 10 ... \n" }, { "code": null, "e": 171377, "s": 170976, "text": "The above result shows the dataset has many Factor variables which can be considered as categorical variables. For our model we will consider the variables \"AirBags\" and \"Type\". Here we aim to find out any significant correlation between the types of car sold and the type of Air bags it has. If correlation is observed we can estimate which types of cars can sell better with what types of air bags." }, { "code": null, "e": 171680, "s": 171377, "text": "# Load the library.\nlibrary(\"MASS\")\n\n# Create a data frame from the main data set.\ncar.data <- data.frame(Cars93$AirBags, Cars93$Type)\n\n# Create a table with the needed variables.\ncar.data = table(Cars93$AirBags, Cars93$Type) \nprint(car.data)\n\n# Perform the Chi-Square test.\nprint(chisq.test(car.data))" }, { "code": null, "e": 171747, "s": 171680, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 172178, "s": 171747, "text": " Compact Large Midsize Small Sporty Van\n Driver & Passenger 2 4 7 0 3 0\n Driver only 9 7 11 5 8 3\n None 5 0 4 16 3 6\n\n Pearson's Chi-squared test\n\ndata: car.data\nX-squared = 33.001, df = 10, p-value = 0.0002723\n\nWarning message:\nIn chisq.test(car.data) : Chi-squared approximation may be incorrect\n" }, { "code": null, "e": 172263, "s": 172178, "text": "The result shows the p-value of less than 0.05 which indicates a string correlation." }, { "code": null, "e": 172296, "s": 172263, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 172311, "s": 172296, "text": " Nishant Malik" }, { "code": null, "e": 172346, "s": 172311, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 172361, "s": 172346, "text": " Nishant Malik" }, { "code": null, "e": 172396, "s": 172361, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 172411, "s": 172396, "text": " Nishant Malik" }, { "code": null, "e": 172444, "s": 172411, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 172458, "s": 172444, "text": " Asif Hussain" }, { "code": null, "e": 172493, "s": 172458, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 172508, "s": 172493, "text": " Nishant Malik" }, { "code": null, "e": 172543, "s": 172508, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 172557, "s": 172543, "text": " Asif Hussain" }, { "code": null, "e": 172564, "s": 172557, "text": " Print" }, { "code": null, "e": 172575, "s": 172564, "text": " Add Notes" } ]
How to get default phone Network operator name in android?
This example demonstrate about How to get default phone Network operator name in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <TextView android:id="@+id/text" android:textSize="30sp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have taken a text view to show the phone network operator name. Step 3 − Add the following code to java/MainActivity.xml package com.example.myapplication; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.telephony.TelephonyManager; import android.widget.TextView; import static android.Manifest.permission.READ_PHONE_NUMBERS; import static android.Manifest.permission.READ_PHONE_STATE; import static android.Manifest.permission.READ_SMS; public class MainActivity extends AppCompatActivity { private static final int PERMISSION_REQUEST_CODE = 100; TextView textView; TelephonyManager telephonyManager; @RequiresApi(api = Build.VERSION_CODES.P) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); if (ActivityCompat.checkSelfPermission(this, READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{READ_SMS, READ_PHONE_NUMBERS, READ_PHONE_STATE}, PERMISSION_REQUEST_CODE); } else { textView.setText(""+telephonyManager.getNetworkOperatorName()); } } @RequiresApi(api = Build.VERSION_CODES.P) @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case PERMISSION_REQUEST_CODE: if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return; } else { textView.setText(""+telephonyManager.getNetworkOperatorName()); } } } } Step 3 − Add the following code toAndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapplication"> <uses-permission android:name="android.permission.READ_PHONE_NUMBERS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1152, "s": 1062, "text": "This example demonstrate about How to get default phone Network operator name in android." }, { "code": null, "e": 1281, "s": 1152, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1346, "s": 1281, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1914, "s": 1346, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:gravity=\"center\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"30sp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2000, "s": 1914, "text": "In the above code, we have taken a text view to show the phone network operator name." }, { "code": null, "e": 2057, "s": 2000, "text": "Step 3 − Add the following code to java/MainActivity.xml" }, { "code": null, "e": 4657, "s": 2057, "text": "package com.example.myapplication;\n\nimport android.Manifest;\nimport android.content.Context;\nimport android.content.pm.PackageManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.telephony.TelephonyManager;\nimport android.widget.TextView;\n\nimport static android.Manifest.permission.READ_PHONE_NUMBERS;\nimport static android.Manifest.permission.READ_PHONE_STATE;\nimport static android.Manifest.permission.READ_SMS;\n\npublic class MainActivity extends AppCompatActivity {\n private static final int PERMISSION_REQUEST_CODE = 100;\n TextView textView;\n TelephonyManager telephonyManager;\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);\n if (ActivityCompat.checkSelfPermission(this, READ_SMS) != PackageManager.PERMISSION_GRANTED &&\n ActivityCompat.checkSelfPermission(this, READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED &&\n ActivityCompat.checkSelfPermission(this, READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {\n ActivityCompat.requestPermissions(this, new String[]{READ_SMS, READ_PHONE_NUMBERS, READ_PHONE_STATE}, PERMISSION_REQUEST_CODE);\n } else {\n textView.setText(\"\"+telephonyManager.getNetworkOperatorName());\n }\n }\n\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n switch (requestCode) {\n case PERMISSION_REQUEST_CODE:\n if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) !=\n PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,\n Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED &&\n ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) !=\n PackageManager.PERMISSION_GRANTED) {\n return;\n } else {\n textView.setText(\"\"+telephonyManager.getNetworkOperatorName());\n }\n }\n }\n}" }, { "code": null, "e": 4711, "s": 4657, "text": "Step 3 − Add the following code toAndroidManifest.xml" }, { "code": null, "e": 5543, "s": 4711, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"com.example.myapplication\">\n\n <uses-permission android:name=\"android.permission.READ_PHONE_NUMBERS\" />\n <uses-permission android:name=\"android.permission.READ_PHONE_STATE\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5890, "s": 5543, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 5930, "s": 5890, "text": "Click here to download the project code" } ]
Difference between the Ternary operator and Null coalescing operator in php
Ternary operator is used to replace if else statements into one statement. (condition) ? expression1 : expression2; if(condition) { return expression1; } else { return expression2; } If condition is true, then it returns result of expression1 else it returns result of expression2. void is not allowed in condition or expressions. Null coalescing operator is used to provide not null value in case the variable is null. (variable) ?? expression; if(isset(variable)) { return variable; } else { return expression; } If variable is null, then it returns result of expression. <!DOCTYPE html> <html> <head> <title>PHP Example</title> </head> <body> <?php // fetch the value of $_GET['user'] and returns 'not passed' // if username is not passed $username = $_GET['username'] ?? 'not passed'; print($username); print("<br/>"); // Equivalent code using ternary operator $username = isset($_GET['username']) ? $_GET['username'] : 'not passed'; print($username); print("<br/>"); ?> </body> </html> not passed not passed
[ { "code": null, "e": 1137, "s": 1062, "text": "Ternary operator is used to replace if else statements into one statement." }, { "code": null, "e": 1178, "s": 1137, "text": "(condition) ? expression1 : expression2;" }, { "code": null, "e": 1251, "s": 1178, "text": "if(condition) {\n return expression1;\n}\nelse {\n return expression2;\n}" }, { "code": null, "e": 1399, "s": 1251, "text": "If condition is true, then it returns result of expression1 else it returns result of expression2. void is not allowed in condition or expressions." }, { "code": null, "e": 1488, "s": 1399, "text": "Null coalescing operator is used to provide not null value in case the variable is null." }, { "code": null, "e": 1514, "s": 1488, "text": "(variable) ?? expression;" }, { "code": null, "e": 1589, "s": 1514, "text": "if(isset(variable)) {\n return variable;\n}\nelse {\n return expression;\n}" }, { "code": null, "e": 1648, "s": 1589, "text": "If variable is null, then it returns result of expression." }, { "code": null, "e": 2128, "s": 1648, "text": "<!DOCTYPE html>\n<html>\n<head>\n <title>PHP Example</title>\n</head>\n<body>\n <?php\n // fetch the value of $_GET['user'] and returns 'not passed'\n // if username is not passed\n $username = $_GET['username'] ?? 'not passed';\n print($username);\n print(\"<br/>\");\n // Equivalent code using ternary operator\n $username = isset($_GET['username']) ? $_GET['username'] : 'not passed';\n print($username);\n print(\"<br/>\");\n ?>\n</body>\n</html>" }, { "code": null, "e": 2150, "s": 2128, "text": "not passed\nnot passed" } ]
Java Cryptography - Message Digest
Hash functions are extremely useful and appear in almost all information security applications. A hash function is a mathematical function that converts a numerical input value into another compressed numerical value. The input to the hash function is of arbitrary length but output is always of fixed length. Values returned by a hash function are called message digest or simply hash values. The following picture illustrated hash function. Java provides a class named MessageDigest which belongs to the package java.security. This class supports algorithms such as SHA-1, SHA 256, MD5 algorithms to convert an arbitrary length message to a message digest. To convert a given message to a message digest, follow the steps given below − The MessageDigest class provides a method named getInstance(). This method accepts a String variable specifying the name of the algorithm to be used and returns a MessageDigest object implementing the specified algorithm. Create MessageDigest object using the getInstance() method as shown below. MessageDigest md = MessageDigest.getInstance("SHA-256"); After creating the message digest object, you need to pass the message/data to it. You can do so using the update() method of the MessageDigest class, this method accepts a byte array representing the message and adds/passes it to the above created MessageDigest object. md.update(msg.getBytes()); You can generate the message digest using the digest() method od the MessageDigest class this method computes the hash function on the current object and returns the message digest in the form of byte array. Generate the message digest using the digest method. byte[] digest = md.digest(); Following is an example which reads data from a file and generate a message digest and prints it. import java.security.MessageDigest; import java.util.Scanner; public class MessageDigestExample { public static void main(String args[]) throws Exception{ //Reading data from user Scanner sc = new Scanner(System.in); System.out.println("Enter the message"); String message = sc.nextLine(); //Creating the MessageDigest object MessageDigest md = MessageDigest.getInstance("SHA-256"); //Passing data to the created MessageDigest Object md.update(message.getBytes()); //Compute the message digest byte[] digest = md.digest(); System.out.println(digest); //Converting the byte array in to HexString format StringBuffer hexString = new StringBuffer(); for (int i = 0;i<digest.length;i++) { hexString.append(Integer.toHexString(0xFF & digest[i])); } System.out.println("Hex format : " + hexString.toString()); } } The above program generates the following output − Enter the message Hello how are you [B@55f96302 Hex format: 2953d33828c395aebe8225236ba4e23fa75e6f13bd881b9056a3295cbd64d3 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2149, "s": 2053, "text": "Hash functions are extremely useful and appear in almost all information security applications." }, { "code": null, "e": 2363, "s": 2149, "text": "A hash function is a mathematical function that converts a numerical input value into another compressed numerical value. The input to the hash function is of arbitrary length but output is always of fixed length." }, { "code": null, "e": 2496, "s": 2363, "text": "Values returned by a hash function are called message digest or simply hash values. The following picture illustrated hash function." }, { "code": null, "e": 2712, "s": 2496, "text": "Java provides a class named MessageDigest which belongs to the package java.security. This class supports algorithms such as SHA-1, SHA 256, MD5 algorithms to convert an arbitrary length message to a message digest." }, { "code": null, "e": 2791, "s": 2712, "text": "To convert a given message to a message digest, follow the steps given below −" }, { "code": null, "e": 3013, "s": 2791, "text": "The MessageDigest class provides a method named getInstance(). This method accepts a String variable specifying the name of the algorithm to be used and returns a MessageDigest object implementing the specified algorithm." }, { "code": null, "e": 3088, "s": 3013, "text": "Create MessageDigest object using the getInstance() method as shown below." }, { "code": null, "e": 3146, "s": 3088, "text": "MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n" }, { "code": null, "e": 3417, "s": 3146, "text": "After creating the message digest object, you need to pass the message/data to it. You can do so using the update() method of the MessageDigest class, this method accepts a byte array representing the message and adds/passes it to the above created MessageDigest object." }, { "code": null, "e": 3445, "s": 3417, "text": "md.update(msg.getBytes());\n" }, { "code": null, "e": 3653, "s": 3445, "text": "You can generate the message digest using the digest() method od the MessageDigest class this method computes the hash function on the current object and returns the message digest in the form of byte array." }, { "code": null, "e": 3706, "s": 3653, "text": "Generate the message digest using the digest method." }, { "code": null, "e": 3736, "s": 3706, "text": "byte[] digest = md.digest();\n" }, { "code": null, "e": 3834, "s": 3736, "text": "Following is an example which reads data from a file and generate a message digest and prints it." }, { "code": null, "e": 4794, "s": 3834, "text": "import java.security.MessageDigest;\nimport java.util.Scanner;\n\npublic class MessageDigestExample {\n public static void main(String args[]) throws Exception{\n //Reading data from user\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the message\");\n String message = sc.nextLine();\n\t \n //Creating the MessageDigest object \n MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n\n //Passing data to the created MessageDigest Object\n md.update(message.getBytes());\n \n //Compute the message digest\n byte[] digest = md.digest(); \n System.out.println(digest); \n \n //Converting the byte array in to HexString format\n StringBuffer hexString = new StringBuffer();\n \n for (int i = 0;i<digest.length;i++) {\n hexString.append(Integer.toHexString(0xFF & digest[i]));\n }\n System.out.println(\"Hex format : \" + hexString.toString()); \n }\n}" }, { "code": null, "e": 4845, "s": 4794, "text": "The above program generates the following output −" }, { "code": null, "e": 4969, "s": 4845, "text": "Enter the message\nHello how are you\n[B@55f96302\nHex format: 2953d33828c395aebe8225236ba4e23fa75e6f13bd881b9056a3295cbd64d3\n" }, { "code": null, "e": 5002, "s": 4969, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5018, "s": 5002, "text": " Malhar Lathkar" }, { "code": null, "e": 5051, "s": 5018, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5067, "s": 5051, "text": " Malhar Lathkar" }, { "code": null, "e": 5102, "s": 5067, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5116, "s": 5102, "text": " Anadi Sharma" }, { "code": null, "e": 5150, "s": 5116, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5164, "s": 5150, "text": " Tushar Kale" }, { "code": null, "e": 5201, "s": 5164, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5216, "s": 5201, "text": " Monica Mittal" }, { "code": null, "e": 5249, "s": 5216, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5268, "s": 5249, "text": " Arnab Chakraborty" }, { "code": null, "e": 5275, "s": 5268, "text": " Print" }, { "code": null, "e": 5286, "s": 5275, "text": " Add Notes" } ]
BERT for dummies — Step by Step Tutorial | by Michel Kana, Ph.D | Towards Data Science
This article introduces everything you need in order to take off with BERT. We provide a step-by-step guide on how to fine-tune Bidirectional Encoder Representations from Transformers (BERT) for Natural Language Understanding and benchmark it with LSTM. Chatbots, virtual assistant, and dialog agents will typically classify queries into specific intents in order to generate the most coherent response. Intent classification is a classification problem that predicts the intent label for any given user query. It is usually a multi-class classification problem, where the query is assigned one unique label. For example, the query “how much does the limousine service cost within pittsburgh” is labeled as “groundfare” while the query “what kind of ground transportation is available in denver” is labeled as “ground_service”. The query “i want to fly from boston at 838 am and arrive in Denver at 1110 in the morning” is a “flight” intent, while “ show me the costs and times for flights from san francisco to atlanta” is an “airfare+flight_time” intent. towardsdatascience.com The examples above show how ambiguous intent labeling can be. Users might add misleading words, causing multiple intents to be present in the same query. Attention-based learning methods were proposed for intent classification (Liu and Lane, 2016; Goo et al., 2018). One type of network built with attention is called a Transformer. It applies attention mechanisms to gather information about the relevant context of a given word, and then encode that context in a rich vector that smartly represents the word. In this article, we will demonstrate Transformer, especially how its attention mechanism helps in solving the intent classification task by learning contextual relationships. After demonstrating the limitation of a LSTM-based classifier, we introduce BERT: Pre-training of Deep Bidirectional Transformers, a novel Transformer-approach, pre-trained on large corpora and open-sourced. The last part of this article presents the Python code necessary for fine-tuning BERT for the task of Intent Classification and achieving state-of-art accuracy on unseen intent queries. We use the ATIS (Airline Travel Information System) dataset, a standard benchmark dataset widely used for recognizing the intent behind a customer query. In one of our previous article, you will find the Python code for loading the ATIS dataset. In the ATIS training dataset, we have 26 distinct intents, whose distribution is shown below. The dataset is highly unbalanced, with most queries labeled as “flight” (code 14). Before looking at Transformer, we implement a simple LSTM recurrent network for solving the classification task. After the usual preprocessing, tokenization and vectorization, the 4978 samples are fed into a Keras Embedding layer, which projects each word as a Word2vec embedding of dimension 256. The results are passed through a LSTM layer with 1024 cells. This produces 1024 outputs which are given to a Dense layer with 26 nodes and softmax activation. The probabilities created at the end of this pipeline are compared to the original labels using categorical crossentropy. As we can see in the training output above, the Adam optimizer gets stuck, the loss and accuracy do not improve. The model appears to predict the majority class “flight” at each step. When we use the trained model to predict the intents on the unseen test dataset, the confusion matrix clearly shows how the model overfits to the majority “flight” class. Dealing with an imbalanced dataset is a common challenge when solving a classification task. Data augmentation is one thing that comes to mind as a good workaround. Here, it is not rare to encounter the SMOTE algorithm, as a popular choice for augmenting the dataset without biasing predictions. SMOTE uses a k-Nearest Neighbors classifier to create synthetic datapoints as a multi-dimensional interpolation of closely related groups of true data points. Unfortunately, we have 25 minority classes in the ATIS training dataset, leaving us with a single overly representative class. SMOTE fails to work as it cannot find enough neighbors (minimum is 2). Oversampling with replacement is an alternative to SMOTE, which also does not improve the model’s predictive performance either. The SNIPS dataset, which is collected from the Snips personal voice assistant, a more recent dataset for natural language understanding, is a dataset which could be used to augment the ATIS dataset in a future effort. Since we were not quite successful at augmenting the dataset, now, we will rather reduce the scope of the problem. We define a binary classification task where the “flight” queries are evaluated against the remaining classes, by collapsing them into a single class called “other”. The distribution of labels in this new dataset is given below. We can now use a similar network architecture as previously. The only change is to reduce the number of nodes in the Dense layer to 1, activation function to sigmoid and the loss function to binary crossentropy. Surprisingly, the LSTM model is still not able to learn to predict the intent, given the user query, as we see below. After 10 epochs, we evaluate the model on an unseen test dataset. This time, we have all samples being predicted as “other”, although “flight” had more than twice as many samples as “other” in the training set. The motivation why we are now looking at Transformer is the poor classification result we witnessed with sequence-to-sequence models on the Intent Classification task when the dataset is imbalanced. In this section, we introduce a variant of Transformer and implement it for solving our classification problem. We will look especially at the late 2018 published Bidirectional Encoder Representations from Transformers (BERT). BERT is basically a trained Transformer Encoder stack, with twelve in the Base version, and twenty-four in the Large version, compared to 6 encoder layers in the original Transformer we described in the previous article. towardsdatascience.com BERT encoders have larger feedforward networks (768 and 1024 nodes in Base and Large respectively) and more attention heads (12 and 16 respectively). BERT was trained on Wikipedia and Book Corpus, a dataset containing +10,000 books of different genres. Below you can see a diagram of additional variants of BERT pre-trained on specialized corpora. BERT was released to the public, as a new era in NLP. Its open-sourced model code broke several records for difficult language-based tasks. The pre-trained model on massive datasets enables anyone building natural language processing to use this free powerhouse. BERT theoretically allows us to smash multiple benchmarks with minimal task-specific fine-tuning. BERT works similarly to the Transformer encoder stack, by taking a sequence of words as input which keep flowing up the stack from one encoder to the next, while new sequences are coming in. The final output for each sequence is a vector of 728 numbers in Base or 1024 in Large version. We will use such vectors for our intent classification problem. Proper language representation is key for general-purpose language understanding by machines. Context-free models such as word2vec or GloVe generate a single word embedding representation for each word in the vocabulary. For example, the word “bank” would have the same representation in “bank deposit” and in “riverbank”. Contextual models instead generate a representation of each word that is based on the other words in the sentence. BERT, as a contextual model, captures these relationships in a bidirectional way. BERT was built upon recent work and clever ideas in pre-training contextual representations including Semi-supervised Sequence Learning, Generative Pre-Training, ELMo, the OpenAI Transformer, ULMFit and the Transformer. Although these models are all unidirectional or shallowly bidirectional, BERT is fully bidirectional. We will use BERT to extract high-quality language features from the ATIS query text data, and fine-tune BERT on a specific task (classification) with own data to produce state of the art predictions. Feel free to download the original Jupyter Notebook, which we will adapt for our goal in this section. As for development environment, we recommend Google Colab with its offer of free GPUs and TPUs, which can be added by going to the menu and selecting: Edit -> Notebook Settings -> Add accelerator (GPU). An alternative to Colab is to use a JupyterLab Notebook Instance on Google Cloud Platform, by selecting the menu AI Platform -> Notebooks -> New Instance -> Pytorch 1.1 -> With 1 NVIDIA Tesla K80 after requesting Google to increase your GPU quota. This will cost ca. $0.40 per hour (current pricing, which might change). Below you find the code for verifying your GPU availability. We will use the PyTorch interface for BERT by Hugging Face, which at the moment, is the most widely accepted and most powerful PyTorch interface for getting on rails with BERT. Hugging Face provides pytorch-transformers repository with additional libraries for interfacing more pre-trained models for natural language processing: GPT, GPT-2, Transformer-XL, XLNet, XLM. As you can see below, in order for torch to use the GPU, you have to identify and specify the GPU as the device, because later in the training loop, we load data onto that device. Now we can upload our dataset to the notebook instance. Please run the code from our previous article to preprocess the dataset using the Python function load_atis() before moving on. BERT expects input data in a specific format, with special tokens to mark the beginning ([CLS]) and separation/end of sentences ([SEP]). Furthermore, we need to tokenize our text into tokens that correspond to BERT’s vocabulary. '[CLS] i want to fly from boston at 838 am and arrive in denver at 1110 in the morning [SEP]'['[CLS]', 'i', 'want', 'to', 'fly', 'from', 'boston', 'at', '83', '##8', 'am', 'and', 'arrive', 'in', 'denver', 'at', '111', '##0', 'in', 'the', 'morning', '[SEP]'] For each tokenized sentence, BERT requires input ids, a sequence of integers identifying each input token to its index number in the BERT tokenizer vocabulary. BERT’s clever language modeling task masks 15% of words in the input and asks the model to predict the missing word. To make BERT better at handling relationships between multiple sentences, the pre-training process also included an additional task: given two sentences (A and B), is B likely to be the sentence that follows A? Therefore we need to tell BERT what task we are solving by using the concept of attention mask and segment mask. In our case, all words in a query will be predicted and we do not have multiple sentences per query. We define the mask below. Now it is time to create all tensors and iterators needed during fine-tuning of BERT using our data. Finally, it is time to fine-tune the BERT model so that it outputs the intent class given a user query string. For this purpose, we use the BertForSequenceClassification, which is the normal BERT model with an added single linear layer on top for classification. Below we display a summary of the model. The encoder summary is shown only once. The same summary would normally be repeated 12 times. We display only 1 of them for simplicity sake. We can see the BertEmbedding layer at the beginning, followed by a Transformer architecture for each encoder layer: BertAttention, BertIntermediate, BertOutput. At the end, we have the Classifier layer. As we feed input data, the entire pre-trained BERT model and the additional untrained classification layer is trained on our specific task. Training the classifier is relatively inexpensive. The bottom layers have already great English words representation, and we only really need to train the top layer, with a bit of tweaking going on in the lower levels to accommodate our task. This is a variant of transfer learning. The training loss plot from the variable train_loss_set looks awesome. The whole training loop took less than 10 minutes. Now, it is the moment of truth. Is BERT overfitting? Or is it doing better than our previous LSTM network? We now load the test dataset and prepare inputs just as we did with the training set. We then create tensors and run the model on the dataset in evaluation mode. With BERT we are able to get a good score (95.93%) on the intent classification task. This demonstrates that with a pre-trained BERT model it is possible to quickly and effectively create a high-quality model with minimal effort and training time using the PyTorch interface. In this article, I demonstrated how to load the pre-trained BERT model in a PyTorch notebook and fine-tune it on your own dataset for solving a specific task. Attention matters when dealing with natural language understanding tasks. When combined with powerful words embedding from Transformer, an intent classifier can significantly improve its performance, as we successfully exposed. My new article provides hands-on proven PyTorch code for question answering with BERT fine-tuned on the SQuAD dataset. towardsdatascience.com This area opens a wide door for future work, especially because natural language understanding is at the core of several technologies including conversational AI (chatbots, personal assistants) and upcoming augmented analytics which was ranked by Gartner as a top disruptive challenge that organizations will face very soon. Understanding natural language has an impact on traditional analytical and business intelligence since executives are rapidly adopting smart information retrieval by text queries and data narratives instead of dashboards with complex charts. Thank you for reading more from me.
[ { "code": null, "e": 426, "s": 172, "text": "This article introduces everything you need in order to take off with BERT. We provide a step-by-step guide on how to fine-tune Bidirectional Encoder Representations from Transformers (BERT) for Natural Language Understanding and benchmark it with LSTM." }, { "code": null, "e": 1229, "s": 426, "text": "Chatbots, virtual assistant, and dialog agents will typically classify queries into specific intents in order to generate the most coherent response. Intent classification is a classification problem that predicts the intent label for any given user query. It is usually a multi-class classification problem, where the query is assigned one unique label. For example, the query “how much does the limousine service cost within pittsburgh” is labeled as “groundfare” while the query “what kind of ground transportation is available in denver” is labeled as “ground_service”. The query “i want to fly from boston at 838 am and arrive in Denver at 1110 in the morning” is a “flight” intent, while “ show me the costs and times for flights from san francisco to atlanta” is an “airfare+flight_time” intent." }, { "code": null, "e": 1252, "s": 1229, "text": "towardsdatascience.com" }, { "code": null, "e": 1763, "s": 1252, "text": "The examples above show how ambiguous intent labeling can be. Users might add misleading words, causing multiple intents to be present in the same query. Attention-based learning methods were proposed for intent classification (Liu and Lane, 2016; Goo et al., 2018). One type of network built with attention is called a Transformer. It applies attention mechanisms to gather information about the relevant context of a given word, and then encode that context in a rich vector that smartly represents the word." }, { "code": null, "e": 2486, "s": 1763, "text": "In this article, we will demonstrate Transformer, especially how its attention mechanism helps in solving the intent classification task by learning contextual relationships. After demonstrating the limitation of a LSTM-based classifier, we introduce BERT: Pre-training of Deep Bidirectional Transformers, a novel Transformer-approach, pre-trained on large corpora and open-sourced. The last part of this article presents the Python code necessary for fine-tuning BERT for the task of Intent Classification and achieving state-of-art accuracy on unseen intent queries. We use the ATIS (Airline Travel Information System) dataset, a standard benchmark dataset widely used for recognizing the intent behind a customer query." }, { "code": null, "e": 2755, "s": 2486, "text": "In one of our previous article, you will find the Python code for loading the ATIS dataset. In the ATIS training dataset, we have 26 distinct intents, whose distribution is shown below. The dataset is highly unbalanced, with most queries labeled as “flight” (code 14)." }, { "code": null, "e": 3334, "s": 2755, "text": "Before looking at Transformer, we implement a simple LSTM recurrent network for solving the classification task. After the usual preprocessing, tokenization and vectorization, the 4978 samples are fed into a Keras Embedding layer, which projects each word as a Word2vec embedding of dimension 256. The results are passed through a LSTM layer with 1024 cells. This produces 1024 outputs which are given to a Dense layer with 26 nodes and softmax activation. The probabilities created at the end of this pipeline are compared to the original labels using categorical crossentropy." }, { "code": null, "e": 3518, "s": 3334, "text": "As we can see in the training output above, the Adam optimizer gets stuck, the loss and accuracy do not improve. The model appears to predict the majority class “flight” at each step." }, { "code": null, "e": 3689, "s": 3518, "text": "When we use the trained model to predict the intents on the unseen test dataset, the confusion matrix clearly shows how the model overfits to the majority “flight” class." }, { "code": null, "e": 4471, "s": 3689, "text": "Dealing with an imbalanced dataset is a common challenge when solving a classification task. Data augmentation is one thing that comes to mind as a good workaround. Here, it is not rare to encounter the SMOTE algorithm, as a popular choice for augmenting the dataset without biasing predictions. SMOTE uses a k-Nearest Neighbors classifier to create synthetic datapoints as a multi-dimensional interpolation of closely related groups of true data points. Unfortunately, we have 25 minority classes in the ATIS training dataset, leaving us with a single overly representative class. SMOTE fails to work as it cannot find enough neighbors (minimum is 2). Oversampling with replacement is an alternative to SMOTE, which also does not improve the model’s predictive performance either." }, { "code": null, "e": 4689, "s": 4471, "text": "The SNIPS dataset, which is collected from the Snips personal voice assistant, a more recent dataset for natural language understanding, is a dataset which could be used to augment the ATIS dataset in a future effort." }, { "code": null, "e": 5033, "s": 4689, "text": "Since we were not quite successful at augmenting the dataset, now, we will rather reduce the scope of the problem. We define a binary classification task where the “flight” queries are evaluated against the remaining classes, by collapsing them into a single class called “other”. The distribution of labels in this new dataset is given below." }, { "code": null, "e": 5363, "s": 5033, "text": "We can now use a similar network architecture as previously. The only change is to reduce the number of nodes in the Dense layer to 1, activation function to sigmoid and the loss function to binary crossentropy. Surprisingly, the LSTM model is still not able to learn to predict the intent, given the user query, as we see below." }, { "code": null, "e": 5574, "s": 5363, "text": "After 10 epochs, we evaluate the model on an unseen test dataset. This time, we have all samples being predicted as “other”, although “flight” had more than twice as many samples as “other” in the training set." }, { "code": null, "e": 6000, "s": 5574, "text": "The motivation why we are now looking at Transformer is the poor classification result we witnessed with sequence-to-sequence models on the Intent Classification task when the dataset is imbalanced. In this section, we introduce a variant of Transformer and implement it for solving our classification problem. We will look especially at the late 2018 published Bidirectional Encoder Representations from Transformers (BERT)." }, { "code": null, "e": 6221, "s": 6000, "text": "BERT is basically a trained Transformer Encoder stack, with twelve in the Base version, and twenty-four in the Large version, compared to 6 encoder layers in the original Transformer we described in the previous article." }, { "code": null, "e": 6244, "s": 6221, "text": "towardsdatascience.com" }, { "code": null, "e": 6592, "s": 6244, "text": "BERT encoders have larger feedforward networks (768 and 1024 nodes in Base and Large respectively) and more attention heads (12 and 16 respectively). BERT was trained on Wikipedia and Book Corpus, a dataset containing +10,000 books of different genres. Below you can see a diagram of additional variants of BERT pre-trained on specialized corpora." }, { "code": null, "e": 6953, "s": 6592, "text": "BERT was released to the public, as a new era in NLP. Its open-sourced model code broke several records for difficult language-based tasks. The pre-trained model on massive datasets enables anyone building natural language processing to use this free powerhouse. BERT theoretically allows us to smash multiple benchmarks with minimal task-specific fine-tuning." }, { "code": null, "e": 7304, "s": 6953, "text": "BERT works similarly to the Transformer encoder stack, by taking a sequence of words as input which keep flowing up the stack from one encoder to the next, while new sequences are coming in. The final output for each sequence is a vector of 728 numbers in Base or 1024 in Large version. We will use such vectors for our intent classification problem." }, { "code": null, "e": 8146, "s": 7304, "text": "Proper language representation is key for general-purpose language understanding by machines. Context-free models such as word2vec or GloVe generate a single word embedding representation for each word in the vocabulary. For example, the word “bank” would have the same representation in “bank deposit” and in “riverbank”. Contextual models instead generate a representation of each word that is based on the other words in the sentence. BERT, as a contextual model, captures these relationships in a bidirectional way. BERT was built upon recent work and clever ideas in pre-training contextual representations including Semi-supervised Sequence Learning, Generative Pre-Training, ELMo, the OpenAI Transformer, ULMFit and the Transformer. Although these models are all unidirectional or shallowly bidirectional, BERT is fully bidirectional." }, { "code": null, "e": 8346, "s": 8146, "text": "We will use BERT to extract high-quality language features from the ATIS query text data, and fine-tune BERT on a specific task (classification) with own data to produce state of the art predictions." }, { "code": null, "e": 8449, "s": 8346, "text": "Feel free to download the original Jupyter Notebook, which we will adapt for our goal in this section." }, { "code": null, "e": 9034, "s": 8449, "text": "As for development environment, we recommend Google Colab with its offer of free GPUs and TPUs, which can be added by going to the menu and selecting: Edit -> Notebook Settings -> Add accelerator (GPU). An alternative to Colab is to use a JupyterLab Notebook Instance on Google Cloud Platform, by selecting the menu AI Platform -> Notebooks -> New Instance -> Pytorch 1.1 -> With 1 NVIDIA Tesla K80 after requesting Google to increase your GPU quota. This will cost ca. $0.40 per hour (current pricing, which might change). Below you find the code for verifying your GPU availability." }, { "code": null, "e": 9404, "s": 9034, "text": "We will use the PyTorch interface for BERT by Hugging Face, which at the moment, is the most widely accepted and most powerful PyTorch interface for getting on rails with BERT. Hugging Face provides pytorch-transformers repository with additional libraries for interfacing more pre-trained models for natural language processing: GPT, GPT-2, Transformer-XL, XLNet, XLM." }, { "code": null, "e": 9584, "s": 9404, "text": "As you can see below, in order for torch to use the GPU, you have to identify and specify the GPU as the device, because later in the training loop, we load data onto that device." }, { "code": null, "e": 9768, "s": 9584, "text": "Now we can upload our dataset to the notebook instance. Please run the code from our previous article to preprocess the dataset using the Python function load_atis() before moving on." }, { "code": null, "e": 9997, "s": 9768, "text": "BERT expects input data in a specific format, with special tokens to mark the beginning ([CLS]) and separation/end of sentences ([SEP]). Furthermore, we need to tokenize our text into tokens that correspond to BERT’s vocabulary." }, { "code": null, "e": 10257, "s": 9997, "text": "'[CLS] i want to fly from boston at 838 am and arrive in denver at 1110 in the morning [SEP]'['[CLS]', 'i', 'want', 'to', 'fly', 'from', 'boston', 'at', '83', '##8', 'am', 'and', 'arrive', 'in', 'denver', 'at', '111', '##0', 'in', 'the', 'morning', '[SEP]']" }, { "code": null, "e": 10417, "s": 10257, "text": "For each tokenized sentence, BERT requires input ids, a sequence of integers identifying each input token to its index number in the BERT tokenizer vocabulary." }, { "code": null, "e": 10985, "s": 10417, "text": "BERT’s clever language modeling task masks 15% of words in the input and asks the model to predict the missing word. To make BERT better at handling relationships between multiple sentences, the pre-training process also included an additional task: given two sentences (A and B), is B likely to be the sentence that follows A? Therefore we need to tell BERT what task we are solving by using the concept of attention mask and segment mask. In our case, all words in a query will be predicted and we do not have multiple sentences per query. We define the mask below." }, { "code": null, "e": 11086, "s": 10985, "text": "Now it is time to create all tensors and iterators needed during fine-tuning of BERT using our data." }, { "code": null, "e": 11734, "s": 11086, "text": "Finally, it is time to fine-tune the BERT model so that it outputs the intent class given a user query string. For this purpose, we use the BertForSequenceClassification, which is the normal BERT model with an added single linear layer on top for classification. Below we display a summary of the model. The encoder summary is shown only once. The same summary would normally be repeated 12 times. We display only 1 of them for simplicity sake. We can see the BertEmbedding layer at the beginning, followed by a Transformer architecture for each encoder layer: BertAttention, BertIntermediate, BertOutput. At the end, we have the Classifier layer." }, { "code": null, "e": 12157, "s": 11734, "text": "As we feed input data, the entire pre-trained BERT model and the additional untrained classification layer is trained on our specific task. Training the classifier is relatively inexpensive. The bottom layers have already great English words representation, and we only really need to train the top layer, with a bit of tweaking going on in the lower levels to accommodate our task. This is a variant of transfer learning." }, { "code": null, "e": 12279, "s": 12157, "text": "The training loss plot from the variable train_loss_set looks awesome. The whole training loop took less than 10 minutes." }, { "code": null, "e": 12548, "s": 12279, "text": "Now, it is the moment of truth. Is BERT overfitting? Or is it doing better than our previous LSTM network? We now load the test dataset and prepare inputs just as we did with the training set. We then create tensors and run the model on the dataset in evaluation mode." }, { "code": null, "e": 12824, "s": 12548, "text": "With BERT we are able to get a good score (95.93%) on the intent classification task. This demonstrates that with a pre-trained BERT model it is possible to quickly and effectively create a high-quality model with minimal effort and training time using the PyTorch interface." }, { "code": null, "e": 13211, "s": 12824, "text": "In this article, I demonstrated how to load the pre-trained BERT model in a PyTorch notebook and fine-tune it on your own dataset for solving a specific task. Attention matters when dealing with natural language understanding tasks. When combined with powerful words embedding from Transformer, an intent classifier can significantly improve its performance, as we successfully exposed." }, { "code": null, "e": 13330, "s": 13211, "text": "My new article provides hands-on proven PyTorch code for question answering with BERT fine-tuned on the SQuAD dataset." }, { "code": null, "e": 13353, "s": 13330, "text": "towardsdatascience.com" }, { "code": null, "e": 13920, "s": 13353, "text": "This area opens a wide door for future work, especially because natural language understanding is at the core of several technologies including conversational AI (chatbots, personal assistants) and upcoming augmented analytics which was ranked by Gartner as a top disruptive challenge that organizations will face very soon. Understanding natural language has an impact on traditional analytical and business intelligence since executives are rapidly adopting smart information retrieval by text queries and data narratives instead of dashboards with complex charts." } ]
How to declare a variable inside a procedure in MySQL?
You can use the DECLARE command to declare a variable inside a MySQL procedure. Let us create a stored procedure in MySQL − mysql> DELIMITER // mysql> CREATE PROCEDURE DECLARE_VARIABLE_DEMO(IN value int) -> BEGIN -> DECLARE searchValue int; -> set searchValue=value; -> if searchValue=10 then -> select searchValue+100; -> else -> select searchValue; -> end if; -> END -> // Query OK, 0 rows affected (0.17 sec) mysql> DELIMITER ; Above, we have declared a variable. Now, let us call the stored procedure using CALL command − mysql> call DECLARE_VARIABLE_DEMO(10); This will produce the following output − +-----------------+ | searchValue+100 | +-----------------+ | 110 | +-----------------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.02 sec)
[ { "code": null, "e": 1186, "s": 1062, "text": "You can use the DECLARE command to declare a variable inside a MySQL procedure. Let us create a stored procedure in MySQL −" }, { "code": null, "e": 1529, "s": 1186, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE DECLARE_VARIABLE_DEMO(IN value int)\n -> BEGIN\n -> DECLARE searchValue int;\n -> set searchValue=value;\n -> if searchValue=10 then\n -> select searchValue+100;\n -> else\n -> select searchValue;\n -> end if;\n -> END\n -> //\nQuery OK, 0 rows affected (0.17 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 1624, "s": 1529, "text": "Above, we have declared a variable. Now, let us call the stored procedure using CALL command −" }, { "code": null, "e": 1663, "s": 1624, "text": "mysql> call DECLARE_VARIABLE_DEMO(10);" }, { "code": null, "e": 1704, "s": 1663, "text": "This will produce the following output −" }, { "code": null, "e": 1865, "s": 1704, "text": "+-----------------+\n| searchValue+100 |\n+-----------------+\n| 110 |\n+-----------------+\n1 row in set (0.00 sec)\nQuery OK, 0 rows affected (0.02 sec)" } ]
execve() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint execve - execute program #include <unistd.h> int execve(const char *filename, char *const argv[], char *const envp[]); int execve(const char *filename, char *const argv[], char *const envp[]); execve() executes the program pointed to by filename. filename must be either a binary executable, or a script starting with a line of the form "#! interpreter [arg]". In the latter case, the interpreter must be a valid pathname for an executable which is not itself a script, which will be invoked as interpreter [arg] filename. argv is an array of argument strings passed to the new program. envp is an array of strings, conventionally of the form key=value, which are passed as environment to the new program. Both argv and envp must be terminated by a null pointer. The argument vector and environment can be accessed by the called program’s main function, when it is defined as int main(int argc, char *argv[], char *envp[]). execve() does not return on success, and the text, data, bss, and stack of the calling process are overwritten by that of the program loaded. The program invoked inherits the calling process’s PID, and any open file descriptors that are not set to close-on-exec. Signals pending on the calling process are cleared. Any signals set to be caught by the calling process are reset to their default behaviour. The SIGCHLD signal (when set to SIG_IGN) may or may not be reset to SIG_DFL. If the current program is being ptraced, a SIGTRAP is sent to it after a successful execve(). If the set-user-ID bit is set on the program file pointed to by filename, and the calling process is not being ptraced, then the effective user ID of the calling process is changed to that of the owner of the program file. i Similarly, when the set-group-ID bit of the program file is set the effective group ID of the calling process is set to the group of the program file. The effective user ID of the process is copied to the saved set-user-ID; similarly, the effective group ID is copied to the saved set-group-ID. This copying takes place after any effective ID changes that occur because of the set-user-ID and set-group-ID permission bits. If the executable is an a.out dynamically-linked binary executable containing shared-library stubs, the Linux dynamic linker ld.so(8) is called at the start of execution to bring needed shared libraries into memory and link the executable with them. If the executable is a dynamically-linked ELF executable, the interpreter named in the PT_INTERP segment is used to load the needed shared libraries. This interpreter is typically /lib/ld-linux.so.1 for binaries linked with the Linux libc version 5, or /lib/ld-linux.so.2 for binaries linked with the GNU libc version 2. On success, execve() does not return, on error -1 is returned, and errno is set appropriately. SVr4, 4.3BSD, POSIX.1-2001. POSIX.1-2001 does not document the #! behavior but is otherwise compatible. SUID and SGID processes can not be ptrace()d. Linux ignores the SUID and SGID bits on scripts. The result of mounting a filesystem nosuid vary between Linux kernel versions: some will refuse execution of SUID/SGID executables when this would give the user powers she did not have already (and return EPERM), some will just ignore the SUID/SGID bits and exec() successfully. A maximum line length of 127 characters is allowed for the first line in a #! executable shell script. With Unix V6 the argument list of an exec() call was ended by 0, while the argument list of main was ended by -1. Thus, this argument list was not directly usable in a further exec() call. Since Unix V7 both are NULL. chmod (2) chmod (2) fork (2) fork (2) path_resolution (2) path_resolution (2) ptrace (2) ptrace (2) ld (8) ld (8) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2344, "s": 2319, "text": "execve - execute program" }, { "code": null, "e": 2453, "s": 2344, "text": "#include <unistd.h> \nint execve(const char *filename, char *const argv[], \n char *const envp[]); \n" }, { "code": null, "e": 2542, "s": 2453, "text": "\nint execve(const char *filename, char *const argv[], \n char *const envp[]); \n" }, { "code": null, "e": 2872, "s": 2542, "text": "execve() executes the program pointed to by filename.\nfilename must be either a binary executable, or a script\nstarting with a line of the form \"#! interpreter [arg]\".\nIn the latter case, the interpreter must be a valid pathname for an\nexecutable which is not itself a script, which will be invoked as\ninterpreter [arg] filename." }, { "code": null, "e": 3276, "s": 2872, "text": "\nargv is an array of argument strings passed to the new program.\nenvp is an array of strings, conventionally of the form\nkey=value, which are passed as environment to the new\nprogram. Both argv and envp must be terminated by a null\npointer. The argument vector and environment can be accessed by the\ncalled program’s main function, when it is defined as int main(int\nargc, char *argv[], char *envp[])." }, { "code": null, "e": 3762, "s": 3276, "text": "\nexecve() does not return on success, and the text, data, bss, and\nstack of the calling process are overwritten by that of the program\nloaded. The program invoked inherits the calling process’s PID, and any\nopen file descriptors that are not set to close-on-exec. Signals pending\non the calling process are cleared. Any signals set to be caught by\nthe calling process are reset to their default behaviour.\nThe SIGCHLD signal (when set to SIG_IGN) may or may not be reset to SIG_DFL." }, { "code": null, "e": 3857, "s": 3762, "text": "\nIf the current program is being ptraced, a SIGTRAP is sent to it\nafter a successful execve()." }, { "code": null, "e": 4235, "s": 3857, "text": "\nIf the set-user-ID bit is set on the program file pointed to by\nfilename, and the calling process is not being ptraced,\nthen the effective user ID of the calling process is changed\nto that of the owner of the program file. i\nSimilarly, when the set-group-ID\nbit of the program file is set the effective group ID of the calling\nprocess is set to the group of the program file." }, { "code": null, "e": 4508, "s": 4235, "text": "\nThe effective user ID of the process is copied to the saved set-user-ID;\nsimilarly, the effective group ID is copied to the saved set-group-ID.\nThis copying takes place after any effective ID changes that occur\nbecause of the set-user-ID and set-group-ID permission bits." }, { "code": null, "e": 4759, "s": 4508, "text": "\nIf the executable is an a.out dynamically-linked\nbinary executable containing\nshared-library stubs, the Linux dynamic linker\nld.so(8)\nis called at the start of execution to bring\nneeded shared libraries into memory\nand link the executable with them." }, { "code": null, "e": 5082, "s": 4759, "text": "\nIf the executable is a dynamically-linked ELF executable, the\ninterpreter named in the PT_INTERP segment is used to load the needed\nshared libraries. This interpreter is typically\n/lib/ld-linux.so.1 for binaries linked with the Linux libc\nversion 5, or /lib/ld-linux.so.2 for binaries linked with the\nGNU libc version 2." }, { "code": null, "e": 5177, "s": 5082, "text": "On success, execve() does not return, on error -1 is returned, and\nerrno is set appropriately." }, { "code": null, "e": 5284, "s": 5177, "text": "SVr4, 4.3BSD, POSIX.1-2001. \nPOSIX.1-2001 does not document the #! behavior\nbut is otherwise compatible. " }, { "code": null, "e": 5380, "s": 5284, "text": "SUID and SGID processes can not be ptrace()d. Linux ignores the SUID and SGID bits on scripts.\n" }, { "code": null, "e": 5659, "s": 5380, "text": "The result of mounting a filesystem\nnosuid vary between Linux kernel versions:\nsome will refuse execution of SUID/SGID executables when this would\ngive the user powers she did not have already (and return EPERM),\nsome will just ignore the SUID/SGID bits and\nexec() successfully." }, { "code": null, "e": 5763, "s": 5659, "text": "\nA maximum line length of 127 characters is allowed for the first line in\na #! executable shell script." }, { "code": null, "e": 5981, "s": 5763, "text": "With Unix V6 the argument list of an\nexec() call was ended by 0,\nwhile the argument list of\nmain was ended by -1. Thus, this\nargument list was not directly usable in a further\nexec() call.\nSince Unix V7 both are NULL." }, { "code": null, "e": 5991, "s": 5981, "text": "chmod (2)" }, { "code": null, "e": 6001, "s": 5991, "text": "chmod (2)" }, { "code": null, "e": 6010, "s": 6001, "text": "fork (2)" }, { "code": null, "e": 6019, "s": 6010, "text": "fork (2)" }, { "code": null, "e": 6039, "s": 6019, "text": "path_resolution (2)" }, { "code": null, "e": 6059, "s": 6039, "text": "path_resolution (2)" }, { "code": null, "e": 6070, "s": 6059, "text": "ptrace (2)" }, { "code": null, "e": 6081, "s": 6070, "text": "ptrace (2)" }, { "code": null, "e": 6088, "s": 6081, "text": "ld (8)" }, { "code": null, "e": 6095, "s": 6088, "text": "ld (8)" }, { "code": null, "e": 6112, "s": 6095, "text": "\nAdvertisements\n" }, { "code": null, "e": 6147, "s": 6112, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 6175, "s": 6147, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6209, "s": 6175, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6226, "s": 6209, "text": " Frahaan Hussain" }, { "code": null, "e": 6259, "s": 6226, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 6270, "s": 6259, "text": " Pradeep D" }, { "code": null, "e": 6305, "s": 6270, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6321, "s": 6305, "text": " Musab Zayadneh" }, { "code": null, "e": 6354, "s": 6321, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 6366, "s": 6354, "text": " GUHARAJANM" }, { "code": null, "e": 6398, "s": 6366, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 6406, "s": 6398, "text": " Uplatz" }, { "code": null, "e": 6413, "s": 6406, "text": " Print" }, { "code": null, "e": 6424, "s": 6413, "text": " Add Notes" } ]
C library function - bsearch()
The C library function void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *)) function searches an array of nitems objects, the initial member of which is pointed to by base, for a member that matches the object pointed to, by key. The size of each member of the array is specified by size. The contents of the array should be in ascending sorted order according to the comparison function referenced by compar. Following is the declaration for bsearch() function. void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *)) key − This is the pointer to the object that serves as key for the search, type-casted as a void*. key − This is the pointer to the object that serves as key for the search, type-casted as a void*. base − This is the pointer to the first object of the array where the search is performed, type-casted as a void*. base − This is the pointer to the first object of the array where the search is performed, type-casted as a void*. nitems − This is the number of elements in the array pointed by base. nitems − This is the number of elements in the array pointed by base. size − This is the size in bytes of each element in the array. size − This is the size in bytes of each element in the array. compare − This is the function that compares two elements. compare − This is the function that compares two elements. This function returns a pointer to an entry in the array that matches the search key. If key is not found, a NULL pointer is returned. The following example shows the usage of bsearch() function. #include <stdio.h> #include <stdlib.h> int cmpfunc(const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int values[] = { 5, 20, 29, 32, 63 }; int main () { int *item; int key = 32; /* using bsearch() to find value 32 in the array */ item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc); if( item != NULL ) { printf("Found item = %d\n", *item); } else { printf("Item = %d could not be found\n", *item); } return(0); } Let us compile and run the above program that will produce the following result − Found item = 32 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2364, "s": 2007, "text": "The C library function void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *)) function searches an array of nitems objects, the initial member of which is pointed to by base, for a member that matches the object pointed to, by key. The size of each member of the array is specified by size." }, { "code": null, "e": 2485, "s": 2364, "text": "The contents of the array should be in ascending sorted order according to the comparison function referenced by compar." }, { "code": null, "e": 2538, "s": 2485, "text": "Following is the declaration for bsearch() function." }, { "code": null, "e": 2658, "s": 2538, "text": "void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *))" }, { "code": null, "e": 2757, "s": 2658, "text": "key − This is the pointer to the object that serves as key for the search, type-casted as a void*." }, { "code": null, "e": 2856, "s": 2757, "text": "key − This is the pointer to the object that serves as key for the search, type-casted as a void*." }, { "code": null, "e": 2972, "s": 2856, "text": "base − This is the pointer to the first object of the array where the search is performed, type-casted as a void*." }, { "code": null, "e": 3088, "s": 2972, "text": "base − This is the pointer to the first object of the array where the search is performed, type-casted as a void*." }, { "code": null, "e": 3158, "s": 3088, "text": "nitems − This is the number of elements in the array pointed by base." }, { "code": null, "e": 3228, "s": 3158, "text": "nitems − This is the number of elements in the array pointed by base." }, { "code": null, "e": 3291, "s": 3228, "text": "size − This is the size in bytes of each element in the array." }, { "code": null, "e": 3354, "s": 3291, "text": "size − This is the size in bytes of each element in the array." }, { "code": null, "e": 3413, "s": 3354, "text": "compare − This is the function that compares two elements." }, { "code": null, "e": 3472, "s": 3413, "text": "compare − This is the function that compares two elements." }, { "code": null, "e": 3607, "s": 3472, "text": "This function returns a pointer to an entry in the array that matches the search key. If key is not found, a NULL pointer is returned." }, { "code": null, "e": 3668, "s": 3607, "text": "The following example shows the usage of bsearch() function." }, { "code": null, "e": 4158, "s": 3668, "text": "#include <stdio.h>\n#include <stdlib.h>\n\n\nint cmpfunc(const void * a, const void * b) {\n return ( *(int*)a - *(int*)b );\n}\n\nint values[] = { 5, 20, 29, 32, 63 };\n\nint main () {\n int *item;\n int key = 32;\n\n /* using bsearch() to find value 32 in the array */\n item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);\n if( item != NULL ) {\n printf(\"Found item = %d\\n\", *item);\n } else {\n printf(\"Item = %d could not be found\\n\", *item);\n }\n \n return(0);\n}" }, { "code": null, "e": 4240, "s": 4158, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 4257, "s": 4240, "text": "Found item = 32\n" }, { "code": null, "e": 4290, "s": 4257, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4305, "s": 4290, "text": " Nishant Malik" }, { "code": null, "e": 4340, "s": 4305, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4355, "s": 4340, "text": " Nishant Malik" }, { "code": null, "e": 4390, "s": 4355, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4404, "s": 4390, "text": " Asif Hussain" }, { "code": null, "e": 4437, "s": 4404, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4455, "s": 4437, "text": " Richa Maheshwari" }, { "code": null, "e": 4490, "s": 4455, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4509, "s": 4490, "text": " Vandana Annavaram" }, { "code": null, "e": 4542, "s": 4509, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 4554, "s": 4542, "text": " Amit Diwan" }, { "code": null, "e": 4561, "s": 4554, "text": " Print" }, { "code": null, "e": 4572, "s": 4561, "text": " Add Notes" } ]
jsoup - Set HTML
Following example will showcase use of method to set, prepend or append html to a dom element after parsing an HTML String into a Document object. Document document = Jsoup.parse(html); Element div = document.getElementById("sampleDiv"); div.html("<p>This is a sample content.</p>"); div.prepend("<p>Initial Text</p>"); div.append("<p>End Text</p>"); Where document − document object represents the HTML DOM. document − document object represents the HTML DOM. Jsoup − main class to parse the given HTML String. Jsoup − main class to parse the given HTML String. html − HTML String. html − HTML String. div − Element object represent the html node element representing anchor tag. div − Element object represent the html node element representing anchor tag. div.html() − html(content) method replaces the element's outer html with the corresponding value. div.html() − html(content) method replaces the element's outer html with the corresponding value. div.prepend() − prepend(content) method adds the content before the outer html. div.prepend() − prepend(content) method adds the content before the outer html. div.append() − append(content) method adds the content after the outer html. div.append() − append(content) method adds the content after the outer html. Element object represent a dom elment and provides various method to set, prepend or append html to a dom element. Create the following java program using any editor of your choice in say C:/> jsoup. JsoupTester.java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; public class JsoupTester { public static void main(String[] args) { String html = "<html><head><title>Sample Title</title></head>" + "<body>" + "<div id='sampleDiv'><a id='googleA' href='www.google.com'>Google</a></div>" +"</body></html>"; Document document = Jsoup.parse(html); Element div = document.getElementById("sampleDiv"); System.out.println("Outer HTML Before Modification :\n" + div.outerHtml()); div.html("<p>This is a sample content.</p>"); System.out.println("Outer HTML After Modification :\n" + div.outerHtml()); div.prepend("<p>Initial Text</p>"); System.out.println("After Prepend :\n" + div.outerHtml()); div.append("<p>End Text</p>"); System.out.println("After Append :\n" + div.outerHtml()); } } Compile the class using javac compiler as follows: C:\jsoup>javac JsoupTester.java Now run the JsoupTester to see the result. C:\jsoup>java JsoupTester See the result. Outer HTML Before Modification : <div id="sampleDiv"> <a id="googleA" href="www.google.com">Google</a> </div> Outer HTML After Modification : <div id="sampleDiv"> <p>This is a sample content.</p> </div> After Prepend : <div id="sampleDiv"> <p>Initial Text</p> <p>This is a sample content.</p> </div> After Append : <div id="sampleDiv"> <p>Initial Text</p> <p>This is a sample content.</p> <p>End Text</p> </div> Outer HTML Before Modification : <span>Sample Content</span> Outer HTML After Modification : <span>Sample Content</span> Print Add Notes Bookmark this page
[ { "code": null, "e": 2177, "s": 2030, "text": "Following example will showcase use of method to set, prepend or append html to a dom element after parsing an HTML String into a Document object." }, { "code": null, "e": 2393, "s": 2177, "text": "Document document = Jsoup.parse(html);\nElement div = document.getElementById(\"sampleDiv\"); \ndiv.html(\"<p>This is a sample content.</p>\"); \ndiv.prepend(\"<p>Initial Text</p>\");\ndiv.append(\"<p>End Text</p>\"); \n" }, { "code": null, "e": 2399, "s": 2393, "text": "Where" }, { "code": null, "e": 2451, "s": 2399, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2503, "s": 2451, "text": "document − document object represents the HTML DOM." }, { "code": null, "e": 2554, "s": 2503, "text": "Jsoup − main class to parse the given HTML String." }, { "code": null, "e": 2605, "s": 2554, "text": "Jsoup − main class to parse the given HTML String." }, { "code": null, "e": 2625, "s": 2605, "text": "html − HTML String." }, { "code": null, "e": 2645, "s": 2625, "text": "html − HTML String." }, { "code": null, "e": 2723, "s": 2645, "text": "div − Element object represent the html node element representing anchor tag." }, { "code": null, "e": 2801, "s": 2723, "text": "div − Element object represent the html node element representing anchor tag." }, { "code": null, "e": 2899, "s": 2801, "text": "div.html() − html(content) method replaces the element's outer html with the corresponding value." }, { "code": null, "e": 2997, "s": 2899, "text": "div.html() − html(content) method replaces the element's outer html with the corresponding value." }, { "code": null, "e": 3077, "s": 2997, "text": "div.prepend() − prepend(content) method adds the content before the outer html." }, { "code": null, "e": 3157, "s": 3077, "text": "div.prepend() − prepend(content) method adds the content before the outer html." }, { "code": null, "e": 3234, "s": 3157, "text": "div.append() − append(content) method adds the content after the outer html." }, { "code": null, "e": 3311, "s": 3234, "text": "div.append() − append(content) method adds the content after the outer html." }, { "code": null, "e": 3426, "s": 3311, "text": "Element object represent a dom elment and provides various method to set, prepend or append html to a dom element." }, { "code": null, "e": 3511, "s": 3426, "text": "Create the following java program using any editor of your choice in say C:/> jsoup." }, { "code": null, "e": 3528, "s": 3511, "text": "JsoupTester.java" }, { "code": null, "e": 4446, "s": 3528, "text": "import org.jsoup.Jsoup;\nimport org.jsoup.nodes.Document;\nimport org.jsoup.nodes.Element;\n\npublic class JsoupTester {\n public static void main(String[] args) {\n \n String html = \"<html><head><title>Sample Title</title></head>\"\n + \"<body>\"\n + \"<div id='sampleDiv'><a id='googleA' href='www.google.com'>Google</a></div>\"\n +\"</body></html>\";\n Document document = Jsoup.parse(html);\n\n Element div = document.getElementById(\"sampleDiv\");\n System.out.println(\"Outer HTML Before Modification :\\n\" + div.outerHtml());\n div.html(\"<p>This is a sample content.</p>\");\n System.out.println(\"Outer HTML After Modification :\\n\" + div.outerHtml());\n div.prepend(\"<p>Initial Text</p>\");\n System.out.println(\"After Prepend :\\n\" + div.outerHtml());\n div.append(\"<p>End Text</p>\");\n System.out.println(\"After Append :\\n\" + div.outerHtml()); \n }\n}" }, { "code": null, "e": 4497, "s": 4446, "text": "Compile the class using javac compiler as follows:" }, { "code": null, "e": 4530, "s": 4497, "text": "C:\\jsoup>javac JsoupTester.java\n" }, { "code": null, "e": 4573, "s": 4530, "text": "Now run the JsoupTester to see the result." }, { "code": null, "e": 4600, "s": 4573, "text": "C:\\jsoup>java JsoupTester\n" }, { "code": null, "e": 4616, "s": 4600, "text": "See the result." }, { "code": null, "e": 5157, "s": 4616, "text": "Outer HTML Before Modification :\n<div id=\"sampleDiv\">\n <a id=\"googleA\" href=\"www.google.com\">Google</a>\n</div>\nOuter HTML After Modification :\n<div id=\"sampleDiv\">\n <p>This is a sample content.</p>\n</div>\nAfter Prepend :\n<div id=\"sampleDiv\">\n <p>Initial Text</p>\n <p>This is a sample content.</p>\n</div>\nAfter Append :\n<div id=\"sampleDiv\">\n <p>Initial Text</p>\n <p>This is a sample content.</p>\n <p>End Text</p>\n</div>\nOuter HTML Before Modification :\n<span>Sample Content</span>\nOuter HTML After Modification :\n<span>Sample Content</span>\n" }, { "code": null, "e": 5164, "s": 5157, "text": " Print" }, { "code": null, "e": 5175, "s": 5164, "text": " Add Notes" } ]
BigDecimal toBigInteger() Method in Java - GeeksforGeeks
09 Nov, 2021 The java.math.BigDecimal.toBigInteger() is an inbuilt method in java that converts this BigDecimal to a BigInteger. This conversion is analogous to the narrowing primitive conversion from double to long. Any fractional part of this BigDecimal will be discarded. This conversion can lose information about the precision of the BigDecimal value. Note: If an exception is thrown in the conversion inexact (in other words if a nonzero fractional part is discarded), use the toBigIntegerExact() method. Syntax: public BigInteger toBigInteger() Parameters: This method does not accepts any parameters.Return value: This method returns the value of BigDecimal object converted to a BigInteger. Examples: Input: (BigDecimal) 123.321 Output: (BigInteger) 123 Input: (BigDecimal) 123.001 Output: (BigInteger) 123 Below programs illustrate the working of the above-mentioned method: Program 1: Java // Program to demonstrate toBigInteger() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // Assigning the BigDecimal b BigDecimal b = new BigDecimal("123.321"); // Assigning the BigInteger value of BigDecimal b to BigInteger i BigInteger i = b.toBigInteger(); // Print i value System.out.println("BigInteger value of " + b + " is " + i); }} BigInteger value of 123.321 is 123 Program 2: Java // Program to demonstrate toBigInteger() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // Assigning the BigDecimal b BigDecimal b = new BigDecimal("123.001"); // Assigning the BigInteger value of BigDecimal b to BigInteger i BigInteger i = b.toBigInteger(); // Printing i value System.out.println("BigInteger value of " + b + " is " + i); }} BigInteger value of 123.001 is 123 Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#toBigInteger() prachisoda1234 Java-BigDecimal Java-Functions java-math Java-math-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java How to remove an element from ArrayList in Java? Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23582, "s": 23554, "text": "\n09 Nov, 2021" }, { "code": null, "e": 23926, "s": 23582, "text": "The java.math.BigDecimal.toBigInteger() is an inbuilt method in java that converts this BigDecimal to a BigInteger. This conversion is analogous to the narrowing primitive conversion from double to long. Any fractional part of this BigDecimal will be discarded. This conversion can lose information about the precision of the BigDecimal value." }, { "code": null, "e": 24080, "s": 23926, "text": "Note: If an exception is thrown in the conversion inexact (in other words if a nonzero fractional part is discarded), use the toBigIntegerExact() method." }, { "code": null, "e": 24089, "s": 24080, "text": "Syntax: " }, { "code": null, "e": 24122, "s": 24089, "text": "public BigInteger toBigInteger()" }, { "code": null, "e": 24270, "s": 24122, "text": "Parameters: This method does not accepts any parameters.Return value: This method returns the value of BigDecimal object converted to a BigInteger." }, { "code": null, "e": 24282, "s": 24270, "text": "Examples: " }, { "code": null, "e": 24389, "s": 24282, "text": "Input: (BigDecimal) 123.321\nOutput: (BigInteger) 123\n\nInput: (BigDecimal) 123.001\nOutput: (BigInteger) 123" }, { "code": null, "e": 24459, "s": 24389, "text": "Below programs illustrate the working of the above-mentioned method: " }, { "code": null, "e": 24472, "s": 24459, "text": "Program 1: " }, { "code": null, "e": 24477, "s": 24472, "text": "Java" }, { "code": "// Program to demonstrate toBigInteger() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // Assigning the BigDecimal b BigDecimal b = new BigDecimal(\"123.321\"); // Assigning the BigInteger value of BigDecimal b to BigInteger i BigInteger i = b.toBigInteger(); // Print i value System.out.println(\"BigInteger value of \" + b + \" is \" + i); }}", "e": 24928, "s": 24477, "text": null }, { "code": null, "e": 24963, "s": 24928, "text": "BigInteger value of 123.321 is 123" }, { "code": null, "e": 24977, "s": 24965, "text": "Program 2: " }, { "code": null, "e": 24982, "s": 24977, "text": "Java" }, { "code": "// Program to demonstrate toBigInteger() method of BigDecimal import java.math.*; public class GFG { public static void main(String[] args) { // Assigning the BigDecimal b BigDecimal b = new BigDecimal(\"123.001\"); // Assigning the BigInteger value of BigDecimal b to BigInteger i BigInteger i = b.toBigInteger(); // Printing i value System.out.println(\"BigInteger value of \" + b + \" is \" + i); }}", "e": 25436, "s": 24982, "text": null }, { "code": null, "e": 25471, "s": 25436, "text": "BigInteger value of 123.001 is 123" }, { "code": null, "e": 25568, "s": 25473, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#toBigInteger() " }, { "code": null, "e": 25583, "s": 25568, "text": "prachisoda1234" }, { "code": null, "e": 25599, "s": 25583, "text": "Java-BigDecimal" }, { "code": null, "e": 25614, "s": 25599, "text": "Java-Functions" }, { "code": null, "e": 25624, "s": 25614, "text": "java-math" }, { "code": null, "e": 25642, "s": 25624, "text": "Java-math-package" }, { "code": null, "e": 25647, "s": 25642, "text": "Java" }, { "code": null, "e": 25652, "s": 25647, "text": "Java" }, { "code": null, "e": 25750, "s": 25652, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25759, "s": 25750, "text": "Comments" }, { "code": null, "e": 25772, "s": 25759, "text": "Old Comments" }, { "code": null, "e": 25802, "s": 25772, "text": "Functional Interfaces in Java" }, { "code": null, "e": 25817, "s": 25802, "text": "Stream In Java" }, { "code": null, "e": 25838, "s": 25817, "text": "Constructors in Java" }, { "code": null, "e": 25884, "s": 25838, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 25903, "s": 25884, "text": "Exceptions in Java" }, { "code": null, "e": 25920, "s": 25903, "text": "Generics in Java" }, { "code": null, "e": 25963, "s": 25920, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 25979, "s": 25963, "text": "Strings in Java" }, { "code": null, "e": 26028, "s": 25979, "text": "How to remove an element from ArrayList in Java?" } ]
How to Zoom with Axes3D in Matplotlib?
To zoom with Axes3D, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create a new figure or activate an existing figure using figure() method. Get 3D axes object using Axes3D(fig) method. Plot x, y and z data points using scatter() method. To display the figure, use show() method. from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig = plt.figure() ax = Axes3D(fig) x = [2, 4, 6, 3, 1] y = [1, 6, 8, 1, 3] z = [3, 4, 10, 3, 1] ax.scatter3D(x, y, z, c=z, alpha=1, marker='d', s=150) plt.show()
[ { "code": null, "e": 1117, "s": 1062, "text": "To zoom with Axes3D, we can take the following steps −" }, { "code": null, "e": 1193, "s": 1117, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1267, "s": 1193, "text": "Create a new figure or activate an existing figure using figure() method." }, { "code": null, "e": 1312, "s": 1267, "text": "Get 3D axes object using Axes3D(fig) method." }, { "code": null, "e": 1364, "s": 1312, "text": "Plot x, y and z data points using scatter() method." }, { "code": null, "e": 1406, "s": 1364, "text": "To display the figure, use show() method." }, { "code": null, "e": 1737, "s": 1406, "text": "from mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig = plt.figure()\nax = Axes3D(fig)\nx = [2, 4, 6, 3, 1]\ny = [1, 6, 8, 1, 3]\nz = [3, 4, 10, 3, 1]\n\nax.scatter3D(x, y, z, c=z, alpha=1, marker='d', s=150)\nplt.show()\n" } ]
C library function - malloc()
The C library function void *malloc(size_t size) allocates the requested memory and returns a pointer to it. Following is the declaration for malloc() function. void *malloc(size_t size) size − This is the size of the memory block, in bytes. size − This is the size of the memory block, in bytes. This function returns a pointer to the allocated memory, or NULL if the request fails. The following example shows the usage of malloc() function. #include <stdio.h> #include <stdlib.h> int main () { char *str; /* Initial memory allocation */ str = (char *) malloc(15); strcpy(str, "tutorialspoint"); printf("String = %s, Address = %u\n", str, str); /* Reallocating memory */ str = (char *) realloc(str, 25); strcat(str, ".com"); printf("String = %s, Address = %u\n", str, str); free(str); return(0); } Let us compile and run the above program that will produce the following result − String = tutorialspoint, Address = 355090448 String = tutorialspoint.com, Address = 355090448 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2116, "s": 2007, "text": "The C library function void *malloc(size_t size) allocates the requested memory and returns a pointer to it." }, { "code": null, "e": 2168, "s": 2116, "text": "Following is the declaration for malloc() function." }, { "code": null, "e": 2194, "s": 2168, "text": "void *malloc(size_t size)" }, { "code": null, "e": 2249, "s": 2194, "text": "size − This is the size of the memory block, in bytes." }, { "code": null, "e": 2304, "s": 2249, "text": "size − This is the size of the memory block, in bytes." }, { "code": null, "e": 2391, "s": 2304, "text": "This function returns a pointer to the allocated memory, or NULL if the request fails." }, { "code": null, "e": 2451, "s": 2391, "text": "The following example shows the usage of malloc() function." }, { "code": null, "e": 2850, "s": 2451, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main () {\n char *str;\n\n /* Initial memory allocation */\n str = (char *) malloc(15);\n strcpy(str, \"tutorialspoint\");\n printf(\"String = %s, Address = %u\\n\", str, str);\n\n /* Reallocating memory */\n str = (char *) realloc(str, 25);\n strcat(str, \".com\");\n printf(\"String = %s, Address = %u\\n\", str, str);\n\n free(str);\n \n return(0);\n}" }, { "code": null, "e": 2932, "s": 2850, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3027, "s": 2932, "text": "String = tutorialspoint, Address = 355090448\nString = tutorialspoint.com, Address = 355090448\n" }, { "code": null, "e": 3060, "s": 3027, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3075, "s": 3060, "text": " Nishant Malik" }, { "code": null, "e": 3110, "s": 3075, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3125, "s": 3110, "text": " Nishant Malik" }, { "code": null, "e": 3160, "s": 3125, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3174, "s": 3160, "text": " Asif Hussain" }, { "code": null, "e": 3207, "s": 3174, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3225, "s": 3207, "text": " Richa Maheshwari" }, { "code": null, "e": 3260, "s": 3225, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3279, "s": 3260, "text": " Vandana Annavaram" }, { "code": null, "e": 3312, "s": 3279, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3324, "s": 3312, "text": " Amit Diwan" }, { "code": null, "e": 3331, "s": 3324, "text": " Print" }, { "code": null, "e": 3342, "s": 3331, "text": " Add Notes" } ]
How to Add Fingerprint Authentication in Your Android App? - GeeksforGeeks
16 Feb, 2021 Now a day, we have seen that most of our Android phone contains fingerprint authentication. And we can implement that fingerprint authentication in our app so to secure our app as much as we can. In this article, we will take a look at the implementation of fingerprint authentication. We will be building a simple application in which we will be displaying an image of a fingerprint and a login button. After clicking on the login button we will apply our fingerprint. And if that same fingerprint is added into the Security setting then we will get login success. A sample video 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 Java 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 Java as the programming language. Step 2: Add dependency and JitPack Repository Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. implementation ‘androidx.biometric:biometric:1.0.1’ Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section. allprojects { repositories { ... maven { url “https://jitpack.io” } } } After adding this dependency sync your project and now we will move towards its implementation. Step 3: Working with the AndroidManifst.xml file Add the following line inside your AndroidManifst.xml file. <uses-permission android:name=”android.permission.USE_BIOMETRIC”/> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GFG | First App" android:textColor="#fafafa" android:textSize="30dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Use your fingerprint to login" android:textColor="#fafafa" android:textSize="18sp" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginVertical="20dp" android:src="@drawable/ic_fingerprint_black_24dp" /> <TextView android:id="@+id/msgtext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:textSize="18sp" /> <Button android:id="@+id/login" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginVertical="20dp" android:background="#fafafa" android:text="Login" /> </LinearLayout> Create a new Drawable Resource File and name the file as the background. Below is the code for the background.xml file. XML <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:angle="-90" android:endColor="#fff" android:startColor="#29DA2E" /></shape> Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.biometric.BiometricManager;import androidx.biometric.BiometricPrompt;import androidx.core.content.ContextCompat; import java.util.concurrent.Executor; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialising msgtext and loginbutton TextView msgtex = findViewById(R.id.msgtext); final Button loginbutton = findViewById(R.id.login); // creating a variable for our BiometricManager // and lets check if our user can use biometric sensor or not BiometricManager biometricManager = androidx.biometric.BiometricManager.from(this); switch (biometricManager.canAuthenticate()) { // this means we can use biometric sensor case BiometricManager.BIOMETRIC_SUCCESS: msgtex.setText("You can use the fingerprint sensor to login"); msgtex.setTextColor(Color.parseColor("#fafafa")); break; // this means that the device doesn't have fingerprint sensor case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE: msgtex.setText("This device doesnot have a fingerprint sensor"); loginbutton.setVisibility(View.GONE); break; // this means that biometric sensor is not available case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE: msgtex.setText("The biometric sensor is currently unavailable"); loginbutton.setVisibility(View.GONE); break; // this means that the device doesn't contain your fingerprint case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED: msgtex.setText("Your device doesn't have fingerprint saved,please check your security settings"); loginbutton.setVisibility(View.GONE); break; } // creating a variable for our Executor Executor executor = ContextCompat.getMainExecutor(this); // this will give us result of AUTHENTICATION final BiometricPrompt biometricPrompt = new BiometricPrompt(MainActivity.this, executor, new BiometricPrompt.AuthenticationCallback() { @Override public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) { super.onAuthenticationError(errorCode, errString); } // THIS METHOD IS CALLED WHEN AUTHENTICATION IS SUCCESS @Override public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) { super.onAuthenticationSucceeded(result); Toast.makeText(getApplicationContext(), "Login Success", Toast.LENGTH_SHORT).show(); loginbutton.setText("Login Successful"); } @Override public void onAuthenticationFailed() { super.onAuthenticationFailed(); } }); // creating a variable for our promptInfo // BIOMETRIC DIALOG final BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder().setTitle("GFG") .setDescription("Use your fingerprint to login ").setNegativeButtonText("Cancel").build(); loginbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { biometricPrompt.authenticate(promptInfo); } }); }} GitHub link: https://github.com/Anni1123/FingerprintAuthentication android Picked Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 24749, "s": 24721, "text": "\n16 Feb, 2021" }, { "code": null, "e": 25035, "s": 24749, "text": "Now a day, we have seen that most of our Android phone contains fingerprint authentication. And we can implement that fingerprint authentication in our app so to secure our app as much as we can. In this article, we will take a look at the implementation of fingerprint authentication." }, { "code": null, "e": 25482, "s": 25035, "text": "We will be building a simple application in which we will be displaying an image of a fingerprint and a login button. After clicking on the login button we will apply our fingerprint. And if that same fingerprint is added into the Security setting then we will get login success. A sample video 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 Java language. " }, { "code": null, "e": 25511, "s": 25482, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25673, "s": 25511, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 25719, "s": 25673, "text": "Step 2: Add dependency and JitPack Repository" }, { "code": null, "e": 25838, "s": 25719, "text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. " }, { "code": null, "e": 25890, "s": 25838, "text": "implementation ‘androidx.biometric:biometric:1.0.1’" }, { "code": null, "e": 26032, "s": 25890, "text": "Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section." }, { "code": null, "e": 26046, "s": 26032, "text": "allprojects {" }, { "code": null, "e": 26062, "s": 26046, "text": " repositories {" }, { "code": null, "e": 26069, "s": 26062, "text": " ..." }, { "code": null, "e": 26107, "s": 26069, "text": " maven { url “https://jitpack.io” }" }, { "code": null, "e": 26114, "s": 26107, "text": " }" }, { "code": null, "e": 26116, "s": 26114, "text": "}" }, { "code": null, "e": 26214, "s": 26116, "text": "After adding this dependency sync your project and now we will move towards its implementation. " }, { "code": null, "e": 26263, "s": 26214, "text": "Step 3: Working with the AndroidManifst.xml file" }, { "code": null, "e": 26323, "s": 26263, "text": "Add the following line inside your AndroidManifst.xml file." }, { "code": null, "e": 26390, "s": 26323, "text": "<uses-permission android:name=”android.permission.USE_BIOMETRIC”/>" }, { "code": null, "e": 26438, "s": 26390, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 26581, "s": 26438, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 26585, "s": 26581, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"@drawable/background\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GFG | First App\" android:textColor=\"#fafafa\" android:textSize=\"30dp\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Use your fingerprint to login\" android:textColor=\"#fafafa\" android:textSize=\"18sp\" /> <ImageView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginVertical=\"20dp\" android:src=\"@drawable/ic_fingerprint_black_24dp\" /> <TextView android:id=\"@+id/msgtext\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"\" android:textSize=\"18sp\" /> <Button android:id=\"@+id/login\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginVertical=\"20dp\" android:background=\"#fafafa\" android:text=\"Login\" /> </LinearLayout>", "e": 28060, "s": 26585, "text": null }, { "code": null, "e": 28180, "s": 28060, "text": "Create a new Drawable Resource File and name the file as the background. Below is the code for the background.xml file." }, { "code": null, "e": 28184, "s": 28180, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><shape xmlns:android=\"http://schemas.android.com/apk/res/android\"> <gradient android:angle=\"-90\" android:endColor=\"#fff\" android:startColor=\"#29DA2E\" /></shape>", "e": 28407, "s": 28184, "text": null }, { "code": null, "e": 28455, "s": 28407, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 28645, "s": 28455, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 28650, "s": 28645, "text": "Java" }, { "code": "import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.biometric.BiometricManager;import androidx.biometric.BiometricPrompt;import androidx.core.content.ContextCompat; import java.util.concurrent.Executor; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialising msgtext and loginbutton TextView msgtex = findViewById(R.id.msgtext); final Button loginbutton = findViewById(R.id.login); // creating a variable for our BiometricManager // and lets check if our user can use biometric sensor or not BiometricManager biometricManager = androidx.biometric.BiometricManager.from(this); switch (biometricManager.canAuthenticate()) { // this means we can use biometric sensor case BiometricManager.BIOMETRIC_SUCCESS: msgtex.setText(\"You can use the fingerprint sensor to login\"); msgtex.setTextColor(Color.parseColor(\"#fafafa\")); break; // this means that the device doesn't have fingerprint sensor case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE: msgtex.setText(\"This device doesnot have a fingerprint sensor\"); loginbutton.setVisibility(View.GONE); break; // this means that biometric sensor is not available case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE: msgtex.setText(\"The biometric sensor is currently unavailable\"); loginbutton.setVisibility(View.GONE); break; // this means that the device doesn't contain your fingerprint case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED: msgtex.setText(\"Your device doesn't have fingerprint saved,please check your security settings\"); loginbutton.setVisibility(View.GONE); break; } // creating a variable for our Executor Executor executor = ContextCompat.getMainExecutor(this); // this will give us result of AUTHENTICATION final BiometricPrompt biometricPrompt = new BiometricPrompt(MainActivity.this, executor, new BiometricPrompt.AuthenticationCallback() { @Override public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) { super.onAuthenticationError(errorCode, errString); } // THIS METHOD IS CALLED WHEN AUTHENTICATION IS SUCCESS @Override public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) { super.onAuthenticationSucceeded(result); Toast.makeText(getApplicationContext(), \"Login Success\", Toast.LENGTH_SHORT).show(); loginbutton.setText(\"Login Successful\"); } @Override public void onAuthenticationFailed() { super.onAuthenticationFailed(); } }); // creating a variable for our promptInfo // BIOMETRIC DIALOG final BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder().setTitle(\"GFG\") .setDescription(\"Use your fingerprint to login \").setNegativeButtonText(\"Cancel\").build(); loginbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { biometricPrompt.authenticate(promptInfo); } }); }}", "e": 32524, "s": 28650, "text": null }, { "code": null, "e": 32591, "s": 32524, "text": "GitHub link: https://github.com/Anni1123/FingerprintAuthentication" }, { "code": null, "e": 32599, "s": 32591, "text": "android" }, { "code": null, "e": 32606, "s": 32599, "text": "Picked" }, { "code": null, "e": 32630, "s": 32606, "text": "Technical Scripter 2020" }, { "code": null, "e": 32638, "s": 32630, "text": "Android" }, { "code": null, "e": 32643, "s": 32638, "text": "Java" }, { "code": null, "e": 32662, "s": 32643, "text": "Technical Scripter" }, { "code": null, "e": 32667, "s": 32662, "text": "Java" }, { "code": null, "e": 32675, "s": 32667, "text": "Android" }, { "code": null, "e": 32773, "s": 32675, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32782, "s": 32773, "text": "Comments" }, { "code": null, "e": 32795, "s": 32782, "text": "Old Comments" }, { "code": null, "e": 32834, "s": 32795, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32884, "s": 32834, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 32935, "s": 32884, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 32973, "s": 32935, "text": "Android Listview in Java with Example" }, { "code": null, "e": 33015, "s": 32973, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 33030, "s": 33015, "text": "Arrays in Java" }, { "code": null, "e": 33074, "s": 33030, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33096, "s": 33074, "text": "For-each loop in Java" }, { "code": null, "e": 33121, "s": 33096, "text": "Reverse a string in Java" } ]
Automatic License Plate Detection & Recognition using deep learning | by Achraf KHAZRI | Towards Data Science
Introduction The massive integration of information technologies, under different aspects of the modern world, has led to the treatment of vehicles as conceptual resources in information systems. Since an autonomous information system has no meaning without any data, there is a need to reform vehicle information between reality and the information system.This can be achieved by human agents or by special intelligent equipment that will allow identification of vehicles by their registration plates in real environments. Among intelligent equipment, mention is made of the system of detection and recognition of the number plates of vehicles.The system of vehicle number plate detection and recognition is used to detect the plates then make the recognition of the plate that is to extract the text from an image and all that thanks to the calculation modules that use location algorithms, segmentation plate and character recognition.The detection and reading of license plates is a kind of intelligent system and it is considerable because of the potential applications in several sectors which are quoted: - Command force: This system is used for the detection of stolen and searched vehicles. The detected plates are compared to those of the reported vehicles. - Parking management: The management of car entrances and exits. Road safety: This system is used to detect license plates exceeding a certain speed, coupling the plate reading system with road radar, crossing wildfires ... Our project will be divised into 3 steps : Step1 : Licence plate detection In order to detect licence we will use Yolo ( You Only Look One ) deep learning object detection architecture based on convolution neural networks. This architecture was introduced by Joseph Redmon , Ali Farhadi, Ross Girshick and Santosh Divvala first version in 2015 and later version 2 and 3. Yolo v1 : Paper link. Yolo v2 : Paper link. Yolo v3 : Paper link. Yolo is a single network trained end to end to perform a regression task predicting both object bounding box and object class. This network is extremely fast, it processes images in real-time at 45 frames per second. A smaller version of the network, Fast YOLO, processes an astounding 155 frames per second. Implementing YOLO V3: First, we prepared a dataset composed of 700 images of cars that contains Tunisian licence plate, for each image, we make an xml file ( Changed after that to text file that contains coordinates compatible with Darknet config file input. Darknet : project used to retrain YOLO pretrained models) using a desktop application called LabelImg. # First download Darknet project$ git clone https://github.com/pjreddie/darknet.git# in "darknet/Makefile" put affect 1 to OpenCV, CUDNN and GPU if you # want to train with you GPU then time thos two commands$ cd darknet$ make# Load convert.py to change labels (xml files) into the appropriate # format that darknet understand and past it under darknet/ https://github.com/GuiltyNeuron/ANPR# Unzip the dataset$ unzip dataset.zip# Create two folders, one for the images and the other for labels$ mkdir darknet/images$ mkdir darknet/labels# Convert labels format and create files with location of images# for the test and the training$ python convert.py# Create a folder under darknet/ that will contain your data$ mkdir darknet/custom# Move files train.txt and test.txt that contains data path to# custom folder$ mv train.txt custom/$ mv test.txt custom/# Create file to put licence plate class name "LP"$ touch darknet/custom/classes.names$ echo LP > classes.names# Create Backup folder to save weights$ mkdir custom/weights# Create a file contains information about data and cfg # files locations$ touch darknet/custom/darknet.data# in darknet/custom/darknet.data file paste those informationsclasses = 1train = custom/train.txtvalid = custom/test.txtnames = custom/classes.namesbackup = custom/weights/# Copy and paste yolo config file in "darknet/custom"$ cp darknet/cfg/yolov3.cfg darknet/custom# Open yolov3.cfg and change :# " filters=(classes + 5)*3" just the ones before "Yolo"# in our case classes=1, so filters=18# change classes=... to classes=1# Download pretrained model$ wget https://pjreddie.com/media/files/darknet53.conv.74 -O ~/darknet/darknet53.conv.74# Let's train our model !!!!!!!!!!!!!!!!!!!!!$ ./darknet detector train custom/darknet.data custom/yolov3.cfg darknet53.conv.74 After finishing the training, to detectect u liscence plate from an image, choose the latest model from darknet/custom/weights , and put its path or name in file object_detection_yolo.py, also we will use yolov3.cfg file, just in this file put # before training so we desable training then run : python object-detection_yolo.py --image= image.jpg and this what we have as a result : Step2 : Licence plate segmentation Now we have to segment our plate number. The input is the image of the plate, we will have to be able to extract the unicharacter images. The result of this step, being used as input to the recognition phase, is of great importance. In a system of automatic reading of number plates. Segmentation is one of the most important processes for the automatic identification of license plates, because any other step is based on it. If the segmentation fails, recognition phase will not be correct.To ensure proper segmentation, preliminary processing will have to be performed. The histogram of pixel projection consists of finding the upper and lower limits, left and right of each character. We perform a horizontal projection to find the top and bottom positions of the characters. The value of a group of histograms is the sum of the white pixels along a particular line in the horizontal direction. When all the values ​​along all the lines in the horizontal direction are calculated, the horizontal projection histogram is obtained. The average value of the histogram is then used as a threshold to determine the upper and lower limits. The central area whose segment of the histogram is greater than the threshold is recorded as the area delimited by the upper and lower limits. Then in the same way we calculate the vertical projection histogram but by changing the rows by the columns of the image to have the two limits of each character (left and right). Another approach to extract digits from licence plate is to use open/close morphologye to make some sorte of connected region then use connected component algorith to extract connected regions. Step3 : Licence plate recognition The recognition phase is the last step in the development of the automatic license plate reader system. Thus, it closes all the processes passing by the acquisition of the image, followed by the location of the plate until the segmentation. The recognition must make from the images characters obtained at the end of the segmentation phase. The learning model that will be used for this recognition must be able to read an image and to render the corresponding character. In order to make the most of the data available for learning, we cut each character indivudually by resizing it in a square after applying the same image processing steps used before segmentation of the license plate. As a result, we obtained a set of of data composed of 11 classes and for each class we have 30–40 images of 28X28 pixel dimesion PNG formats; numbers from 0 to 9 and the word in Arabic (Tunisia). Then, we made some researches based on scientific articles that compare the multilayer perceptron (MLP) and the classifier K nearest neighbors (KNN). And as a result we have found that: performance is increased if the number of hidden layer neurons is also increased when using the MLP classifier and if the nearest neighbor number is also increased when using the KNN. the ability to adjust the performance of the k-NN classifier is very limited here. But an adjustable number of hidden layers and adjustable MLP connection weights provides a greater opportunity to refine the decision regions. So as a result, we will choose the multilayer perceptron for this phase. Github project repo link
[ { "code": null, "e": 185, "s": 172, "text": "Introduction" }, { "code": null, "e": 1284, "s": 185, "text": "The massive integration of information technologies, under different aspects of the modern world, has led to the treatment of vehicles as conceptual resources in information systems. Since an autonomous information system has no meaning without any data, there is a need to reform vehicle information between reality and the information system.This can be achieved by human agents or by special intelligent equipment that will allow identification of vehicles by their registration plates in real environments. Among intelligent equipment, mention is made of the system of detection and recognition of the number plates of vehicles.The system of vehicle number plate detection and recognition is used to detect the plates then make the recognition of the plate that is to extract the text from an image and all that thanks to the calculation modules that use location algorithms, segmentation plate and character recognition.The detection and reading of license plates is a kind of intelligent system and it is considerable because of the potential applications in several sectors which are quoted:" }, { "code": null, "e": 1440, "s": 1284, "text": "- Command force: This system is used for the detection of stolen and searched vehicles. The detected plates are compared to those of the reported vehicles." }, { "code": null, "e": 1505, "s": 1440, "text": "- Parking management: The management of car entrances and exits." }, { "code": null, "e": 1664, "s": 1505, "text": "Road safety: This system is used to detect license plates exceeding a certain speed, coupling the plate reading system with road radar, crossing wildfires ..." }, { "code": null, "e": 1707, "s": 1664, "text": "Our project will be divised into 3 steps :" }, { "code": null, "e": 1739, "s": 1707, "text": "Step1 : Licence plate detection" }, { "code": null, "e": 1887, "s": 1739, "text": "In order to detect licence we will use Yolo ( You Only Look One ) deep learning object detection architecture based on convolution neural networks." }, { "code": null, "e": 2035, "s": 1887, "text": "This architecture was introduced by Joseph Redmon , Ali Farhadi, Ross Girshick and Santosh Divvala first version in 2015 and later version 2 and 3." }, { "code": null, "e": 2057, "s": 2035, "text": "Yolo v1 : Paper link." }, { "code": null, "e": 2079, "s": 2057, "text": "Yolo v2 : Paper link." }, { "code": null, "e": 2101, "s": 2079, "text": "Yolo v3 : Paper link." }, { "code": null, "e": 2228, "s": 2101, "text": "Yolo is a single network trained end to end to perform a regression task predicting both object bounding box and object class." }, { "code": null, "e": 2410, "s": 2228, "text": "This network is extremely fast, it processes images in real-time at 45 frames per second. A smaller version of the network, Fast YOLO, processes an astounding 155 frames per second." }, { "code": null, "e": 2432, "s": 2410, "text": "Implementing YOLO V3:" }, { "code": null, "e": 2772, "s": 2432, "text": "First, we prepared a dataset composed of 700 images of cars that contains Tunisian licence plate, for each image, we make an xml file ( Changed after that to text file that contains coordinates compatible with Darknet config file input. Darknet : project used to retrain YOLO pretrained models) using a desktop application called LabelImg." }, { "code": null, "e": 4575, "s": 2772, "text": "# First download Darknet project$ git clone https://github.com/pjreddie/darknet.git# in \"darknet/Makefile\" put affect 1 to OpenCV, CUDNN and GPU if you # want to train with you GPU then time thos two commands$ cd darknet$ make# Load convert.py to change labels (xml files) into the appropriate # format that darknet understand and past it under darknet/ https://github.com/GuiltyNeuron/ANPR# Unzip the dataset$ unzip dataset.zip# Create two folders, one for the images and the other for labels$ mkdir darknet/images$ mkdir darknet/labels# Convert labels format and create files with location of images# for the test and the training$ python convert.py# Create a folder under darknet/ that will contain your data$ mkdir darknet/custom# Move files train.txt and test.txt that contains data path to# custom folder$ mv train.txt custom/$ mv test.txt custom/# Create file to put licence plate class name \"LP\"$ touch darknet/custom/classes.names$ echo LP > classes.names# Create Backup folder to save weights$ mkdir custom/weights# Create a file contains information about data and cfg # files locations$ touch darknet/custom/darknet.data# in darknet/custom/darknet.data file paste those informationsclasses = 1train = custom/train.txtvalid = custom/test.txtnames = custom/classes.namesbackup = custom/weights/# Copy and paste yolo config file in \"darknet/custom\"$ cp darknet/cfg/yolov3.cfg darknet/custom# Open yolov3.cfg and change :# \" filters=(classes + 5)*3\" just the ones before \"Yolo\"# in our case classes=1, so filters=18# change classes=... to classes=1# Download pretrained model$ wget https://pjreddie.com/media/files/darknet53.conv.74 -O ~/darknet/darknet53.conv.74# Let's train our model !!!!!!!!!!!!!!!!!!!!!$ ./darknet detector train custom/darknet.data custom/yolov3.cfg darknet53.conv.74" }, { "code": null, "e": 4871, "s": 4575, "text": "After finishing the training, to detectect u liscence plate from an image, choose the latest model from darknet/custom/weights , and put its path or name in file object_detection_yolo.py, also we will use yolov3.cfg file, just in this file put # before training so we desable training then run :" }, { "code": null, "e": 4922, "s": 4871, "text": "python object-detection_yolo.py --image= image.jpg" }, { "code": null, "e": 4958, "s": 4922, "text": "and this what we have as a result :" }, { "code": null, "e": 4993, "s": 4958, "text": "Step2 : Licence plate segmentation" }, { "code": null, "e": 5277, "s": 4993, "text": "Now we have to segment our plate number. The input is the image of the plate, we will have to be able to extract the unicharacter images. The result of this step, being used as input to the recognition phase, is of great importance. In a system of automatic reading of number plates." }, { "code": null, "e": 5566, "s": 5277, "text": "Segmentation is one of the most important processes for the automatic identification of license plates, because any other step is based on it. If the segmentation fails, recognition phase will not be correct.To ensure proper segmentation, preliminary processing will have to be performed." }, { "code": null, "e": 6454, "s": 5566, "text": "The histogram of pixel projection consists of finding the upper and lower limits, left and right of each character. We perform a horizontal projection to find the top and bottom positions of the characters. The value of a group of histograms is the sum of the white pixels along a particular line in the horizontal direction. When all the values ​​along all the lines in the horizontal direction are calculated, the horizontal projection histogram is obtained. The average value of the histogram is then used as a threshold to determine the upper and lower limits. The central area whose segment of the histogram is greater than the threshold is recorded as the area delimited by the upper and lower limits. Then in the same way we calculate the vertical projection histogram but by changing the rows by the columns of the image to have the two limits of each character (left and right)." }, { "code": null, "e": 6648, "s": 6454, "text": "Another approach to extract digits from licence plate is to use open/close morphologye to make some sorte of connected region then use connected component algorith to extract connected regions." }, { "code": null, "e": 6682, "s": 6648, "text": "Step3 : Licence plate recognition" }, { "code": null, "e": 7154, "s": 6682, "text": "The recognition phase is the last step in the development of the automatic license plate reader system. Thus, it closes all the processes passing by the acquisition of the image, followed by the location of the plate until the segmentation. The recognition must make from the images characters obtained at the end of the segmentation phase. The learning model that will be used for this recognition must be able to read an image and to render the corresponding character." }, { "code": null, "e": 7568, "s": 7154, "text": "In order to make the most of the data available for learning, we cut each character indivudually by resizing it in a square after applying the same image processing steps used before segmentation of the license plate. As a result, we obtained a set of of data composed of 11 classes and for each class we have 30–40 images of 28X28 pixel dimesion PNG formats; numbers from 0 to 9 and the word in Arabic (Tunisia)." }, { "code": null, "e": 8237, "s": 7568, "text": "Then, we made some researches based on scientific articles that compare the multilayer perceptron (MLP) and the classifier K nearest neighbors (KNN). And as a result we have found that: performance is increased if the number of hidden layer neurons is also increased when using the MLP classifier and if the nearest neighbor number is also increased when using the KNN. the ability to adjust the performance of the k-NN classifier is very limited here. But an adjustable number of hidden layers and adjustable MLP connection weights provides a greater opportunity to refine the decision regions. So as a result, we will choose the multilayer perceptron for this phase." } ]
How to get the first day of the current month in MySQL?
With the help of following MySQL query, we can get the first day of the current month − mysql> SELECT DATE_SUB(LAST_DAY(NOW()),INTERVAL DAY(LAST_DAY(NOW()))- 1 DAY) AS 'FIRST DAY OF CURRENT MONTH'; +----------------------------+ | FIRST DAY OF CURRENT MONTH | +----------------------------+ | 2017-10-01 | +----------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1150, "s": 1062, "text": "With the help of following MySQL query, we can get the first day of the current month −" }, { "code": null, "e": 1439, "s": 1150, "text": "mysql> SELECT DATE_SUB(LAST_DAY(NOW()),INTERVAL DAY(LAST_DAY(NOW()))-\n1 DAY) AS 'FIRST DAY OF CURRENT MONTH';\n+----------------------------+\n| FIRST DAY OF CURRENT MONTH |\n+----------------------------+\n| 2017-10-01 |\n+----------------------------+\n1 row in set (0.00 sec)" } ]
Sed Command in Linux/Unix with examples - GeeksforGeeks
21 Dec, 2021 SED command in UNIX stands for stream editor and it can perform lots of functions on file like searching, find and replace, insertion or deletion. Though most common use of SED command in UNIX is for substitution or for find and replace. By using SED you can edit files even without opening them, which is much quicker way to find and replace something in file, than first opening that file in VI Editor and then changing it. SED is a powerful text stream editor. Can do insertion, deletion, search and replace(substitution). SED command in unix supports regular expression which allows it perform complex pattern matching. Syntax: sed OPTIONS... [SCRIPT] [INPUTFILE...] Example: Consider the below text file as an input. $cat > geekfile.txt unix is great os. unix is opensource. unix is free os. learn operating system. unix linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Sample Commands Replacing or substituting string : Sed command is mostly used to replace the text in a file. The below simple sed command replaces the word “unix” with “linux” in the file. $sed 's/unix/linux/' geekfile.txt Output : linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Here the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string. By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third...occurrence in the line. Replacing the nth occurrence of a pattern in a line : Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word “unix” with “linux” in a line. $sed 's/unix/linux/2' geekfile.txt Output: unix is great os. linux is opensource. unix is free os. learn operating system. unix linux which one you choose. unix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful. Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line. $sed 's/unix/linux/g' geekfile.txt Output : linux is great os. linux is opensource. linux is free os. learn operating system. linux linux which one you choose. linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful. Replacing from nth occurrence to all occurrences in a line : Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces the third, fourth, fifth... “unix” word with “linux” word in a line. $sed 's/unix/linux/3g' geekfile.txt Output: unix is great os. unix is opensource. linux is free os. learn operating system. unix linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful. Parenthesize first character of each word : This sed example prints the first character of every word in parenthesis. $ echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g' Output: (W)elcome (T)o (T)he (G)eek (S)tuff Replacing string on a specific line number : You can restrict the sed command to replace the string on a specific line number. An example is $sed '3 s/unix/linux/' geekfile.txt Output: unix is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. The above sed command replaces the string only on the third line. Duplicating the replaced line with /p flag : The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once. $sed 's/unix/linux/p' geekfile.txt Output: linux is great os. unix is opensource. unix is free os. linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Printing only the replaced lines : Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time. $sed -n 's/unix/linux/p' geekfile.txt Output: linux is great os. unix is opensource. unix is free os. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. If you use -n alone without /p, then the sed does not print anything. Replacing string on a range of lines : You can specify a range of line numbers to the sed command for replacing a string. $sed '1,3 s/unix/linux/' geekfile.txt Output: linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Here the sed command replaces the lines with range from 1 to 3. Another example is $sed '2,$ s/unix/linux/' geekfile.txt Output: unix is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful Here $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file. Deleting lines from a particular file : SED command can also be used for deleting lines from a particular file. SED command is used for performing deletion operation without even opening the file Examples: 1. To Delete a particular line say n in this example Syntax: $ sed 'nd' filename.txt Example: $ sed '5d' filename.txt 2. To Delete a last line Syntax: $ sed '$d' filename.txt 3. To Delete line from range x to y Syntax: $ sed 'x,yd' filename.txt Example: $ sed '3,6d' filename.txt 4. To Delete from nth to last line Syntax: $ sed 'nth,$d' filename.txt Example: $ sed '12,$d' filename.txt 5. To Delete pattern matching line Syntax: $ sed '/pattern/d' filename.txt Example: $ sed '/abc/d' filename.txt Replacing or substituting string : Sed command is mostly used to replace the text in a file. The below simple sed command replaces the word “unix” with “linux” in the file. $sed 's/unix/linux/' geekfile.txt Output : linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Here the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string. By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third...occurrence in the line. $sed 's/unix/linux/' geekfile.txt Output : linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Here the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string. By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third...occurrence in the line. Replacing the nth occurrence of a pattern in a line : Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word “unix” with “linux” in a line. $sed 's/unix/linux/2' geekfile.txt Output: unix is great os. linux is opensource. unix is free os. learn operating system. unix linux which one you choose. unix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful. $sed 's/unix/linux/2' geekfile.txt Output: unix is great os. linux is opensource. unix is free os. learn operating system. unix linux which one you choose. unix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful. Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line. $sed 's/unix/linux/g' geekfile.txt Output : linux is great os. linux is opensource. linux is free os. learn operating system. linux linux which one you choose. linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful. $sed 's/unix/linux/g' geekfile.txt Output : linux is great os. linux is opensource. linux is free os. learn operating system. linux linux which one you choose. linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful. Replacing from nth occurrence to all occurrences in a line : Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces the third, fourth, fifth... “unix” word with “linux” word in a line. $sed 's/unix/linux/3g' geekfile.txt Output: unix is great os. unix is opensource. linux is free os. learn operating system. unix linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful. $sed 's/unix/linux/3g' geekfile.txt Output: unix is great os. unix is opensource. linux is free os. learn operating system. unix linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful. Parenthesize first character of each word : This sed example prints the first character of every word in parenthesis. $ echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g' Output: (W)elcome (T)o (T)he (G)eek (S)tuff $ echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g' Output: (W)elcome (T)o (T)he (G)eek (S)tuff Replacing string on a specific line number : You can restrict the sed command to replace the string on a specific line number. An example is $sed '3 s/unix/linux/' geekfile.txt Output: unix is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. The above sed command replaces the string only on the third line. $sed '3 s/unix/linux/' geekfile.txt Output: unix is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. The above sed command replaces the string only on the third line. Duplicating the replaced line with /p flag : The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once. $sed 's/unix/linux/p' geekfile.txt Output: linux is great os. unix is opensource. unix is free os. linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. $sed 's/unix/linux/p' geekfile.txt Output: linux is great os. unix is opensource. unix is free os. linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Printing only the replaced lines : Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time. $sed -n 's/unix/linux/p' geekfile.txt Output: linux is great os. unix is opensource. unix is free os. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. If you use -n alone without /p, then the sed does not print anything. $sed -n 's/unix/linux/p' geekfile.txt Output: linux is great os. unix is opensource. unix is free os. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. If you use -n alone without /p, then the sed does not print anything. Replacing string on a range of lines : You can specify a range of line numbers to the sed command for replacing a string. $sed '1,3 s/unix/linux/' geekfile.txt Output: linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Here the sed command replaces the lines with range from 1 to 3. Another example is $sed '2,$ s/unix/linux/' geekfile.txt Output: unix is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful Here $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file. $sed '1,3 s/unix/linux/' geekfile.txt Output: linux is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful. Here the sed command replaces the lines with range from 1 to 3. Another example is $sed '2,$ s/unix/linux/' geekfile.txt Output: unix is great os. unix is opensource. unix is free os. learn operating system. linux linux which one you choose. linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful Here $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file. Deleting lines from a particular file : SED command can also be used for deleting lines from a particular file. SED command is used for performing deletion operation without even opening the file Examples: 1. To Delete a particular line say n in this example Syntax: $ sed 'nd' filename.txt Example: $ sed '5d' filename.txt 2. To Delete a last line Syntax: $ sed '$d' filename.txt 3. To Delete line from range x to y Syntax: $ sed 'x,yd' filename.txt Example: $ sed '3,6d' filename.txt 4. To Delete from nth to last line Syntax: $ sed 'nth,$d' filename.txt Example: $ sed '12,$d' filename.txt 5. To Delete pattern matching line Syntax: $ sed '/pattern/d' filename.txt Example: $ sed '/abc/d' filename.txt Syntax: $ sed 'nd' filename.txt Example: $ sed '5d' filename.txt 2. To Delete a last line Syntax: $ sed '$d' filename.txt 3. To Delete line from range x to y Syntax: $ sed 'x,yd' filename.txt Example: $ sed '3,6d' filename.txt 4. To Delete from nth to last line Syntax: $ sed 'nth,$d' filename.txt Example: $ sed '12,$d' filename.txt 5. To Delete pattern matching line Syntax: $ sed '/pattern/d' filename.txt Example: $ sed '/abc/d' filename.txt SED command in Linux | Set 2 This article is contributed by Akshay Rajput and Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ManasChhabra2 meetgor linux-command Linux-text-processing-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Mutex lock for Linux Thread Synchronization Compiling with g++ Cat command in Linux with examples tar command in Linux with examples Named Pipe or FIFO with example C program Making your own Linux Shell in C Thread functions in C/C++ Head command in Linux with examples ps command in Linux with Examples Piping in Unix or Linux
[ { "code": null, "e": 23639, "s": 23608, "text": " \n21 Dec, 2021\n" }, { "code": null, "e": 24065, "s": 23639, "text": "SED command in UNIX stands for stream editor and it can perform lots of functions on file like searching, find and replace, insertion or deletion. Though most common use of SED command in UNIX is for substitution or for find and replace. By using SED you can edit files even without opening them, which is much quicker way to find and replace something in file, than first opening that file in VI Editor and then changing it." }, { "code": null, "e": 24166, "s": 24065, "text": "SED is a powerful text stream editor. Can do insertion, deletion, search and replace(substitution)." }, { "code": null, "e": 24264, "s": 24166, "text": "SED command in unix supports regular expression which allows it perform complex pattern matching." }, { "code": null, "e": 24272, "s": 24264, "text": "Syntax:" }, { "code": null, "e": 24312, "s": 24272, "text": "sed OPTIONS... [SCRIPT] [INPUTFILE...] " }, { "code": null, "e": 24363, "s": 24312, "text": "Example:\nConsider the below text file as an input." }, { "code": null, "e": 24384, "s": 24363, "text": "$cat > geekfile.txt\n" }, { "code": null, "e": 24574, "s": 24384, "text": "unix is great os. unix is opensource. unix is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 24590, "s": 24574, "text": "Sample Commands" }, { "code": null, "e": 30071, "s": 24590, "text": "\nReplacing or substituting string : Sed command is mostly used to replace the text in a file. The below simple sed command replaces the word “unix” with “linux” in the file.\n$sed 's/unix/linux/' geekfile.txt\n\nOutput : \nlinux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n\nHere the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string. \nBy default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third...occurrence in the line. \nReplacing the nth occurrence of a pattern in a line : Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word “unix” with “linux” in a line.\n$sed 's/unix/linux/2' geekfile.txt\n\nOutput:\nunix is great os. linux is opensource. unix is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful.\n\n\nReplacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.\n$sed 's/unix/linux/g' geekfile.txt\n\nOutput : \nlinux is great os. linux is opensource. linux is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.\n\n\nReplacing from nth occurrence to all occurrences in a line : Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces the third, fourth, fifth... “unix” word with “linux” word in a line.\n$sed 's/unix/linux/3g' geekfile.txt\n\nOutput:\nunix is great os. unix is opensource. linux is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful.\n\n\nParenthesize first character of each word : This sed example prints the first character of every word in parenthesis.\n$ echo \"Welcome To The Geek Stuff\" | sed 's/\\(\\b[A-Z]\\)/\\(\\1\\)/g'\n\nOutput:\n(W)elcome (T)o (T)he (G)eek (S)tuff\n\n\nReplacing string on a specific line number : You can restrict the sed command to replace the string on a specific line number. An example is\n$sed '3 s/unix/linux/' geekfile.txt\n\nOutput:\nunix is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n\nThe above sed command replaces the string only on the third line. \nDuplicating the replaced line with /p flag : The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.\n$sed 's/unix/linux/p' geekfile.txt\n\nOutput:\nlinux is great os. unix is opensource. unix is free os.\nlinux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n\n\nPrinting only the replaced lines : Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.\n$sed -n 's/unix/linux/p' geekfile.txt\n\nOutput:\nlinux is great os. unix is opensource. unix is free os.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n\nIf you use -n alone without /p, then the sed does not print anything.\n \nReplacing string on a range of lines : You can specify a range of line numbers to the sed command for replacing a string.\n$sed '1,3 s/unix/linux/' geekfile.txt\n\nOutput:\nlinux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n\nHere the sed command replaces the lines with range from 1 to 3. Another example is\n$sed '2,$ s/unix/linux/' geekfile.txt\n\nOutput:\nunix is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful\n\nHere $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file.\n \nDeleting lines from a particular file : SED command can also be used for deleting lines from a particular file. SED command is used for performing deletion operation without even opening the file\nExamples:\n1. To Delete a particular line say n in this example\nSyntax:\n$ sed 'nd' filename.txt\nExample:\n$ sed '5d' filename.txt\n\n2. To Delete a last line\nSyntax:\n$ sed '$d' filename.txt\n\n3. To Delete line from range x to y\nSyntax:\n$ sed 'x,yd' filename.txt\nExample:\n$ sed '3,6d' filename.txt\n\n4. To Delete from nth to last line\nSyntax:\n$ sed 'nth,$d' filename.txt\nExample:\n$ sed '12,$d' filename.txt\n\n5. To Delete pattern matching line\nSyntax:\n$ sed '/pattern/d' filename.txt\nExample:\n$ sed '/abc/d' filename.txt\n\n\n" }, { "code": null, "e": 30786, "s": 30071, "text": "Replacing or substituting string : Sed command is mostly used to replace the text in a file. The below simple sed command replaces the word “unix” with “linux” in the file.\n$sed 's/unix/linux/' geekfile.txt\n\nOutput : \nlinux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n\nHere the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string. \nBy default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third...occurrence in the line. " }, { "code": null, "e": 30821, "s": 30786, "text": "$sed 's/unix/linux/' geekfile.txt\n" }, { "code": null, "e": 30831, "s": 30821, "text": "Output : " }, { "code": null, "e": 31024, "s": 30831, "text": "linux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 31176, "s": 31024, "text": "Here the “s” specifies the substitution operation. The “/” are delimiters. The “unix” is the search pattern and the “linux” is the replacement string. " }, { "code": null, "e": 31328, "s": 31176, "text": "By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third...occurrence in the line. " }, { "code": null, "e": 31801, "s": 31328, "text": "Replacing the nth occurrence of a pattern in a line : Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word “unix” with “linux” in a line.\n$sed 's/unix/linux/2' geekfile.txt\n\nOutput:\nunix is great os. linux is opensource. unix is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful.\n\n" }, { "code": null, "e": 31837, "s": 31801, "text": "$sed 's/unix/linux/2' geekfile.txt\n" }, { "code": null, "e": 31845, "s": 31837, "text": "Output:" }, { "code": null, "e": 32037, "s": 31845, "text": "unix is great os. linux is opensource. unix is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 32466, "s": 32037, "text": "Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.\n$sed 's/unix/linux/g' geekfile.txt\n\nOutput : \nlinux is great os. linux is opensource. linux is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.\n\n" }, { "code": null, "e": 32502, "s": 32466, "text": "$sed 's/unix/linux/g' geekfile.txt\n" }, { "code": null, "e": 32512, "s": 32502, "text": "Output : " }, { "code": null, "e": 32710, "s": 32512, "text": "linux is great os. linux is opensource. linux is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.\n" }, { "code": null, "e": 33231, "s": 32710, "text": "Replacing from nth occurrence to all occurrences in a line : Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence of a pattern in a line. The following sed command replaces the third, fourth, fifth... “unix” word with “linux” word in a line.\n$sed 's/unix/linux/3g' geekfile.txt\n\nOutput:\nunix is great os. unix is opensource. linux is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful.\n\n" }, { "code": null, "e": 33268, "s": 33231, "text": "$sed 's/unix/linux/3g' geekfile.txt\n" }, { "code": null, "e": 33276, "s": 33268, "text": "Output:" }, { "code": null, "e": 33469, "s": 33276, "text": "unix is great os. unix is opensource. linux is free os.\nlearn operating system.\nunix linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn linux .linux is a powerful.\n" }, { "code": null, "e": 33700, "s": 33469, "text": "Parenthesize first character of each word : This sed example prints the first character of every word in parenthesis.\n$ echo \"Welcome To The Geek Stuff\" | sed 's/\\(\\b[A-Z]\\)/\\(\\1\\)/g'\n\nOutput:\n(W)elcome (T)o (T)he (G)eek (S)tuff\n\n" }, { "code": null, "e": 33767, "s": 33700, "text": "$ echo \"Welcome To The Geek Stuff\" | sed 's/\\(\\b[A-Z]\\)/\\(\\1\\)/g'\n" }, { "code": null, "e": 33775, "s": 33767, "text": "Output:" }, { "code": null, "e": 33812, "s": 33775, "text": "(W)elcome (T)o (T)he (G)eek (S)tuff\n" }, { "code": null, "e": 34256, "s": 33812, "text": "Replacing string on a specific line number : You can restrict the sed command to replace the string on a specific line number. An example is\n$sed '3 s/unix/linux/' geekfile.txt\n\nOutput:\nunix is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n\nThe above sed command replaces the string only on the third line. " }, { "code": null, "e": 34293, "s": 34256, "text": "$sed '3 s/unix/linux/' geekfile.txt\n" }, { "code": null, "e": 34301, "s": 34293, "text": "Output:" }, { "code": null, "e": 34492, "s": 34301, "text": "unix is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 34559, "s": 34492, "text": "The above sed command replaces the string only on the third line. " }, { "code": null, "e": 35180, "s": 34559, "text": "Duplicating the replaced line with /p flag : The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.\n$sed 's/unix/linux/p' geekfile.txt\n\nOutput:\nlinux is great os. unix is opensource. unix is free os.\nlinux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n\n" }, { "code": null, "e": 35216, "s": 35180, "text": "$sed 's/unix/linux/p' geekfile.txt\n" }, { "code": null, "e": 35224, "s": 35216, "text": "Output:" }, { "code": null, "e": 35585, "s": 35224, "text": "linux is great os. unix is opensource. unix is free os.\nlinux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 36110, "s": 35585, "text": "Printing only the replaced lines : Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.\n$sed -n 's/unix/linux/p' geekfile.txt\n\nOutput:\nlinux is great os. unix is opensource. unix is free os.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n\nIf you use -n alone without /p, then the sed does not print anything.\n " }, { "code": null, "e": 36149, "s": 36110, "text": "$sed -n 's/unix/linux/p' geekfile.txt\n" }, { "code": null, "e": 36157, "s": 36149, "text": "Output:" }, { "code": null, "e": 36326, "s": 36157, "text": "linux is great os. unix is opensource. unix is free os.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 36398, "s": 36326, "text": "If you use -n alone without /p, then the sed does not print anything.\n " }, { "code": null, "e": 37207, "s": 36398, "text": "Replacing string on a range of lines : You can specify a range of line numbers to the sed command for replacing a string.\n$sed '1,3 s/unix/linux/' geekfile.txt\n\nOutput:\nlinux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n\nHere the sed command replaces the lines with range from 1 to 3. Another example is\n$sed '2,$ s/unix/linux/' geekfile.txt\n\nOutput:\nunix is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful\n\nHere $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file.\n " }, { "code": null, "e": 37246, "s": 37207, "text": "$sed '1,3 s/unix/linux/' geekfile.txt\n" }, { "code": null, "e": 37254, "s": 37246, "text": "Output:" }, { "code": null, "e": 37446, "s": 37254, "text": "linux is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nunix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.\n" }, { "code": null, "e": 37529, "s": 37446, "text": "Here the sed command replaces the lines with range from 1 to 3. Another example is" }, { "code": null, "e": 37568, "s": 37529, "text": "$sed '2,$ s/unix/linux/' geekfile.txt\n" }, { "code": null, "e": 37576, "s": 37568, "text": "Output:" }, { "code": null, "e": 37767, "s": 37576, "text": "unix is great os. unix is opensource. unix is free os.\nlearn operating system.\nlinux linux which one you choose.\nlinux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful\n" }, { "code": null, "e": 37893, "s": 37767, "text": "Here $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file.\n " }, { "code": null, "e": 38604, "s": 37893, "text": "Deleting lines from a particular file : SED command can also be used for deleting lines from a particular file. SED command is used for performing deletion operation without even opening the file\nExamples:\n1. To Delete a particular line say n in this example\nSyntax:\n$ sed 'nd' filename.txt\nExample:\n$ sed '5d' filename.txt\n\n2. To Delete a last line\nSyntax:\n$ sed '$d' filename.txt\n\n3. To Delete line from range x to y\nSyntax:\n$ sed 'x,yd' filename.txt\nExample:\n$ sed '3,6d' filename.txt\n\n4. To Delete from nth to last line\nSyntax:\n$ sed 'nth,$d' filename.txt\nExample:\n$ sed '12,$d' filename.txt\n\n5. To Delete pattern matching line\nSyntax:\n$ sed '/pattern/d' filename.txt\nExample:\n$ sed '/abc/d' filename.txt\n\n" }, { "code": null, "e": 38670, "s": 38604, "text": "Syntax:\n$ sed 'nd' filename.txt\nExample:\n$ sed '5d' filename.txt\n" }, { "code": null, "e": 38695, "s": 38670, "text": "2. To Delete a last line" }, { "code": null, "e": 38728, "s": 38695, "text": "Syntax:\n$ sed '$d' filename.txt\n" }, { "code": null, "e": 38764, "s": 38728, "text": "3. To Delete line from range x to y" }, { "code": null, "e": 38834, "s": 38764, "text": "Syntax:\n$ sed 'x,yd' filename.txt\nExample:\n$ sed '3,6d' filename.txt\n" }, { "code": null, "e": 38869, "s": 38834, "text": "4. To Delete from nth to last line" }, { "code": null, "e": 38942, "s": 38869, "text": "Syntax:\n$ sed 'nth,$d' filename.txt\nExample:\n$ sed '12,$d' filename.txt\n" }, { "code": null, "e": 38977, "s": 38942, "text": "5. To Delete pattern matching line" }, { "code": null, "e": 39055, "s": 38977, "text": "Syntax:\n$ sed '/pattern/d' filename.txt\nExample:\n$ sed '/abc/d' filename.txt\n" }, { "code": null, "e": 39085, "s": 39055, "text": "\nSED command in Linux | Set 2" }, { "code": null, "e": 39400, "s": 39085, "text": "This article is contributed by Akshay Rajput and Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 39525, "s": 39400, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 39539, "s": 39525, "text": "ManasChhabra2" }, { "code": null, "e": 39547, "s": 39539, "text": "meetgor" }, { "code": null, "e": 39563, "s": 39547, "text": "\nlinux-command\n" }, { "code": null, "e": 39596, "s": 39563, "text": "\nLinux-text-processing-commands\n" }, { "code": null, "e": 39609, "s": 39596, "text": "\nLinux-Unix\n" }, { "code": null, "e": 39814, "s": 39609, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 39858, "s": 39814, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 39877, "s": 39858, "text": "Compiling with g++" }, { "code": null, "e": 39912, "s": 39877, "text": "Cat command in Linux with examples" }, { "code": null, "e": 39947, "s": 39912, "text": "tar command in Linux with examples" }, { "code": null, "e": 39989, "s": 39947, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 40022, "s": 39989, "text": "Making your own Linux Shell in C" }, { "code": null, "e": 40048, "s": 40022, "text": "Thread functions in C/C++" }, { "code": null, "e": 40084, "s": 40048, "text": "Head command in Linux with examples" }, { "code": null, "e": 40119, "s": 40084, "text": "ps command in Linux with Examples" } ]
What is Syntax Tree?
tree in which each leaf node describes an operand & each interior node an operator. The syntax tree is shortened form of the Parse Tree. Example1 − Draw Syntax Tree for the string a + b ∗ c − d. Rules for constructing a syntax tree Each node in a syntax tree can be executed as data with multiple fields. In the node for an operator, one field recognizes the operator and the remaining field includes a pointer to the nodes for the operands. The operator is known as the label of the node. The following functions are used to create the nodes of the syntax tree for the expressions with binary operators. Each function returns a pointer to the recently generated node. mknode (op, left, right) − It generates an operator node with label op and two field including pointers to left and right. mknode (op, left, right) − It generates an operator node with label op and two field including pointers to left and right. mkleaf (id, entry) − It generates an identifier node with label id and the field including the entry, a pointer to the symbol table entry for the identifier. mkleaf (id, entry) − It generates an identifier node with label id and the field including the entry, a pointer to the symbol table entry for the identifier. mkleaf (num, val) − It generates a number node with label num and a field including val, the value of the number. For example, construct a syntax tree for an expression a − 4 + c. In this sequence, p1, p2, ... . . p5are pointers to the symbol table entries for identifier 'a' and 'c' respectively. mkleaf (num, val) − It generates a number node with label num and a field including val, the value of the number. For example, construct a syntax tree for an expression a − 4 + c. In this sequence, p1, p2, ... . . p5are pointers to the symbol table entries for identifier 'a' and 'c' respectively. p1− mkleaf (id, entry a); p2− mkleaf (num, 4); p3− mknode ( ′−′, p1, p2) p4− mkleaf(id, entry c) p5− mknode(′+′, p3, p4); The tree is generated in a bottom-up fashion. The function calls mkleaf (id, entry a) and mkleaf (num 4) construct the leaves for a and 4. The pointers to these nodes are stored using p1and p2. The call mknodes (′−′, p1, p2 ) then make the interior node with the leaves for a and 4 as children. The syntax tree will be Syntax Directed Translation of Syntax Trees Node (+, E(1), VAL, E(2). VAL) will create a node labeled +. E(1). VAL &E(2). VAL are left & right children of this node. Similarly, Node (∗, E(1). VAL, E(2). VAL) will make the syntax as − Function UNARY (−, E(1). VAL)will make a node – (unary minus) & E(1). VAL will be the only child of it. Function LEAF (id) will create a Leaf node with label id. Example2 − Construct a syntax tree for the expression. a = b ∗ −c + d Solution Example3 − Construct a syntax tree for a statement. If a = b then b = 2 * c Solution Example4 − Consider the following code. Draw its syntax Tree If x > 0 then x = 2 * (a + 1) else x = x + 1. Example5 − Draw syntax tree for following arithmetic expression a * (b + c) – d /2. Also, write given expression in postfix form. Postfix Notation a b c + * d 2 / -
[ { "code": null, "e": 1199, "s": 1062, "text": "tree in which each leaf node describes an operand & each interior node an operator. The syntax tree is shortened form of the Parse Tree." }, { "code": null, "e": 1257, "s": 1199, "text": "Example1 − Draw Syntax Tree for the string a + b ∗ c − d." }, { "code": null, "e": 1294, "s": 1257, "text": "Rules for constructing a syntax tree" }, { "code": null, "e": 1731, "s": 1294, "text": "Each node in a syntax tree can be executed as data with multiple fields. In the node for an operator, one field recognizes the operator and the remaining field includes a pointer to the nodes for the operands. The operator is known as the label of the node. The following functions are used to create the nodes of the syntax tree for the expressions with binary operators. Each function returns a pointer to the recently generated node." }, { "code": null, "e": 1854, "s": 1731, "text": "mknode (op, left, right) − It generates an operator node with label op and two field including pointers to left and right." }, { "code": null, "e": 1977, "s": 1854, "text": "mknode (op, left, right) − It generates an operator node with label op and two field including pointers to left and right." }, { "code": null, "e": 2135, "s": 1977, "text": "mkleaf (id, entry) − It generates an identifier node with label id and the field including the entry, a pointer to the symbol table entry for the identifier." }, { "code": null, "e": 2293, "s": 2135, "text": "mkleaf (id, entry) − It generates an identifier node with label id and the field including the entry, a pointer to the symbol table entry for the identifier." }, { "code": null, "e": 2591, "s": 2293, "text": "mkleaf (num, val) − It generates a number node with label num and a field including val, the value of the number. For example, construct a syntax tree for an expression a − 4 + c. In this sequence, p1, p2, ... . . p5are pointers to the symbol table entries for identifier 'a' and 'c' respectively." }, { "code": null, "e": 2889, "s": 2591, "text": "mkleaf (num, val) − It generates a number node with label num and a field including val, the value of the number. For example, construct a syntax tree for an expression a − 4 + c. In this sequence, p1, p2, ... . . p5are pointers to the symbol table entries for identifier 'a' and 'c' respectively." }, { "code": null, "e": 3011, "s": 2889, "text": "p1− mkleaf (id, entry a);\np2− mkleaf (num, 4);\np3− mknode ( ′−′, p1, p2)\np4− mkleaf(id, entry c)\np5− mknode(′+′, p3, p4);" }, { "code": null, "e": 3330, "s": 3011, "text": "The tree is generated in a bottom-up fashion. The function calls mkleaf (id, entry a) and mkleaf (num 4) construct the leaves for a and 4. The pointers to these nodes are stored using p1and p2. The call mknodes (′−′, p1, p2 ) then make the interior node with the leaves for a and 4 as children. The syntax tree will be" }, { "code": null, "e": 3374, "s": 3330, "text": "Syntax Directed Translation of Syntax Trees" }, { "code": null, "e": 3435, "s": 3374, "text": "Node (+, E(1), VAL, E(2). VAL) will create a node labeled +." }, { "code": null, "e": 3496, "s": 3435, "text": "E(1). VAL &E(2). VAL are left & right children of this node." }, { "code": null, "e": 3564, "s": 3496, "text": "Similarly, Node (∗, E(1). VAL, E(2). VAL) will make the syntax as −" }, { "code": null, "e": 3668, "s": 3564, "text": "Function UNARY (−, E(1). VAL)will make a node – (unary minus) & E(1). VAL will be the only child of it." }, { "code": null, "e": 3726, "s": 3668, "text": "Function LEAF (id) will create a Leaf node with label id." }, { "code": null, "e": 3781, "s": 3726, "text": "Example2 − Construct a syntax tree for the expression." }, { "code": null, "e": 3796, "s": 3781, "text": "a = b ∗ −c + d" }, { "code": null, "e": 3805, "s": 3796, "text": "Solution" }, { "code": null, "e": 3857, "s": 3805, "text": "Example3 − Construct a syntax tree for a statement." }, { "code": null, "e": 3881, "s": 3857, "text": "If a = b then b = 2 * c" }, { "code": null, "e": 3890, "s": 3881, "text": "Solution" }, { "code": null, "e": 3951, "s": 3890, "text": "Example4 − Consider the following code. Draw its syntax Tree" }, { "code": null, "e": 3997, "s": 3951, "text": "If x > 0 then x = 2 * (a + 1) else x = x + 1." }, { "code": null, "e": 4127, "s": 3997, "text": "Example5 − Draw syntax tree for following arithmetic expression a * (b + c) – d /2. Also, write given expression in postfix form." }, { "code": null, "e": 4144, "s": 4127, "text": "Postfix Notation" }, { "code": null, "e": 4162, "s": 4144, "text": "a b c + * d 2 / -" } ]
What are literals in Java?
A literal is a source code representation of a fixed value. They are represented directly in the code without any computation. Literals can be assigned to any primitive type variable. byte a = 68; char a = 'A' byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8) number systems as well. Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when using these number systems for literals. For example − int decimal = 100; int octal = 0144; int hexa = 0x64; String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are − "Hello World" "two\nlines" "\"This is in quotes\"" String and char types of literals can contain any Unicode characters. For example − char a = '\u0001'; String a = "\u0001";
[ { "code": null, "e": 1189, "s": 1062, "text": "A literal is a source code representation of a fixed value. They are represented directly in the code without any computation." }, { "code": null, "e": 1246, "s": 1189, "text": "Literals can be assigned to any primitive type variable." }, { "code": null, "e": 1272, "s": 1246, "text": "byte a = 68;\nchar a = 'A'" }, { "code": null, "e": 1399, "s": 1272, "text": "byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8) number systems as well." }, { "code": null, "e": 1531, "s": 1399, "text": "Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when using these number systems for literals. For example −" }, { "code": null, "e": 1585, "s": 1531, "text": "int decimal = 100;\nint octal = 0144;\nint hexa = 0x64;" }, { "code": null, "e": 1766, "s": 1585, "text": "String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are −" }, { "code": null, "e": 1817, "s": 1766, "text": "\"Hello World\"\n\"two\\nlines\"\n\"\\\"This is in quotes\\\"\"" }, { "code": null, "e": 1901, "s": 1817, "text": "String and char types of literals can contain any Unicode characters. For example −" }, { "code": null, "e": 1941, "s": 1901, "text": "char a = '\\u0001';\nString a = \"\\u0001\";" } ]
Binary Search
When the list is sorted we can use the binary search technique to find items on the list. In this procedure, the entire list is divided into two sub-lists. If the item is found in the middle position, it returns the location, otherwise jumps to either left or right sub-list and do the same process again until finding the item or exceed the range. Time Complexity: O(1) for the best case. O(log2 n) for average or worst case. Space Complexity: O(1) Input: A sorted list of data: 12 25 48 52 67 79 88 93 The search key 79 Output: Item found at location: 5 binarySearch(array, start, end, key) Input − An sorted array, start and end location, and the search key Output − location of the key (if found), otherwise wrong location. Begin if start <= end then mid := start + (end - start) /2 if array[mid] = key then return mid location if array[mid] > key then call binarySearch(array, mid+1, end, key) else when array[mid] < key then call binarySearch(array, start, mid-1, key) else return invalid location End #include<iostream> using namespace std; int binarySearch(int array[], int start, int end, int key) { if(start <= end) { int mid = (start + (end - start) /2); //mid location of the list if(array[mid] == key) return mid; if(array[mid] > key) return binarySearch(array, start, mid-1, key); return binarySearch(array, mid+1, end, key); } return -1; } int main() { int n, searchKey, loc; cout << "Enter number of items: "; cin >> n; int arr[n]; //create an array of size n cout << "Enter items: " << endl; for(int i = 0; i< n; i++) { cin >> arr[i]; } cout << "Enter search key to search in the list: "; cin >> searchKey; if((loc = binarySearch(arr, 0, n, searchKey)) >= 0) cout << "Item found at location: " << loc << endl; else cout << "Item is not found in the list." << endl; } Enter number of items: 8 Enter items: 12 25 48 52 67 79 88 93 Enter search key to search in the list: 79 Item found at location: 5
[ { "code": null, "e": 1411, "s": 1062, "text": "When the list is sorted we can use the binary search technique to find items on the list. In this procedure, the entire list is divided into two sub-lists. If the item is found in the middle position, it returns the location, otherwise jumps to either left or right sub-list and do the same process again until finding the item or exceed the range." }, { "code": null, "e": 1489, "s": 1411, "text": "Time Complexity: O(1) for the best case. O(log2 n) for average or worst case." }, { "code": null, "e": 1513, "s": 1489, "text": "Space Complexity: O(1) " }, { "code": null, "e": 1620, "s": 1513, "text": "Input: \nA sorted list of data: 12 25 48 52 67 79 88 93\nThe search key 79\nOutput:\nItem found at location: 5" }, { "code": null, "e": 1657, "s": 1620, "text": "binarySearch(array, start, end, key)" }, { "code": null, "e": 1725, "s": 1657, "text": "Input − An sorted array, start and end location, and the search key" }, { "code": null, "e": 1792, "s": 1725, "text": "Output − location of the key (if found), otherwise wrong location." }, { "code": null, "e": 2135, "s": 1792, "text": "Begin\n if start <= end then\n mid := start + (end - start) /2\n if array[mid] = key then\n return mid location\n if array[mid] > key then\n call binarySearch(array, mid+1, end, key)\n else when array[mid] < key then\n call binarySearch(array, start, mid-1, key)\n else\n return invalid location\nEnd" }, { "code": null, "e": 3022, "s": 2135, "text": "#include<iostream>\nusing namespace std;\n\nint binarySearch(int array[], int start, int end, int key) {\n if(start <= end) {\n int mid = (start + (end - start) /2); //mid location of the list\n if(array[mid] == key)\n return mid;\n if(array[mid] > key)\n return binarySearch(array, start, mid-1, key);\n return binarySearch(array, mid+1, end, key);\n }\n return -1;\n}\n\nint main() {\n int n, searchKey, loc;\n cout << \"Enter number of items: \";\n cin >> n;\n\n int arr[n]; //create an array of size n\n cout << \"Enter items: \" << endl;\n\n for(int i = 0; i< n; i++) {\n cin >> arr[i];\n }\n\n cout << \"Enter search key to search in the list: \";\n cin >> searchKey;\n\n if((loc = binarySearch(arr, 0, n, searchKey)) >= 0)\n cout << \"Item found at location: \" << loc << endl;\n else\n cout << \"Item is not found in the list.\" << endl;\n}" }, { "code": null, "e": 3153, "s": 3022, "text": "Enter number of items: 8\nEnter items:\n12 25 48 52 67 79 88 93\nEnter search key to search in the list: 79\nItem found at location: 5" } ]
What are the different data types used in SQL queries?
Data type specifies the kind of data that a field stores. There are different types of data types used in the structured query language (SQL) queries which are as follows − Character data type Number data type Date and time data types Let’s see each data type with an example. Character data types are used to store characters. We can use CHAR, VARCHAR, VARCHAR2, NVARCHAR2, NCAHR and LONG as character data types. It stores variable-length character data up to a maximum of 4000 characters. Values in different records can have a different number of characters. The syntax is as follows − fieldname VARCHAR2(maximum size) Given below is an example of VARCHAR2 character data type − create table employee(ename varchar2(30),department varchar2(20)); The output is given herewith: Table created It is the same as VARCHAR2 but it is in ANSI standard. The syntax is as follows − fieldname VARCHAR(maximum size) Given below is an example of VARCHAR character data type − create table student(stdname varchar(20), branch varchar(30)); The output is given herewith: Table created It has fixed length character data up to a maximum size of 2000 characters. Data values for different records all have the same number of characters. DBMS adds trailing blank spaces to the end of the entry to make the entry fill with maximum size value. Data longer than maximum size causes an error. The syntax is as follows − fieldname CHAR(maximum size) Given below is an example of CHAR character data type − create table student(stdname char(20), branch char(30)); Output: Table created; In the above example student name and branch both are of character data types, so a table is created with column names stdname and branch. It is analogous to VARCHAR2 and CHAR but uses Unicode rather than ASCII. It is used to hold character data in languages other than English. Given below is an example of NVARCHAR and NCHAR character data type − create table employee(ename NVARCHAR2(30),department NCHAR2(20)); insert into employee values('bhanu','CSE'); insert into employee values('priya','ECE'); insert into employee values('hari','EEE'); select * from employee; The output is as follows − bhanu|CSE priya|ECE hari |EEE Variable length character data up to 2 GB, max per one table. This data type stores negative, positive, fixed and floating-point numbers with precision up to 38 decimal places. The syntax is as follows − filedname NUMBER[(precision, scale)] Integer: fieldname NUMBER(precision) Fixed Point: fieldname NUMBER[(precision, scale)] Given below is an example of the number data type − create table employee(ename NVARCHAR2(30),department NCHAR2(20), average NUMBER(5,2)); insert into employee values('bhanu','CSE',-0.5); insert into employee values('priya','ECE',15.6); insert into employee values('hari','EEE',27.8); select * from employee; The output is given below − bhanu|CSE|-0.5 priya|ECE|15.6 hari|EEE|27.8 Dates are from BC to AD. Default date format is DD-MM-YY. Default time format is: HH:MI:SS AM The syntax is as follows − fieldname DATE It is similar to DATE but stores fractional seconds. The syntax is as follows − fieldname TIMESTAMP(fractional-seconds-pre)
[ { "code": null, "e": 1235, "s": 1062, "text": "Data type specifies the kind of data that a field stores. There are different types of data types used in the structured query language (SQL) queries which are as follows −" }, { "code": null, "e": 1255, "s": 1235, "text": "Character data type" }, { "code": null, "e": 1272, "s": 1255, "text": "Number data type" }, { "code": null, "e": 1297, "s": 1272, "text": "Date and time data types" }, { "code": null, "e": 1339, "s": 1297, "text": "Let’s see each data type with an example." }, { "code": null, "e": 1477, "s": 1339, "text": "Character data types are used to store characters. We can use CHAR, VARCHAR, VARCHAR2, NVARCHAR2, NCAHR and LONG as character data types." }, { "code": null, "e": 1625, "s": 1477, "text": "It stores variable-length character data up to a maximum of 4000 characters. Values in different records can have a different number of characters." }, { "code": null, "e": 1652, "s": 1625, "text": "The syntax is as follows −" }, { "code": null, "e": 1685, "s": 1652, "text": "fieldname VARCHAR2(maximum size)" }, { "code": null, "e": 1745, "s": 1685, "text": "Given below is an example of VARCHAR2 character data type −" }, { "code": null, "e": 1812, "s": 1745, "text": "create table employee(ename varchar2(30),department varchar2(20));" }, { "code": null, "e": 1856, "s": 1812, "text": "The output is given herewith: Table created" }, { "code": null, "e": 1911, "s": 1856, "text": "It is the same as VARCHAR2 but it is in ANSI standard." }, { "code": null, "e": 1938, "s": 1911, "text": "The syntax is as follows −" }, { "code": null, "e": 1970, "s": 1938, "text": "fieldname VARCHAR(maximum size)" }, { "code": null, "e": 2029, "s": 1970, "text": "Given below is an example of VARCHAR character data type −" }, { "code": null, "e": 2093, "s": 2029, "text": "create table student(stdname varchar(20), branch varchar(30));\n" }, { "code": null, "e": 2137, "s": 2093, "text": "The output is given herewith: Table created" }, { "code": null, "e": 2287, "s": 2137, "text": "It has fixed length character data up to a maximum size of 2000 characters. Data values for different records all have the same number of characters." }, { "code": null, "e": 2438, "s": 2287, "text": "DBMS adds trailing blank spaces to the end of the entry to make the entry fill with maximum size value. Data longer than maximum size causes an error." }, { "code": null, "e": 2465, "s": 2438, "text": "The syntax is as follows −" }, { "code": null, "e": 2494, "s": 2465, "text": "fieldname CHAR(maximum size)" }, { "code": null, "e": 2550, "s": 2494, "text": "Given below is an example of CHAR character data type −" }, { "code": null, "e": 2630, "s": 2550, "text": "create table student(stdname char(20), branch char(30));\nOutput: Table created;" }, { "code": null, "e": 2769, "s": 2630, "text": "In the above example student name and branch both are of character data types, so a table is created with column names stdname and branch." }, { "code": null, "e": 2909, "s": 2769, "text": "It is analogous to VARCHAR2 and CHAR but uses Unicode rather than ASCII. It is used to hold character data in languages other than English." }, { "code": null, "e": 2979, "s": 2909, "text": "Given below is an example of NVARCHAR and NCHAR character data type −" }, { "code": null, "e": 3200, "s": 2979, "text": "create table employee(ename NVARCHAR2(30),department NCHAR2(20));\ninsert into employee values('bhanu','CSE');\ninsert into employee values('priya','ECE');\ninsert into employee values('hari','EEE');\nselect * from employee;" }, { "code": null, "e": 3227, "s": 3200, "text": "The output is as follows −" }, { "code": null, "e": 3257, "s": 3227, "text": "bhanu|CSE\npriya|ECE\nhari |EEE" }, { "code": null, "e": 3319, "s": 3257, "text": "Variable length character data up to 2 GB, max per one table." }, { "code": null, "e": 3434, "s": 3319, "text": "This data type stores negative, positive, fixed and floating-point numbers with precision up to 38 decimal places." }, { "code": null, "e": 3461, "s": 3434, "text": "The syntax is as follows −" }, { "code": null, "e": 3498, "s": 3461, "text": "filedname NUMBER[(precision, scale)]" }, { "code": null, "e": 3535, "s": 3498, "text": "Integer: fieldname NUMBER(precision)" }, { "code": null, "e": 3585, "s": 3535, "text": "Fixed Point: fieldname NUMBER[(precision, scale)]" }, { "code": null, "e": 3637, "s": 3585, "text": "Given below is an example of the number data type −" }, { "code": null, "e": 3894, "s": 3637, "text": "create table employee(ename NVARCHAR2(30),department NCHAR2(20), average NUMBER(5,2));\ninsert into employee values('bhanu','CSE',-0.5);\ninsert into employee values('priya','ECE',15.6);\ninsert into employee values('hari','EEE',27.8);\nselect * from employee;" }, { "code": null, "e": 3922, "s": 3894, "text": "The output is given below −" }, { "code": null, "e": 3966, "s": 3922, "text": "bhanu|CSE|-0.5\npriya|ECE|15.6\nhari|EEE|27.8" }, { "code": null, "e": 4024, "s": 3966, "text": "Dates are from BC to AD. Default date format is DD-MM-YY." }, { "code": null, "e": 4060, "s": 4024, "text": "Default time format is: HH:MI:SS AM" }, { "code": null, "e": 4087, "s": 4060, "text": "The syntax is as follows −" }, { "code": null, "e": 4102, "s": 4087, "text": "fieldname DATE" }, { "code": null, "e": 4155, "s": 4102, "text": "It is similar to DATE but stores fractional seconds." }, { "code": null, "e": 4182, "s": 4155, "text": "The syntax is as follows −" }, { "code": null, "e": 4226, "s": 4182, "text": "fieldname TIMESTAMP(fractional-seconds-pre)" } ]
Spelling checker in Python - GeeksforGeeks
07 Oct, 2020 For any type of text processing or analysis, checking the spelling of the word is one of the basic requirements. This article discusses various ways that you can check the spellings of the words and also can correct the spelling of the respective word. First, you need to install the library textblob using pip in command prompt. pip install textblob You can also install this library in Jupyter Notebook as: Python3 import sys!{sys.executable} - m pip install textblob Program for Spelling checker – Python3 from textblob import TextBlob a = "cmputr" # incorrect spellingprint("original text: "+str(a)) b = TextBlob(a) # prints the corrected spellingprint("corrected text: "+str(b.correct())) Output: original text: cmputr corrected text: computer You can install this library as below:Using pip: pip install pyspellchecker In Jupyter Notebook: Python3 import sys!{sys.executable} - m pip install pyspellchecker Spelling Checker program using pyspellchecker – Python3 from spellchecker import SpellChecker spell = SpellChecker() # find those words that may be misspelledmisspelled = spell.unknown(["cmputr", "watr", "study", "wrte"]) for word in misspelled: # Get the one `most likely` answer print(spell.correction(word)) # Get a list of `likely` options print(spell.candidates(word)) Output: computer {'caput', 'caputs', 'compute', 'computor', 'impute', 'computer'} water {'water', 'watt', 'warr', 'wart', 'war', 'wath', 'wat'} write {'wroe', 'arte', 'wre', 'rte', 'wrote', 'write'} To achieve the best quality while making spelling corrections dictionary-based methods are not enough. You need to consider the word surroundings. JamSpell is a python spell checking library based on a language model. It makes different corrections for a different context. 1) Install swig3 apt-get install swig3.0 # for linux brew install swig@3 # for mac 2) Install jamspell pip install jamspell 3) Download a language model for your language Python3 # Create a correctorcorrector = jamspell.TSpellCorrector() # Load Language model -# argument is a downloaded model file pathcorrector.LoadLangModel('Downloads/en_model.bin') # To fix text automatically run FixFragment:print(corrector.FixFragment('I am the begt spell cherken!')) # To get a list of possible candidates# pass a splitted sentence, and a word positionprint(corrector.GetCandidates(['i', 'am', 'the', 'begt', 'spell', 'cherken'], 3)) print(corrector.GetCandidates(['i', 'am', 'the', 'begt', 'spell', 'cherken'], 5)) Output: u'I am the best spell checker!' (u'best', u'beat', u'belt', u'bet', u'bent') (u'checker', u'chicken', u'checked', u'wherein', u'coherent', ...) filipp Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python program to convert a list to string Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python program to check whether a number is Prime or not
[ { "code": null, "e": 24024, "s": 23996, "text": "\n07 Oct, 2020" }, { "code": null, "e": 24278, "s": 24024, "text": "For any type of text processing or analysis, checking the spelling of the word is one of the basic requirements. This article discusses various ways that you can check the spellings of the words and also can correct the spelling of the respective word. " }, { "code": null, "e": 24356, "s": 24278, "text": "First, you need to install the library textblob using pip in command prompt. " }, { "code": null, "e": 24378, "s": 24356, "text": "pip install textblob\n" }, { "code": null, "e": 24438, "s": 24378, "text": "You can also install this library in Jupyter Notebook as: " }, { "code": null, "e": 24446, "s": 24438, "text": "Python3" }, { "code": "import sys!{sys.executable} - m pip install textblob", "e": 24499, "s": 24446, "text": null }, { "code": null, "e": 24534, "s": 24499, "text": " Program for Spelling checker – " }, { "code": null, "e": 24542, "s": 24534, "text": "Python3" }, { "code": "from textblob import TextBlob a = \"cmputr\" # incorrect spellingprint(\"original text: \"+str(a)) b = TextBlob(a) # prints the corrected spellingprint(\"corrected text: \"+str(b.correct()))", "e": 24737, "s": 24542, "text": null }, { "code": null, "e": 24747, "s": 24737, "text": "Output: " }, { "code": null, "e": 24797, "s": 24747, "text": "original text: cmputr\ncorrected text: computer\n\n\n" }, { "code": null, "e": 24849, "s": 24799, "text": "You can install this library as below:Using pip: " }, { "code": null, "e": 24879, "s": 24849, "text": "pip install pyspellchecker\n\n\n" }, { "code": null, "e": 24902, "s": 24879, "text": "In Jupyter Notebook: " }, { "code": null, "e": 24910, "s": 24902, "text": "Python3" }, { "code": "import sys!{sys.executable} - m pip install pyspellchecker", "e": 24969, "s": 24910, "text": null }, { "code": null, "e": 25021, "s": 24969, "text": " Spelling Checker program using pyspellchecker – " }, { "code": null, "e": 25029, "s": 25021, "text": "Python3" }, { "code": "from spellchecker import SpellChecker spell = SpellChecker() # find those words that may be misspelledmisspelled = spell.unknown([\"cmputr\", \"watr\", \"study\", \"wrte\"]) for word in misspelled: # Get the one `most likely` answer print(spell.correction(word)) # Get a list of `likely` options print(spell.candidates(word))", "e": 25360, "s": 25029, "text": null }, { "code": null, "e": 25370, "s": 25360, "text": "Output: " }, { "code": null, "e": 25564, "s": 25370, "text": "computer\n{'caput', 'caputs', 'compute', 'computor', 'impute', 'computer'}\nwater\n{'water', 'watt', 'warr', 'wart', 'war', 'wath', 'wat'}\nwrite\n{'wroe', 'arte', 'wre', 'rte', 'wrote', 'write'}\n\n\n" }, { "code": null, "e": 25838, "s": 25564, "text": "To achieve the best quality while making spelling corrections dictionary-based methods are not enough. You need to consider the word surroundings. JamSpell is a python spell checking library based on a language model. It makes different corrections for a different context." }, { "code": null, "e": 25855, "s": 25838, "text": "1) Install swig3" }, { "code": null, "e": 25931, "s": 25855, "text": "apt-get install swig3.0 # for linux\nbrew install swig@3 # for mac\n\n" }, { "code": null, "e": 25951, "s": 25931, "text": "2) Install jamspell" }, { "code": null, "e": 25974, "s": 25951, "text": "pip install jamspell\n\n" }, { "code": null, "e": 26021, "s": 25974, "text": "3) Download a language model for your language" }, { "code": null, "e": 26029, "s": 26021, "text": "Python3" }, { "code": "# Create a correctorcorrector = jamspell.TSpellCorrector() # Load Language model -# argument is a downloaded model file pathcorrector.LoadLangModel('Downloads/en_model.bin') # To fix text automatically run FixFragment:print(corrector.FixFragment('I am the begt spell cherken!')) # To get a list of possible candidates# pass a splitted sentence, and a word positionprint(corrector.GetCandidates(['i', 'am', 'the', 'begt', 'spell', 'cherken'], 3)) print(corrector.GetCandidates(['i', 'am', 'the', 'begt', 'spell', 'cherken'], 5))", "e": 26557, "s": 26029, "text": null }, { "code": null, "e": 26565, "s": 26557, "text": "Output:" }, { "code": null, "e": 26711, "s": 26565, "text": "u'I am the best spell checker!'\n(u'best', u'beat', u'belt', u'bet', u'bent')\n(u'checker', u'chicken', u'checked', u'wherein', u'coherent', ...)\n\n" }, { "code": null, "e": 26718, "s": 26711, "text": "filipp" }, { "code": null, "e": 26725, "s": 26718, "text": "Python" }, { "code": null, "e": 26741, "s": 26725, "text": "Python Programs" }, { "code": null, "e": 26839, "s": 26741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26848, "s": 26839, "text": "Comments" }, { "code": null, "e": 26861, "s": 26848, "text": "Old Comments" }, { "code": null, "e": 26879, "s": 26861, "text": "Python Dictionary" }, { "code": null, "e": 26914, "s": 26879, "text": "Read a file line by line in Python" }, { "code": null, "e": 26946, "s": 26914, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26988, "s": 26946, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27031, "s": 26988, "text": "Python program to convert a list to string" }, { "code": null, "e": 27074, "s": 27031, "text": "Python program to convert a list to string" }, { "code": null, "e": 27096, "s": 27074, "text": "Defaultdict in Python" }, { "code": null, "e": 27135, "s": 27096, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27181, "s": 27135, "text": "Python | Split string into list of characters" } ]
tar - Unix, Linux Command
Operations: [-]A --catenate --concatenate [-]c --create [-]d --diff --compare [-]r --append [-]t --list [-]u --update [-]x --extract --get --delete Common Options: -C, --directory DIR -f, --file F -j, --bzip2 -p, --preserve-permissions -v, --verbose -z, --gzip All Options: [ --atime-preserve ] [ -b, --blocking-factor N ] [ -B, --read-full-records ] [ --backup BACKUP-TYPE ] [ --block-compress ] [ -C, --directory DIR ] [ --check-links ] [ --checkpoint ] [ -f, --file [HOSTNAME:]F ] [ -F, --info-script F --new-volume-script F ] [ --force-local ] [ --format FORMAT ] [ -g, --listed-incremental F ] [ -G, --incremental ] [ --group GROUP ] [ -h, --dereference ] [ --help ] [ -i, --ignore-zeros ] [ --ignore-case ] [ --ignore-failed-read ] [ --index-file FILE ] [ -j, --bzip2 ] [ -k, --keep-old-files ] [ -K, --starting-file F ] [ --keep-newer-files ] [ -l, --one-file-system ] [ -L, --tape-length N ] [ -m, --touch, --modification-time ] [ -M, --multi-volume ] [ --mode PERMISSIONS ] [ -N, --after-date DATE, --newer DATE ] [ --newer-mtime DATE ] [ --no-anchored ] [ --no-ignore-case ] [ --no-recursion ] [ --no-same-permissions ] [ --no-wildcards ] [ --no-wildcards-match-slash ] [ --null ] [ --numeric-owner ] [ -o, --old-archive, --portability, --no-same-owner ] [ -O, --to-stdout ] [ --occurrence[=NUMBER] ] [ --overwrite ] [ --overwrite-dir ] [ --owner USER ] [ -p, --same-permissions, --preserve-permissions ] [ -P, --absolute-names ] [ --pax-option KEYWORD-LIST ] [ --posix ] [ --preserve ] [ --acls ] [ --selinux ] [ --xattrs ] [ --no-acls ] [ --no-selinux ] [ --no-xattrs ] [ -R, --block-number ] [ --record-size SIZE ] [ --recursion ] [ --recursive-unlink ] [ --remove-files ] [ --rmt-command CMD ] [ --rsh-command CMD ] [ -s, --same-order, --preserve-order ] [ -S, --sparse ] [ --same-owner ] [ --show-defaults ] [ --show-omitted-dirs ] [ --strip-components NUMBER, --strip-path NUMBER (1) ] [ --suffix SUFFIX ] [ -T, --files-from F ] [ --totals ] [ -U, --unlink-first ] [ --use-compress-program PROG ] [ --utc ] [ -v, --verbose ] [ -V, --label NAME ] [ --version ] [ --volno-file F ] [ -w, --interactive, --confirmation ] [ -W, --verify ] [ --wildcards ] [ --wildcards-match-slash ] [ --exclude PATTERN ] [ -X, --exclude-from FILE ] [ -Z, --compress, --uncompress ] [ -z, --gzip, --gunzip, --ungzip ] [ -[0-7][lmh] ] (1) tar-1.14 uses --strip-path, tar-1.14.90+ uses --strip-components v7 - Unix V7 oldgnu - GNU tar <=1.12 gnu - GNU tar 1.13 ustar - POSIX.1-1988 posix - POSIX.1-2001 (1) tar-1.14 uses --strip-path, tar-1.14.90+ uses --strip-components Debian Linux http://www.debian.org/ Mike Frysinger <[email protected]> Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10591, "s": 10577, "text": "\nOperations: " }, { "code": null, "e": 10736, "s": 10591, "text": "[-]A --catenate --concatenate \n[-]c --create \n[-]d --diff --compare \n[-]r --append \n[-]t --list \n[-]u --update \n[-]x --extract --get \n--delete \n" }, { "code": null, "e": 10754, "s": 10736, "text": "\nCommon Options: " }, { "code": null, "e": 10858, "s": 10754, "text": "-C, --directory DIR \n-f, --file F \n-j, --bzip2 \n-p, --preserve-permissions \n-v, --verbose \n-z, --gzip \n" }, { "code": null, "e": 12928, "s": 10858, "text": "\nAll Options: \n[\n--atime-preserve ]\n[\n-b, --blocking-factor N ]\n[\n-B, --read-full-records ]\n[\n--backup BACKUP-TYPE ]\n[\n--block-compress ]\n[\n-C, --directory DIR ]\n[\n--check-links ]\n[\n--checkpoint ]\n[\n-f, --file [HOSTNAME:]F ]\n[\n-F, --info-script F --new-volume-script F ]\n[\n--force-local ]\n[\n--format FORMAT ]\n[\n-g, --listed-incremental F ]\n[\n-G, --incremental ]\n[\n--group GROUP ]\n[\n-h, --dereference ]\n[\n--help ]\n[\n-i, --ignore-zeros ]\n[\n--ignore-case ]\n[\n--ignore-failed-read ]\n[\n--index-file FILE ]\n[\n-j, --bzip2 ]\n[\n-k, --keep-old-files ]\n[\n-K, --starting-file F ]\n[\n--keep-newer-files ]\n[\n-l, --one-file-system ]\n[\n-L, --tape-length N ]\n[\n-m, --touch, --modification-time ]\n[\n-M, --multi-volume ]\n[\n--mode PERMISSIONS ]\n[\n-N, --after-date DATE, --newer DATE ]\n[\n--newer-mtime DATE ]\n[\n--no-anchored ]\n[\n--no-ignore-case ]\n[\n--no-recursion ]\n[\n--no-same-permissions ]\n[\n--no-wildcards ]\n[\n--no-wildcards-match-slash ]\n[\n--null ]\n[\n--numeric-owner ]\n[\n-o, --old-archive, --portability, --no-same-owner ]\n[\n-O, --to-stdout ]\n[\n--occurrence[=NUMBER] ]\n[\n--overwrite ]\n[\n--overwrite-dir ]\n[\n--owner USER ]\n[\n-p, --same-permissions, --preserve-permissions ]\n[\n-P, --absolute-names ]\n[\n--pax-option KEYWORD-LIST ]\n[\n--posix ]\n[\n--preserve ]\n[\n--acls ]\n[\n--selinux ]\n[\n--xattrs ]\n[\n--no-acls ]\n[\n--no-selinux ]\n[\n--no-xattrs ]\n[\n-R, --block-number ]\n[\n--record-size SIZE ]\n[\n--recursion ]\n[\n--recursive-unlink ]\n[\n--remove-files ]\n[\n--rmt-command CMD ]\n[\n--rsh-command CMD ]\n[\n-s, --same-order, --preserve-order ]\n[\n-S, --sparse ]\n[\n--same-owner ]\n[\n--show-defaults ]\n[\n--show-omitted-dirs ]\n[\n--strip-components NUMBER, --strip-path NUMBER (1) ]\n[\n--suffix SUFFIX ]\n[\n-T, --files-from F ]\n[\n--totals ]\n[\n-U, --unlink-first ]\n[\n--use-compress-program PROG ]\n[\n--utc ]\n[\n-v, --verbose ]\n[\n-V, --label NAME ]\n[\n--version ]\n[\n--volno-file F ]\n[\n-w, --interactive, --confirmation ]\n[\n-W, --verify ]\n[\n--wildcards ]\n[\n--wildcards-match-slash ]\n[\n--exclude PATTERN ]\n[\n-X, --exclude-from FILE ]\n[\n-Z, --compress, --uncompress ]\n[\n-z, --gzip, --gunzip, --ungzip ]\n[\n-[0-7][lmh] ]\n" }, { "code": null, "e": 12999, "s": 12928, "text": "\n(1) tar-1.14 uses --strip-path, tar-1.14.90+ uses --strip-components\n" }, { "code": null, "e": 13098, "s": 12999, "text": "v7 - Unix V7\noldgnu - GNU tar <=1.12\ngnu - GNU tar 1.13\nustar - POSIX.1-1988\nposix - POSIX.1-2001\n" }, { "code": null, "e": 13169, "s": 13098, "text": "\n(1) tar-1.14 uses --strip-path, tar-1.14.90+ uses --strip-components\n" }, { "code": null, "e": 13241, "s": 13169, "text": "Debian Linux http://www.debian.org/\nMike Frysinger <[email protected]>\n" }, { "code": null, "e": 13258, "s": 13241, "text": "\nAdvertisements\n" }, { "code": null, "e": 13293, "s": 13258, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 13321, "s": 13293, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 13355, "s": 13321, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13372, "s": 13355, "text": " Frahaan Hussain" }, { "code": null, "e": 13405, "s": 13372, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 13416, "s": 13405, "text": " Pradeep D" }, { "code": null, "e": 13451, "s": 13416, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13467, "s": 13451, "text": " Musab Zayadneh" }, { "code": null, "e": 13500, "s": 13467, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 13512, "s": 13500, "text": " GUHARAJANM" }, { "code": null, "e": 13544, "s": 13512, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 13552, "s": 13544, "text": " Uplatz" }, { "code": null, "e": 13559, "s": 13552, "text": " Print" }, { "code": null, "e": 13570, "s": 13559, "text": " Add Notes" } ]
exit(), abort() and assert() in C/C++
The function exit() is used to terminate the calling function immediately without executing further processes. As exit() function calls, it terminates processes. It is declared in “stdlib.h” header file. It does not return anything. Here is the syntax of exit() in C language, void exit(int status_value); Here, status_value − The value which is returned to parent process. Here is an example of exit() in C language, Live Demo #include <stdio.h> #include <stdlib.h> int main() { int x = 10; printf("The value of x : %d\n", x); exit(0); printf("Calling of exit()"); return 0; } The value of x : 10 In the above program, a variable ‘x’ is initialized with a value. The value of variable is printed and exit() function is called. As exit() is called, it exits the execution immediately and it does not print the printf(). The calling of exit() is as follows − int x = 10; printf("The value of x : %d\n", x); exit(0) The function abort() terminates the execution abnormally. It is suggested to not to use this function for termination. It is declared in “stdlib.h” header file. Here is the syntax of abort() in C language, void abort(void); Here is an example of abort() in C language, Live Demo #include <stdio.h> #include <stdlib.h> int main() { int a = 15; printf("The value of a : %d\n", a); abort(); printf("Calling of abort()"); return 0; } Here is the output, The value of a : 15 In the above program, a variable ‘a’ is initialized with the value and printed. As the abort() is called, it terminates the execution immediately but abnormally. The calling of abort() is as follows. int a = 15; printf("The value of a : %d\n", a); abort(); The function assert() is declared in “assert.h” header file. It evaluates the expressions given as argument. If expression is true, it does nothing. If expression is false, it abort the execution. Here is the syntax of assert() in C language, void assert(int exp); Here. exp − The expression you want to evaluate. Here is an example of assert() in C language, Live Demo #include <stdio.h> #include <assert.h> int main() { int a = 15; printf("The value of a : %d\n", a); assert(a!=15); printf("Calling of assert()"); return 0; } The value of a : 15 main: main.c:9: main: Assertion `a!=15' failed. In the above program, a variable ‘a’ is initialized with a value. The value of variable is printed and assert() function is called. As assert() is called, it evaluates the expression that ‘a’ is not equal to 15 which is false that is why it aborts the execution and shows an error. int a = 15; printf("The value of a : %d\n", a); assert(a!=15);
[ { "code": null, "e": 1295, "s": 1062, "text": "The function exit() is used to terminate the calling function immediately without executing further processes. As exit() function calls, it terminates processes. It is declared in “stdlib.h” header file. It does not return anything." }, { "code": null, "e": 1339, "s": 1295, "text": "Here is the syntax of exit() in C language," }, { "code": null, "e": 1368, "s": 1339, "text": "void exit(int status_value);" }, { "code": null, "e": 1374, "s": 1368, "text": "Here," }, { "code": null, "e": 1436, "s": 1374, "text": "status_value − The value which is returned to parent process." }, { "code": null, "e": 1480, "s": 1436, "text": "Here is an example of exit() in C language," }, { "code": null, "e": 1491, "s": 1480, "text": " Live Demo" }, { "code": null, "e": 1656, "s": 1491, "text": "#include <stdio.h>\n#include <stdlib.h>\nint main() {\n int x = 10;\n printf(\"The value of x : %d\\n\", x);\n exit(0);\n printf(\"Calling of exit()\");\n return 0;\n}" }, { "code": null, "e": 1676, "s": 1656, "text": "The value of x : 10" }, { "code": null, "e": 1936, "s": 1676, "text": "In the above program, a variable ‘x’ is initialized with a value. The value of variable is printed and exit() function is called. As exit() is called, it exits the execution immediately and it does not print the printf(). The calling of exit() is as follows −" }, { "code": null, "e": 1992, "s": 1936, "text": "int x = 10;\nprintf(\"The value of x : %d\\n\", x);\nexit(0)" }, { "code": null, "e": 2153, "s": 1992, "text": "The function abort() terminates the execution abnormally. It is suggested to not to use this function for termination. It is declared in “stdlib.h” header file." }, { "code": null, "e": 2198, "s": 2153, "text": "Here is the syntax of abort() in C language," }, { "code": null, "e": 2216, "s": 2198, "text": "void abort(void);" }, { "code": null, "e": 2261, "s": 2216, "text": "Here is an example of abort() in C language," }, { "code": null, "e": 2272, "s": 2261, "text": " Live Demo" }, { "code": null, "e": 2438, "s": 2272, "text": "#include <stdio.h>\n#include <stdlib.h>\nint main() {\n int a = 15;\n printf(\"The value of a : %d\\n\", a);\n abort();\n printf(\"Calling of abort()\");\n return 0;\n}" }, { "code": null, "e": 2458, "s": 2438, "text": "Here is the output," }, { "code": null, "e": 2478, "s": 2458, "text": "The value of a : 15" }, { "code": null, "e": 2678, "s": 2478, "text": "In the above program, a variable ‘a’ is initialized with the value and printed. As the abort() is called, it terminates the execution immediately but abnormally. The calling of abort() is as follows." }, { "code": null, "e": 2735, "s": 2678, "text": "int a = 15;\nprintf(\"The value of a : %d\\n\", a);\nabort();" }, { "code": null, "e": 2932, "s": 2735, "text": "The function assert() is declared in “assert.h” header file. It evaluates the expressions given as argument. If expression is true, it does nothing. If expression is false, it abort the execution." }, { "code": null, "e": 2978, "s": 2932, "text": "Here is the syntax of assert() in C language," }, { "code": null, "e": 3000, "s": 2978, "text": "void assert(int exp);" }, { "code": null, "e": 3006, "s": 3000, "text": "Here." }, { "code": null, "e": 3049, "s": 3006, "text": "exp − The expression you want to evaluate." }, { "code": null, "e": 3095, "s": 3049, "text": "Here is an example of assert() in C language," }, { "code": null, "e": 3106, "s": 3095, "text": " Live Demo" }, { "code": null, "e": 3279, "s": 3106, "text": "#include <stdio.h>\n#include <assert.h>\nint main() {\n int a = 15;\n printf(\"The value of a : %d\\n\", a);\n assert(a!=15);\n printf(\"Calling of assert()\");\n return 0;\n}" }, { "code": null, "e": 3347, "s": 3279, "text": "The value of a : 15\nmain: main.c:9: main: Assertion `a!=15' failed." }, { "code": null, "e": 3629, "s": 3347, "text": "In the above program, a variable ‘a’ is initialized with a value. The value of variable is printed and assert() function is called. As assert() is called, it evaluates the expression that ‘a’ is not equal to 15 which is false that is why it aborts the execution and shows an error." }, { "code": null, "e": 3692, "s": 3629, "text": "int a = 15;\nprintf(\"The value of a : %d\\n\", a);\nassert(a!=15);" } ]
Java - atan2() Method
The method converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta. double atan2(double y, double x) Here is the detail of parameters − X − X co-ordinate in double data type. X − X co-ordinate in double data type. Y − Y co-ordinate in double data type. Y − Y co-ordinate in double data type. This method returns theta from polar coordinate (r, theta). This method returns theta from polar coordinate (r, theta). public class Test { public static void main(String args[]) { double x = 45.0; double y = 30.0; System.out.println( Math.atan2(x, y) ); } } This will produce the following result − 0.982793723247329 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2478, "s": 2377, "text": "The method converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta." }, { "code": null, "e": 2512, "s": 2478, "text": "double atan2(double y, double x)\n" }, { "code": null, "e": 2547, "s": 2512, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2586, "s": 2547, "text": "X − X co-ordinate in double data type." }, { "code": null, "e": 2625, "s": 2586, "text": "X − X co-ordinate in double data type." }, { "code": null, "e": 2664, "s": 2625, "text": "Y − Y co-ordinate in double data type." }, { "code": null, "e": 2703, "s": 2664, "text": "Y − Y co-ordinate in double data type." }, { "code": null, "e": 2764, "s": 2703, "text": "This method returns theta from polar coordinate (r, theta)." }, { "code": null, "e": 2825, "s": 2764, "text": "This method returns theta from polar coordinate (r, theta)." }, { "code": null, "e": 2991, "s": 2825, "text": "public class Test { \n\n public static void main(String args[]) {\n double x = 45.0;\n double y = 30.0;\n\n System.out.println( Math.atan2(x, y) );\n }\n}" }, { "code": null, "e": 3032, "s": 2991, "text": "This will produce the following result −" }, { "code": null, "e": 3051, "s": 3032, "text": "0.982793723247329\n" }, { "code": null, "e": 3084, "s": 3051, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3100, "s": 3084, "text": " Malhar Lathkar" }, { "code": null, "e": 3133, "s": 3100, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3149, "s": 3133, "text": " Malhar Lathkar" }, { "code": null, "e": 3184, "s": 3149, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3198, "s": 3184, "text": " Anadi Sharma" }, { "code": null, "e": 3232, "s": 3198, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3246, "s": 3232, "text": " Tushar Kale" }, { "code": null, "e": 3283, "s": 3246, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3298, "s": 3283, "text": " Monica Mittal" }, { "code": null, "e": 3331, "s": 3298, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3350, "s": 3331, "text": " Arnab Chakraborty" }, { "code": null, "e": 3357, "s": 3350, "text": " Print" }, { "code": null, "e": 3368, "s": 3357, "text": " Add Notes" } ]
How to disable the back button in android while logging out the application using Kotlin?
This example demonstrates how to disable the back button in android while logging out the application using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="16dp" tools:context=".MainActivity"> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/image" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onBackPressed() { Toast.makeText(applicationContext, "Disabled Back Press", Toast.LENGTH_SHORT).show() } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1178, "s": 1062, "text": "This example demonstrates how to disable the back button in android while logging out the application using Kotlin." }, { "code": null, "e": 1307, "s": 1178, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1372, "s": 1307, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1923, "s": 1372, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:gravity=\"center\"\n android:orientation=\"vertical\"\n android:padding=\"16dp\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:src=\"@drawable/image\" />\n</LinearLayout>" }, { "code": null, "e": 1978, "s": 1923, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 2401, "s": 1978, "text": "import android.os.Bundle\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n }\n override fun onBackPressed() {\n Toast.makeText(applicationContext, \"Disabled Back Press\", Toast.LENGTH_SHORT).show()\n }\n}" }, { "code": null, "e": 2456, "s": 2401, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3123, "s": 2456, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3471, "s": 3123, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
GATE | GATE-CS-2015 (Set 3) | Question 61 - GeeksforGeeks
07 Dec, 2021 Consider the following reservation table for a pipeline having three stages S1, S2 and S3. Time --> ----------------------------- 1 2 3 4 5 ----------------------------- S1 | X | | | | X | S2 | | X | | X | | S3 | | | X | | | The minimum average latency (MAL) is __________(A) 3(B) 2(C) 1(D) 4Answer: (A)Explanation: S1 | X | Y | | | X | Y | X | Y | | | X | Y | S2 | | X | Y | X | Y | | | X | Y | X | Y | | S3 | | | X | Y | | | | | X | Y | | | We can interleave instructions like the above pattern. Latency between X and Y is 1. Latency between first and second X is 5. The pattern repeats after that.So, MAL is (1 + 5)/2;Quiz of this Question sweetyty 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. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 1) | Question 42
[ { "code": null, "e": 24071, "s": 24043, "text": "\n07 Dec, 2021" }, { "code": null, "e": 24162, "s": 24071, "text": "Consider the following reservation table for a pipeline having three stages S1, S2 and S3." }, { "code": null, "e": 24355, "s": 24162, "text": " Time -->\n-----------------------------\n 1 2 3 4 5\n-----------------------------\nS1 | X | | | | X | \nS2 | | X | | X | |\nS3 | | | X | | |" }, { "code": null, "e": 24446, "s": 24355, "text": "The minimum average latency (MAL) is __________(A) 3(B) 2(C) 1(D) 4Answer: (A)Explanation:" }, { "code": null, "e": 24606, "s": 24446, "text": "S1 | X | Y | | | X | Y | X | Y | | | X | Y |\nS2 | | X | Y | X | Y | | | X | Y | X | Y | |\nS3 | | | X | Y | | | | | X | Y | | |\n" }, { "code": null, "e": 24661, "s": 24606, "text": "We can interleave instructions like the above pattern." }, { "code": null, "e": 24691, "s": 24661, "text": "Latency between X and Y is 1." }, { "code": null, "e": 24732, "s": 24691, "text": "Latency between first and second X is 5." }, { "code": null, "e": 24806, "s": 24732, "text": "The pattern repeats after that.So, MAL is (1 + 5)/2;Quiz of this Question" }, { "code": null, "e": 24815, "s": 24806, "text": "sweetyty" }, { "code": null, "e": 24836, "s": 24815, "text": "GATE-CS-2015 (Set 3)" }, { "code": null, "e": 24862, "s": 24836, "text": "GATE-GATE-CS-2015 (Set 3)" }, { "code": null, "e": 24867, "s": 24862, "text": "GATE" }, { "code": null, "e": 24965, "s": 24867, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24974, "s": 24965, "text": "Comments" }, { "code": null, "e": 24987, "s": 24974, "text": "Old Comments" }, { "code": null, "e": 25029, "s": 24987, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25071, "s": 25029, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25105, "s": 25071, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 25147, "s": 25105, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25181, "s": 25147, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25223, "s": 25181, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25277, "s": 25223, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 25319, "s": 25277, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 25352, "s": 25319, "text": "GATE | GATE-CS-2004 | Question 3" } ]
Difference Between Bubble Sort and Selection Sort
In this post, we will understand the difference between Bubble Sort and Selection Sort It is a simple sorting algorithm. It is a simple sorting algorithm. It iterates through the list, and compares adjacent pairs of elements to sort them. It iterates through the list, and compares adjacent pairs of elements to sort them. Based on the adjacent elements, swaps are made. Based on the adjacent elements, swaps are made. It is efficient in comparison to selection sort. It is efficient in comparison to selection sort. It is slower in comparison to selection sort. It is slower in comparison to selection sort. It uses item exchanging to swap elements. It uses item exchanging to swap elements. The elements are repeatedly swapped until all the elements are in the right order. The elements are repeatedly swapped until all the elements are in the right order. Following is the Bubble Sort Algorithm begin BubbleSort(list) for all elements of list if list[i] > list[i+1] swap(list[i], list[i+1]) end if end for return list end BubbleSort First, the minimum or the maximum number from the list is obtained. First, the minimum or the maximum number from the list is obtained. The list is sorted in ascending or descending order. The list is sorted in ascending or descending order. It selects the minimum or maximum element from unsorted sub-array and puts it in the next position of the sorted sub-array. It selects the minimum or maximum element from unsorted sub-array and puts it in the next position of the sorted sub-array. It is considered as an unstable sorting algorithm. It is considered as an unstable sorting algorithm. The time complexity in all cases is O(n squared). The time complexity in all cases is O(n squared). It is less efficient in comparison to insertion sort. It is less efficient in comparison to insertion sort. The number of comparisons made during iterations is more than the element swapping that is done. The number of comparisons made during iterations is more than the element swapping that is done. The location of every element in the list is previously known. The location of every element in the list is previously known. This means the user only searches for the element that needs to be inserted at the specific position. This means the user only searches for the element that needs to be inserted at the specific position. It is efficient compared to the bubble sort It is efficient compared to the bubble sort It is quick in comparison to bubble sort. It is quick in comparison to bubble sort. It uses item selection. It uses item selection. Following is the Selection Sort Algorithm Step 1 - Set MIN to location 0 Step 2 - Search the minimum element in the list Step 3 - Swap with value at location MIN Step 4 - Increment MIN to point to next element Step 5 - Repeat until list is sorted
[ { "code": null, "e": 1149, "s": 1062, "text": "In this post, we will understand the difference between Bubble Sort and Selection Sort" }, { "code": null, "e": 1183, "s": 1149, "text": "It is a simple sorting algorithm." }, { "code": null, "e": 1217, "s": 1183, "text": "It is a simple sorting algorithm." }, { "code": null, "e": 1301, "s": 1217, "text": "It iterates through the list, and compares adjacent pairs of elements to sort them." }, { "code": null, "e": 1385, "s": 1301, "text": "It iterates through the list, and compares adjacent pairs of elements to sort them." }, { "code": null, "e": 1433, "s": 1385, "text": "Based on the adjacent elements, swaps are made." }, { "code": null, "e": 1481, "s": 1433, "text": "Based on the adjacent elements, swaps are made." }, { "code": null, "e": 1530, "s": 1481, "text": "It is efficient in comparison to selection sort." }, { "code": null, "e": 1579, "s": 1530, "text": "It is efficient in comparison to selection sort." }, { "code": null, "e": 1625, "s": 1579, "text": "It is slower in comparison to selection sort." }, { "code": null, "e": 1671, "s": 1625, "text": "It is slower in comparison to selection sort." }, { "code": null, "e": 1713, "s": 1671, "text": "It uses item exchanging to swap elements." }, { "code": null, "e": 1755, "s": 1713, "text": "It uses item exchanging to swap elements." }, { "code": null, "e": 1838, "s": 1755, "text": "The elements are repeatedly swapped until all the elements are in the right order." }, { "code": null, "e": 1921, "s": 1838, "text": "The elements are repeatedly swapped until all the elements are in the right order." }, { "code": null, "e": 1960, "s": 1921, "text": "Following is the Bubble Sort Algorithm" }, { "code": null, "e": 2118, "s": 1960, "text": "begin BubbleSort(list)\n for all elements of list\n if list[i] > list[i+1]\n swap(list[i], list[i+1])\nend if\nend for\n\nreturn list\n\nend BubbleSort" }, { "code": null, "e": 2186, "s": 2118, "text": "First, the minimum or the maximum number from the list is obtained." }, { "code": null, "e": 2254, "s": 2186, "text": "First, the minimum or the maximum number from the list is obtained." }, { "code": null, "e": 2307, "s": 2254, "text": "The list is sorted in ascending or descending order." }, { "code": null, "e": 2360, "s": 2307, "text": "The list is sorted in ascending or descending order." }, { "code": null, "e": 2484, "s": 2360, "text": "It selects the minimum or maximum element from unsorted sub-array and puts it in the next position of the sorted sub-array." }, { "code": null, "e": 2608, "s": 2484, "text": "It selects the minimum or maximum element from unsorted sub-array and puts it in the next position of the sorted sub-array." }, { "code": null, "e": 2659, "s": 2608, "text": "It is considered as an unstable sorting algorithm." }, { "code": null, "e": 2710, "s": 2659, "text": "It is considered as an unstable sorting algorithm." }, { "code": null, "e": 2760, "s": 2710, "text": "The time complexity in all cases is O(n squared)." }, { "code": null, "e": 2810, "s": 2760, "text": "The time complexity in all cases is O(n squared)." }, { "code": null, "e": 2864, "s": 2810, "text": "It is less efficient in comparison to insertion sort." }, { "code": null, "e": 2918, "s": 2864, "text": "It is less efficient in comparison to insertion sort." }, { "code": null, "e": 3015, "s": 2918, "text": "The number of comparisons made during iterations is more than the element swapping that is done." }, { "code": null, "e": 3112, "s": 3015, "text": "The number of comparisons made during iterations is more than the element swapping that is done." }, { "code": null, "e": 3175, "s": 3112, "text": "The location of every element in the list is previously known." }, { "code": null, "e": 3238, "s": 3175, "text": "The location of every element in the list is previously known." }, { "code": null, "e": 3340, "s": 3238, "text": "This means the user only searches for the element that needs to be inserted at the specific position." }, { "code": null, "e": 3442, "s": 3340, "text": "This means the user only searches for the element that needs to be inserted at the specific position." }, { "code": null, "e": 3486, "s": 3442, "text": "It is efficient compared to the bubble sort" }, { "code": null, "e": 3530, "s": 3486, "text": "It is efficient compared to the bubble sort" }, { "code": null, "e": 3572, "s": 3530, "text": "It is quick in comparison to bubble sort." }, { "code": null, "e": 3614, "s": 3572, "text": "It is quick in comparison to bubble sort." }, { "code": null, "e": 3638, "s": 3614, "text": "It uses item selection." }, { "code": null, "e": 3662, "s": 3638, "text": "It uses item selection." }, { "code": null, "e": 3704, "s": 3662, "text": "Following is the Selection Sort Algorithm" }, { "code": null, "e": 3909, "s": 3704, "text": "Step 1 - Set MIN to location 0\nStep 2 - Search the minimum element in the list\nStep 3 - Swap with value at location MIN\nStep 4 - Increment MIN to point to next element\nStep 5 - Repeat until list is sorted" } ]
How can grid plot in Bokeh library be created with Python?
Bokeh is a Python package that helps in data visualization. It is an open source project. Bokeh renders its plot using HTML and JavaScript. This indicates that it is useful while working with web-based dashboards. Bokeh converts the data source into a JSON file. This file is used as an input to BokehJS, which is a JavaScript library. This BokehJS is written in TypeScript that helps render visualization on modern browsers. Dependencies of Bokeh − Numpy Pillow Jinja2 Packaging Pyyaml Six Tornado Python−dateutil Installation of Bokeh on Windows command prompt pip3 install bokeh Installation of Bokeh on Anaconda prompt conda install bokeh import numpy as np from bokeh.plotting import figure, output_file, show N = 420 x = np.linspace(0, 14, N) y = np.linspace(0, 14, N) x1, y1 = np.meshgrid(x, y) d = np.sin(x1)*np.cos(y1) p = figure(tooltips=[("x", "$x"), ("y", "$y"), ("value", "@image")]) p.x_range.range_padding = p.y_range.range_padding = 0 p.image(image=[d], x=0, y=0, dw=11, dh=11, palette="Spectral11", level="image") p.grid.grid_line_width = 0.6 output_file("gridplot.html", title="grid plot example") show(p) The required packages are imported, and aliased. The required packages are imported, and aliased. The figure function is called along with plot width and height. The figure function is called along with plot width and height. The data is defined using NumPy library. The data is defined using NumPy library. The ‘output_file’ function is called to mention the name of the html file that will be generated. The ‘output_file’ function is called to mention the name of the html file that will be generated. The ‘image’ function present in Bokeh is called, along with data. The ‘image’ function present in Bokeh is called, along with data. The ‘show’ function is used to display the plot. The ‘show’ function is used to display the plot.
[ { "code": null, "e": 1276, "s": 1062, "text": "Bokeh is a Python package that helps in data visualization. It is an open source project. Bokeh renders its plot using HTML and JavaScript. This indicates that it is useful while working with web-based dashboards." }, { "code": null, "e": 1488, "s": 1276, "text": "Bokeh converts the data source into a JSON file. This file is used as an input to BokehJS, which is a JavaScript library. This BokehJS is written in TypeScript that helps render visualization on modern browsers." }, { "code": null, "e": 1512, "s": 1488, "text": "Dependencies of Bokeh −" }, { "code": null, "e": 1577, "s": 1512, "text": "Numpy\nPillow\nJinja2\nPackaging\nPyyaml\nSix\nTornado\nPython−dateutil" }, { "code": null, "e": 1625, "s": 1577, "text": "Installation of Bokeh on Windows command prompt" }, { "code": null, "e": 1645, "s": 1625, "text": "pip3 install bokeh\n" }, { "code": null, "e": 1686, "s": 1645, "text": "Installation of Bokeh on Anaconda prompt" }, { "code": null, "e": 1706, "s": 1686, "text": "conda install bokeh" }, { "code": null, "e": 2193, "s": 1706, "text": "import numpy as np\n\nfrom bokeh.plotting import figure, output_file, show\n\nN = 420\nx = np.linspace(0, 14, N)\ny = np.linspace(0, 14, N)\nx1, y1 = np.meshgrid(x, y)\nd = np.sin(x1)*np.cos(y1)\n\np = figure(tooltips=[(\"x\", \"$x\"), (\"y\", \"$y\"), (\"value\", \"@image\")])\np.x_range.range_padding = p.y_range.range_padding = 0\n\np.image(image=[d], x=0, y=0, dw=11, dh=11, palette=\"Spectral11\", level=\"image\")\np.grid.grid_line_width = 0.6\n\noutput_file(\"gridplot.html\", title=\"grid plot example\")\n\nshow(p)" }, { "code": null, "e": 2242, "s": 2193, "text": "The required packages are imported, and aliased." }, { "code": null, "e": 2291, "s": 2242, "text": "The required packages are imported, and aliased." }, { "code": null, "e": 2355, "s": 2291, "text": "The figure function is called along with plot width and height." }, { "code": null, "e": 2419, "s": 2355, "text": "The figure function is called along with plot width and height." }, { "code": null, "e": 2460, "s": 2419, "text": "The data is defined using NumPy library." }, { "code": null, "e": 2501, "s": 2460, "text": "The data is defined using NumPy library." }, { "code": null, "e": 2599, "s": 2501, "text": "The ‘output_file’ function is called to mention the name of the html file that will be generated." }, { "code": null, "e": 2697, "s": 2599, "text": "The ‘output_file’ function is called to mention the name of the html file that will be generated." }, { "code": null, "e": 2763, "s": 2697, "text": "The ‘image’ function present in Bokeh is called, along with data." }, { "code": null, "e": 2829, "s": 2763, "text": "The ‘image’ function present in Bokeh is called, along with data." }, { "code": null, "e": 2878, "s": 2829, "text": "The ‘show’ function is used to display the plot." }, { "code": null, "e": 2927, "s": 2878, "text": "The ‘show’ function is used to display the plot." } ]
wxPython - Notebook Class
wxPython class library contains various ‘book’ control. A book control allows the user to switch between various panels in a frame. This is especially useful when a large amount of data is to be presented. Book classes are inherited from wx.BookCtrlBase class. The following type of book controls are available − wx.Notebook wx.Choicebook wx.Listbook wx.Treebook wx.Notebook widget presents a tabbed control. One Notebook object in a frame has one or more tabs (called Pages), each of them having a panel showing the layout of controls. The user can switch between pages by clicking on the respective tab title. Notebook class constructor takes familiar parameters as the following − wx.Notebook(parent, id, pos, size, style) The following style parameters are available for customization of the widget − wx.NB_TOP Places tabs on the top side wx.NB_LEFT Places tabs on the left side wx.NB_RIGHT Places tabs on the right side wx.NB_BOTTOM Places tabs under the notebook pages instead of above the notebook pages wx.NB_FIXEDWIDTH All tabs will have the same width wx.NB_MULTILINE There can be several rows of tabs Member functions of Notebook class − OnSelChange() Handler function called when the page selection is changed SetPadding() Sets the amount space around each page's icon and label, in pixels GetSelection() Returns the currently selected page SetSelection() Sets the selection to the given page, returning the previous selection AddPage() Adds a new page DeletePage() Deletes a page of given index InsertPage() Inserts a new tab at the given index RemovePage() Removes the page without deleting Event binders defined for this class are − EVT_NOTEBOOK_PAGE_CHANGED() The page selection was changed EVT_NOTEBOOK_PAGE_CHANGING() The page selection is about to be changed The following example deploys a Notebook control in a top level frame. nb = wx.Notebook(self) Two classes based on wx.Panel are designed. The first, puts a multi-line TextCtrl in it. class MyPanel1(wx.Panel): def __init__(self, parent): super(MyPanel1, self).__init__(parent) text = wx.TextCtrl(self, style = wx.TE_MULTILINE, size = (250,150)) The second, shows a RadioBox having three radio buttons. class MyPanel2(wx.Panel): def __init__(self, parent): super(MyPanel2, self).__init__(parent) lblList = ['Value X', 'Value Y', 'Value Z'] rbox = wx.RadioBox(self, label = 'RadioBox', pos = (25,10), choices = lblList, majorDimension = 1, style = wx.RA_SPECIFY_ROWS) Objects of these two panel classes are added as pages in Notebook on the top level frame. nb.AddPage(MyPanel1(nb),"Editor") nb.AddPage(MyPanel2(nb),"RadioButtons") The complete code is as follows − import wx class MyDialog(wx.Dialog): def __init__(self, parent, title): super(MyDialog, self).__init__(parent, title = title, size = (250,150)) panel = wx.Panel(self) self.btn = wx.Button(panel, wx.ID_OK, label = "ok", size = (50,20), pos = (75,50)) class Mywin(wx.Frame): def __init__(self, parent, title): super(Mywin, self).__init__(parent, title = title, size = (250,150)) self.InitUI() def InitUI(self): nb = wx.Notebook(self) nb.AddPage(MyPanel1(nb),"Editor") nb.AddPage(MyPanel2(nb),"RadioButtons") self.Centre() self.Show(True) class MyPanel1(wx.Panel): def __init__(self, parent): super(MyPanel1, self).__init__(parent) text = wx.TextCtrl(self, style = wx.TE_MULTILINE, size = (250,150)) class MyPanel2(wx.Panel): def __init__(self, parent): super(MyPanel2, self).__init__(parent) lblList = ['Value X', 'Value Y', 'Value Z'] rbox = wx.RadioBox(self, label = 'RadioBox', pos = (25,10), choices = lblList, majorDimension = 1, style = wx.RA_SPECIFY_ROWS) ex = wx.App() Mywin(None,'NoteBook demo') ex.MainLoop() The above code produces the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2088, "s": 1882, "text": "wxPython class library contains various ‘book’ control. A book control allows the user to switch between various panels in a frame. This is especially useful when a large amount of data is to be presented." }, { "code": null, "e": 2195, "s": 2088, "text": "Book classes are inherited from wx.BookCtrlBase class. The following type of book controls are available −" }, { "code": null, "e": 2207, "s": 2195, "text": "wx.Notebook" }, { "code": null, "e": 2221, "s": 2207, "text": "wx.Choicebook" }, { "code": null, "e": 2233, "s": 2221, "text": "wx.Listbook" }, { "code": null, "e": 2245, "s": 2233, "text": "wx.Treebook" }, { "code": null, "e": 2494, "s": 2245, "text": "wx.Notebook widget presents a tabbed control. One Notebook object in a frame has one or more tabs (called Pages), each of them having a panel showing the layout of controls. The user can switch between pages by clicking on the respective tab title." }, { "code": null, "e": 2566, "s": 2494, "text": "Notebook class constructor takes familiar parameters as the following −" }, { "code": null, "e": 2609, "s": 2566, "text": "wx.Notebook(parent, id, pos, size, style)\n" }, { "code": null, "e": 2688, "s": 2609, "text": "The following style parameters are available for customization of the widget −" }, { "code": null, "e": 2698, "s": 2688, "text": "wx.NB_TOP" }, { "code": null, "e": 2726, "s": 2698, "text": "Places tabs on the top side" }, { "code": null, "e": 2737, "s": 2726, "text": "wx.NB_LEFT" }, { "code": null, "e": 2766, "s": 2737, "text": "Places tabs on the left side" }, { "code": null, "e": 2778, "s": 2766, "text": "wx.NB_RIGHT" }, { "code": null, "e": 2808, "s": 2778, "text": "Places tabs on the right side" }, { "code": null, "e": 2821, "s": 2808, "text": "wx.NB_BOTTOM" }, { "code": null, "e": 2894, "s": 2821, "text": "Places tabs under the notebook pages instead of above the notebook pages" }, { "code": null, "e": 2911, "s": 2894, "text": "wx.NB_FIXEDWIDTH" }, { "code": null, "e": 2945, "s": 2911, "text": "All tabs will have the same width" }, { "code": null, "e": 2961, "s": 2945, "text": "wx.NB_MULTILINE" }, { "code": null, "e": 2995, "s": 2961, "text": "There can be several rows of tabs" }, { "code": null, "e": 3032, "s": 2995, "text": "Member functions of Notebook class −" }, { "code": null, "e": 3046, "s": 3032, "text": "OnSelChange()" }, { "code": null, "e": 3105, "s": 3046, "text": "Handler function called when the page selection is changed" }, { "code": null, "e": 3118, "s": 3105, "text": "SetPadding()" }, { "code": null, "e": 3185, "s": 3118, "text": "Sets the amount space around each page's icon and label, in pixels" }, { "code": null, "e": 3200, "s": 3185, "text": "GetSelection()" }, { "code": null, "e": 3236, "s": 3200, "text": "Returns the currently selected page" }, { "code": null, "e": 3251, "s": 3236, "text": "SetSelection()" }, { "code": null, "e": 3322, "s": 3251, "text": "Sets the selection to the given page, returning the previous selection" }, { "code": null, "e": 3332, "s": 3322, "text": "AddPage()" }, { "code": null, "e": 3348, "s": 3332, "text": "Adds a new page" }, { "code": null, "e": 3361, "s": 3348, "text": "DeletePage()" }, { "code": null, "e": 3391, "s": 3361, "text": "Deletes a page of given index" }, { "code": null, "e": 3404, "s": 3391, "text": "InsertPage()" }, { "code": null, "e": 3441, "s": 3404, "text": "Inserts a new tab at the given index" }, { "code": null, "e": 3454, "s": 3441, "text": "RemovePage()" }, { "code": null, "e": 3488, "s": 3454, "text": "Removes the page without deleting" }, { "code": null, "e": 3531, "s": 3488, "text": "Event binders defined for this class are −" }, { "code": null, "e": 3559, "s": 3531, "text": "EVT_NOTEBOOK_PAGE_CHANGED()" }, { "code": null, "e": 3590, "s": 3559, "text": "The page selection was changed" }, { "code": null, "e": 3619, "s": 3590, "text": "EVT_NOTEBOOK_PAGE_CHANGING()" }, { "code": null, "e": 3661, "s": 3619, "text": "The page selection is about to be changed" }, { "code": null, "e": 3732, "s": 3661, "text": "The following example deploys a Notebook control in a top level frame." }, { "code": null, "e": 3757, "s": 3732, "text": "nb = wx.Notebook(self) \n" }, { "code": null, "e": 3846, "s": 3757, "text": "Two classes based on wx.Panel are designed. The first, puts a multi-line TextCtrl in it." }, { "code": null, "e": 4025, "s": 3846, "text": "class MyPanel1(wx.Panel): \n def __init__(self, parent): \n super(MyPanel1, self).__init__(parent) \n text = wx.TextCtrl(self, style = wx.TE_MULTILINE, size = (250,150))" }, { "code": null, "e": 4082, "s": 4025, "text": "The second, shows a RadioBox having three radio buttons." }, { "code": null, "e": 4388, "s": 4082, "text": "class MyPanel2(wx.Panel): \n def __init__(self, parent): \n super(MyPanel2, self).__init__(parent) \n lblList = ['Value X', 'Value Y', 'Value Z'] \n rbox = wx.RadioBox(self, label = 'RadioBox', pos = (25,10), choices = lblList,\n majorDimension = 1, style = wx.RA_SPECIFY_ROWS)" }, { "code": null, "e": 4478, "s": 4388, "text": "Objects of these two panel classes are added as pages in Notebook on the top level frame." }, { "code": null, "e": 4554, "s": 4478, "text": "nb.AddPage(MyPanel1(nb),\"Editor\") \nnb.AddPage(MyPanel2(nb),\"RadioButtons\")\n" }, { "code": null, "e": 4588, "s": 4554, "text": "The complete code is as follows −" }, { "code": null, "e": 5801, "s": 4588, "text": "import wx\n \nclass MyDialog(wx.Dialog): \n def __init__(self, parent, title): \n super(MyDialog, self).__init__(parent, title = title, size = (250,150)) \n panel = wx.Panel(self) \n self.btn = wx.Button(panel, wx.ID_OK, label = \"ok\", size = (50,20), pos = (75,50)) \n \nclass Mywin(wx.Frame): \n \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title, size = (250,150)) \n self.InitUI() \n \n def InitUI(self): \n nb = wx.Notebook(self) \n nb.AddPage(MyPanel1(nb),\"Editor\") \n nb.AddPage(MyPanel2(nb),\"RadioButtons\") \n self.Centre() \n self.Show(True) \n\t\t\nclass MyPanel1(wx.Panel): \n def __init__(self, parent): \n super(MyPanel1, self).__init__(parent) \n text = wx.TextCtrl(self, style = wx.TE_MULTILINE, size = (250,150)) \n\t\t\nclass MyPanel2(wx.Panel): \n def __init__(self, parent): \n super(MyPanel2, self).__init__(parent) \n lblList = ['Value X', 'Value Y', 'Value Z'] \n rbox = wx.RadioBox(self, label = 'RadioBox', pos = (25,10), choices = lblList,\n majorDimension = 1, style = wx.RA_SPECIFY_ROWS) \n \nex = wx.App() \nMywin(None,'NoteBook demo') \nex.MainLoop()" }, { "code": null, "e": 5848, "s": 5801, "text": "The above code produces the following output −" }, { "code": null, "e": 5855, "s": 5848, "text": " Print" }, { "code": null, "e": 5866, "s": 5855, "text": " Add Notes" } ]
List of useful Github Commands - GeeksforGeeks
04 Aug, 2021 Github is a distributed version control system which helps to manage the repositories. These are a list of few commands that you can use frequently on github(git bash) 1.git help Take help from github help section for different commands and other errors 2.git config To set the basic configurations on github like your name and email. 3.git config –-global user.name “Ashish Madaan” Sets configuration values for your user name on git. 4.git config –-global user.email [email protected] Sets configuration values for your user email on git. 5.git config –-global color.ui true To see different colours on command line for different outputs. 6.mkdir store Create a directory if not created initially. 7.cd store To go inside the directory and work upon its contents. 8.git init To create a local git repository for us in our store folder.This will help to manage the git commands for that particular repository. 9.git status To see whats changed since last commit.It shows all the files that have been added and modified and ready to be commmitted and files which are untracked 10.git add Readme.txt To add a file Readme.txt to the staging area to track its changes. 11.git commit -m “Created a Readme.txt” To commit our changes(taking a snapshot) and providing a message to remember for future reference. 12.git log To check the history of commits for our reference. Different ways to use add command: 13.git add To add a specific list of files to staging area. 14.git add --all To add all files of current directory to staging area. 15.git add *.txt To add all text files of the current directory to staging area. 16.git add docs/*.txt To add all text files of a particular directory(docs) to staging area. 17.git add docs/ To add all files in a particular directory(docs) to staging area. 18.git add “*.txt” To add text files of entire project to staging area. More Commands: 19.git diff To figure out what changes you made since last commit. 20.git reset head license To undo staging of the file that was added in the staging area. 21.git checkout –license To Blow away all changes since the last commit of the file. 22.git commit -a -m “Readme.md” To add any of our tracked files to staging area and commit them by providing a message to remember. 23.git reset –soft HEAD^ To undo last commit and bring file to staging area. 24.git reset –hard HEAD^ To undo last commit and remove file from the staging area as well(In case we went horribly wrong). 25.git reset –hard HEAD^^ To undo last 2 commits and all changes. 26.git remote add origin https://github.com/madaan123/MyAlgorithms.git This commands make a bookmark which signifies that this particular remote refers to this URL. This remote will be used to pull any content from the directory and push our local content to the global server. 27.git remote add <address> To add new remotes to our local repository for a particular git address. 28.git remove rm To remove a remote from our local repository. 29.git push -u origin master To push all the contents of our local repository that belong to master branch to the server(Global repository). 30.git clone https://github.com/madaan123/MyAlgorithms.git To clone or make a local copy of the global repository in your system (git clone command downloads the repository and creates a remote named as origin which can be checked by command – git remote -v). 31.git branch Testing To create a new branch named as Testing. 32.git branch To see all the branches present and current branch that we are working on. 33.git checkout Testing To switch to branch Testing from master branch. 34.ls To see directories and files in the current directory. 35.git merge Testing To merge Testing branch with master branch. 36.git branch -d Testing To delete Testing branch. 37.git checkout -b admin To create a new branch admin and set it as current branch. 38.git branch -r To look at all the remote branches. 39.git branch -D Testing To forcefully delete a branch without making commmits. 40.git tag To see the list of available tags. 41.git checkout v0.0.1 To set the current tag to v0.0.1. 42.git tag -a v0.0.3 -m “version 0.0.3” To create a new tag. 43.git push –tags To push the tags to remote repository. 44.git fetch To fetch down any changes from global repository to current repository 45.git rebase Three tasks are performed by git rebase Move all changes to master which are not in origin/master to a temporary area.Run all origin master commits.Run all commits in the temporary area on top of our master one at a time, so it avoids merge commits. Move all changes to master which are not in origin/master to a temporary area. Run all origin master commits. Run all commits in the temporary area on top of our master one at a time, so it avoids merge commits. This article is contributed by Ashish Madaan. 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. jasawatsandeep31 GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 DSA Sheet by Love Babbar 6 Best IDE's For Python in 2022 A Freshers Guide To Programming ML | Underfitting and Overfitting Virtualization In Cloud Computing and Types Top 10 Programming Languages to Learn in 2022 What is web socket and how it is different from the HTTP? Top Selenium Frameworks You Should Know Introduction to Hill Climbing | Artificial Intelligence
[ { "code": null, "e": 24617, "s": 24589, "text": "\n04 Aug, 2021" }, { "code": null, "e": 24705, "s": 24617, "text": "Github is a distributed version control system which helps to manage the repositories. " }, { "code": null, "e": 24788, "s": 24705, "text": "These are a list of few commands that you can use frequently on github(git bash) " }, { "code": null, "e": 24799, "s": 24788, "text": "1.git help" }, { "code": null, "e": 24876, "s": 24799, "text": "Take help from github help section for different commands and other errors " }, { "code": null, "e": 24889, "s": 24876, "text": "2.git config" }, { "code": null, "e": 24959, "s": 24889, "text": "To set the basic configurations on github like your name and email. " }, { "code": null, "e": 25007, "s": 24959, "text": "3.git config –-global user.name “Ashish Madaan”" }, { "code": null, "e": 25062, "s": 25007, "text": "Sets configuration values for your user name on git. " }, { "code": null, "e": 25119, "s": 25062, "text": "4.git config –-global user.email [email protected]" }, { "code": null, "e": 25175, "s": 25119, "text": "Sets configuration values for your user email on git. " }, { "code": null, "e": 25211, "s": 25175, "text": "5.git config –-global color.ui true" }, { "code": null, "e": 25277, "s": 25211, "text": "To see different colours on command line for different outputs. " }, { "code": null, "e": 25291, "s": 25277, "text": "6.mkdir store" }, { "code": null, "e": 25338, "s": 25291, "text": "Create a directory if not created initially. " }, { "code": null, "e": 25349, "s": 25338, "text": "7.cd store" }, { "code": null, "e": 25406, "s": 25349, "text": "To go inside the directory and work upon its contents. " }, { "code": null, "e": 25417, "s": 25406, "text": "8.git init" }, { "code": null, "e": 25553, "s": 25417, "text": "To create a local git repository for us in our store folder.This will help to manage the git commands for that particular repository. " }, { "code": null, "e": 25566, "s": 25553, "text": "9.git status" }, { "code": null, "e": 25721, "s": 25566, "text": "To see whats changed since last commit.It shows all the files that have been added and modified and ready to be commmitted and files which are untracked " }, { "code": null, "e": 25743, "s": 25721, "text": "10.git add Readme.txt" }, { "code": null, "e": 25812, "s": 25743, "text": "To add a file Readme.txt to the staging area to track its changes. " }, { "code": null, "e": 25852, "s": 25812, "text": "11.git commit -m “Created a Readme.txt”" }, { "code": null, "e": 25953, "s": 25852, "text": "To commit our changes(taking a snapshot) and providing a message to remember for future reference. " }, { "code": null, "e": 25964, "s": 25953, "text": "12.git log" }, { "code": null, "e": 26016, "s": 25964, "text": "To check the history of commits for our reference. " }, { "code": null, "e": 26053, "s": 26016, "text": "Different ways to use add command: " }, { "code": null, "e": 26064, "s": 26053, "text": "13.git add" }, { "code": null, "e": 26115, "s": 26064, "text": "To add a specific list of files to staging area. " }, { "code": null, "e": 26132, "s": 26115, "text": "14.git add --all" }, { "code": null, "e": 26189, "s": 26132, "text": "To add all files of current directory to staging area. " }, { "code": null, "e": 26206, "s": 26189, "text": "15.git add *.txt" }, { "code": null, "e": 26272, "s": 26206, "text": "To add all text files of the current directory to staging area. " }, { "code": null, "e": 26294, "s": 26272, "text": "16.git add docs/*.txt" }, { "code": null, "e": 26367, "s": 26294, "text": "To add all text files of a particular directory(docs) to staging area. " }, { "code": null, "e": 26384, "s": 26367, "text": "17.git add docs/" }, { "code": null, "e": 26452, "s": 26384, "text": "To add all files in a particular directory(docs) to staging area. " }, { "code": null, "e": 26471, "s": 26452, "text": "18.git add “*.txt”" }, { "code": null, "e": 26541, "s": 26471, "text": "To add text files of entire project to staging area. More Commands: " }, { "code": null, "e": 26553, "s": 26541, "text": "19.git diff" }, { "code": null, "e": 26610, "s": 26553, "text": "To figure out what changes you made since last commit. " }, { "code": null, "e": 26636, "s": 26610, "text": "20.git reset head license" }, { "code": null, "e": 26702, "s": 26636, "text": "To undo staging of the file that was added in the staging area. " }, { "code": null, "e": 26727, "s": 26702, "text": "21.git checkout –license" }, { "code": null, "e": 26789, "s": 26727, "text": "To Blow away all changes since the last commit of the file. " }, { "code": null, "e": 26821, "s": 26789, "text": "22.git commit -a -m “Readme.md”" }, { "code": null, "e": 26923, "s": 26821, "text": "To add any of our tracked files to staging area and commit them by providing a message to remember. " }, { "code": null, "e": 26948, "s": 26923, "text": "23.git reset –soft HEAD^" }, { "code": null, "e": 27002, "s": 26948, "text": "To undo last commit and bring file to staging area. " }, { "code": null, "e": 27027, "s": 27002, "text": "24.git reset –hard HEAD^" }, { "code": null, "e": 27128, "s": 27027, "text": "To undo last commit and remove file from the staging area as well(In case we went horribly wrong). " }, { "code": null, "e": 27154, "s": 27128, "text": "25.git reset –hard HEAD^^" }, { "code": null, "e": 27196, "s": 27154, "text": "To undo last 2 commits and all changes. " }, { "code": null, "e": 27267, "s": 27196, "text": "26.git remote add origin https://github.com/madaan123/MyAlgorithms.git" }, { "code": null, "e": 27476, "s": 27267, "text": "This commands make a bookmark which signifies that this particular remote refers to this URL. This remote will be used to pull any content from the directory and push our local content to the global server. " }, { "code": null, "e": 27505, "s": 27476, "text": "27.git remote add <address> " }, { "code": null, "e": 27580, "s": 27505, "text": "To add new remotes to our local repository for a particular git address. " }, { "code": null, "e": 27597, "s": 27580, "text": "28.git remove rm" }, { "code": null, "e": 27645, "s": 27597, "text": "To remove a remote from our local repository. " }, { "code": null, "e": 27674, "s": 27645, "text": "29.git push -u origin master" }, { "code": null, "e": 27788, "s": 27674, "text": "To push all the contents of our local repository that belong to master branch to the server(Global repository). " }, { "code": null, "e": 27847, "s": 27788, "text": "30.git clone https://github.com/madaan123/MyAlgorithms.git" }, { "code": null, "e": 28050, "s": 27847, "text": "To clone or make a local copy of the global repository in your system (git clone command downloads the repository and creates a remote named as origin which can be checked by command – git remote -v). " }, { "code": null, "e": 28072, "s": 28050, "text": "31.git branch Testing" }, { "code": null, "e": 28115, "s": 28072, "text": "To create a new branch named as Testing. " }, { "code": null, "e": 28129, "s": 28115, "text": "32.git branch" }, { "code": null, "e": 28206, "s": 28129, "text": "To see all the branches present and current branch that we are working on. " }, { "code": null, "e": 28230, "s": 28206, "text": "33.git checkout Testing" }, { "code": null, "e": 28280, "s": 28230, "text": "To switch to branch Testing from master branch. " }, { "code": null, "e": 28286, "s": 28280, "text": "34.ls" }, { "code": null, "e": 28343, "s": 28286, "text": "To see directories and files in the current directory. " }, { "code": null, "e": 28364, "s": 28343, "text": "35.git merge Testing" }, { "code": null, "e": 28410, "s": 28364, "text": "To merge Testing branch with master branch. " }, { "code": null, "e": 28435, "s": 28410, "text": "36.git branch -d Testing" }, { "code": null, "e": 28463, "s": 28435, "text": "To delete Testing branch. " }, { "code": null, "e": 28488, "s": 28463, "text": "37.git checkout -b admin" }, { "code": null, "e": 28549, "s": 28488, "text": "To create a new branch admin and set it as current branch. " }, { "code": null, "e": 28566, "s": 28549, "text": "38.git branch -r" }, { "code": null, "e": 28604, "s": 28566, "text": "To look at all the remote branches. " }, { "code": null, "e": 28629, "s": 28604, "text": "39.git branch -D Testing" }, { "code": null, "e": 28686, "s": 28629, "text": "To forcefully delete a branch without making commmits. " }, { "code": null, "e": 28697, "s": 28686, "text": "40.git tag" }, { "code": null, "e": 28734, "s": 28697, "text": "To see the list of available tags. " }, { "code": null, "e": 28757, "s": 28734, "text": "41.git checkout v0.0.1" }, { "code": null, "e": 28793, "s": 28757, "text": "To set the current tag to v0.0.1. " }, { "code": null, "e": 28833, "s": 28793, "text": "42.git tag -a v0.0.3 -m “version 0.0.3”" }, { "code": null, "e": 28856, "s": 28833, "text": "To create a new tag. " }, { "code": null, "e": 28874, "s": 28856, "text": "43.git push –tags" }, { "code": null, "e": 28915, "s": 28874, "text": "To push the tags to remote repository. " }, { "code": null, "e": 28928, "s": 28915, "text": "44.git fetch" }, { "code": null, "e": 29001, "s": 28928, "text": "To fetch down any changes from global repository to current repository " }, { "code": null, "e": 29015, "s": 29001, "text": "45.git rebase" }, { "code": null, "e": 29057, "s": 29015, "text": "Three tasks are performed by git rebase " }, { "code": null, "e": 29267, "s": 29057, "text": "Move all changes to master which are not in origin/master to a temporary area.Run all origin master commits.Run all commits in the temporary area on top of our master one at a time, so it avoids merge commits." }, { "code": null, "e": 29346, "s": 29267, "text": "Move all changes to master which are not in origin/master to a temporary area." }, { "code": null, "e": 29377, "s": 29346, "text": "Run all origin master commits." }, { "code": null, "e": 29479, "s": 29377, "text": "Run all commits in the temporary area on top of our master one at a time, so it avoids merge commits." }, { "code": null, "e": 29781, "s": 29479, "text": "This article is contributed by Ashish Madaan. 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": 29907, "s": 29781, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 29924, "s": 29907, "text": "jasawatsandeep31" }, { "code": null, "e": 29930, "s": 29924, "text": "GBlog" }, { "code": null, "e": 30028, "s": 29930, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30037, "s": 30028, "text": "Comments" }, { "code": null, "e": 30050, "s": 30037, "text": "Old Comments" }, { "code": null, "e": 30106, "s": 30050, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 30131, "s": 30106, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 30163, "s": 30131, "text": "6 Best IDE's For Python in 2022" }, { "code": null, "e": 30195, "s": 30163, "text": "A Freshers Guide To Programming" }, { "code": null, "e": 30229, "s": 30195, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 30273, "s": 30229, "text": "Virtualization In Cloud Computing and Types" }, { "code": null, "e": 30319, "s": 30273, "text": "Top 10 Programming Languages to Learn in 2022" }, { "code": null, "e": 30377, "s": 30319, "text": "What is web socket and how it is different from the HTTP?" }, { "code": null, "e": 30417, "s": 30377, "text": "Top Selenium Frameworks You Should Know" } ]
How to get HTML content of an element using jQuery?
To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element. You can try to run the following code to get HTML content of an element using jQuery: Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#button1").click(function(){ var res = $('#demo').html(); alert(res); }); }); </script> </head> <body> <div id="demo"> This is <b>demo</b> text. </div> <button id="button1">Get</button> </body> </html>
[ { "code": null, "e": 1204, "s": 1062, "text": "To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element." }, { "code": null, "e": 1290, "s": 1204, "text": "You can try to run the following code to get HTML content of an element using jQuery:" }, { "code": null, "e": 1300, "s": 1290, "text": "Live Demo" }, { "code": null, "e": 1676, "s": 1300, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"#button1\").click(function(){\n var res = $('#demo').html();\n alert(res);\n });\n});\n</script>\n</head>\n<body>\n\n<div id=\"demo\"> This is <b>demo</b> text.\n</div>\n<button id=\"button1\">Get</button>\n</body>\n</html>" } ]
How to create an empty file using Python?
The easiest way to simply create a file without truncating it in case it exists is − open('my_file.txt', 'a').close() In Python 3.4+, you can directly use the pathlib module to touch files. For example, from pathlib import Path Path('my_file.txt').touch() You can also create new files without opening them using the os module. The method mknod() creates a filesystem node (file, device special file or named pipe) named filename. For example, import os os.mknod("my_file.txt")
[ { "code": null, "e": 1147, "s": 1062, "text": "The easiest way to simply create a file without truncating it in case it exists is −" }, { "code": null, "e": 1180, "s": 1147, "text": "open('my_file.txt', 'a').close()" }, { "code": null, "e": 1265, "s": 1180, "text": "In Python 3.4+, you can directly use the pathlib module to touch files. For example," }, { "code": null, "e": 1318, "s": 1265, "text": "from pathlib import Path\nPath('my_file.txt').touch()" }, { "code": null, "e": 1506, "s": 1318, "text": "You can also create new files without opening them using the os module. The method mknod() creates a filesystem node (file, device special file or named pipe) named filename. For example," }, { "code": null, "e": 1540, "s": 1506, "text": "import os\nos.mknod(\"my_file.txt\")" } ]
C# Program to get the last access time of a file
To get the last access time of a file in C#, use the LastAccessTime() method. For this, use the FileInfo as well as DateTime classes.Create an object of each − FileInfo file = new FileInfo("new.txt"); DateTime dt = file.CreationTime; dt = file.LastAccessTime; Let us see the complete code − Live Demo using System.IO; using System; public class Program { public static void Main() { using (StreamWriter sw = new StreamWriter("quiz.txt")) { sw.WriteLine("Quizzes!"); } FileInfo file = new FileInfo("quiz.txt"); // last access time DateTime dt = file.LastAccessTime; Console.WriteLine(dt); } } 9/5/2018 5:21:43 AM
[ { "code": null, "e": 1140, "s": 1062, "text": "To get the last access time of a file in C#, use the LastAccessTime() method." }, { "code": null, "e": 1222, "s": 1140, "text": "For this, use the FileInfo as well as DateTime classes.Create an object of each −" }, { "code": null, "e": 1322, "s": 1222, "text": "FileInfo file = new FileInfo(\"new.txt\");\nDateTime dt = file.CreationTime;\ndt = file.LastAccessTime;" }, { "code": null, "e": 1353, "s": 1322, "text": "Let us see the complete code −" }, { "code": null, "e": 1364, "s": 1353, "text": " Live Demo" }, { "code": null, "e": 1706, "s": 1364, "text": "using System.IO;\nusing System;\npublic class Program {\n public static void Main() {\n using (StreamWriter sw = new StreamWriter(\"quiz.txt\")) {\n sw.WriteLine(\"Quizzes!\");\n }\n FileInfo file = new FileInfo(\"quiz.txt\");\n // last access time\n DateTime dt = file.LastAccessTime;\n Console.WriteLine(dt);\n }\n}" }, { "code": null, "e": 1726, "s": 1706, "text": "9/5/2018 5:21:43 AM" } ]
Perl | String functions (length, lc, uc, index, rindex) - GeeksforGeeks
26 Jun, 2019 String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follows: length() lc() uc() index() rindex() length(): This function is used to find the number of characters in a string. This function returns the length of the string. Below are the programs to illustrate this method. Example 1:# Perl program to demonstrate # string length function # stringmy $s = "geeksforgeeks"; # using length function &# displaying lengthprint(length($s),"\n"); Output:13 # Perl program to demonstrate # string length function # stringmy $s = "geeksforgeeks"; # using length function &# displaying lengthprint(length($s),"\n"); Output: 13 Example 2:# Perl program to demonstrate # string length function # stringmy $s = "#$%HeLLo CSHARP &+#*"; # using length function &# displaying lengthprint(length($s),"\n"); Output:19 # Perl program to demonstrate # string length function # stringmy $s = "#$%HeLLo CSHARP &+#*"; # using length function &# displaying lengthprint(length($s),"\n"); Output: 19 lc(): This function return the lower case version of a string. Below are the programs to illustrate this method. Example 1:# Perl program to demonstrate # string lc function # stringmy $s = "GEEKSFORGEEKS\n"; # using lc function &# displaying resultprint("To lower case: ");print(lc($s),"\n");Output:To lower case: geeksforgeeks # Perl program to demonstrate # string lc function # stringmy $s = "GEEKSFORGEEKS\n"; # using lc function &# displaying resultprint("To lower case: ");print(lc($s),"\n"); Output: To lower case: geeksforgeeks Example 2:# Perl program to demonstrate # string lc function # stringmy $s = "GEEKS\n"; # using lc function &# displaying resultprint("To lower case: ");print(lc($s),"\n");Output:To lower case: geeks # Perl program to demonstrate # string lc function # stringmy $s = "GEEKS\n"; # using lc function &# displaying resultprint("To lower case: ");print(lc($s),"\n"); Output: To lower case: geeks uc(): This function return the upper case version of a string. Below are the programs to illustrate this method. Example 1:# Perl program to demonstrate # string uc function # stringmy $s = "geeksforgeeks"; # using uc function &# displaying resultprint("To Upper Case: ");print(uc($s),"\n");Output:To Upper Case: GEEKSFORGEEKS # Perl program to demonstrate # string uc function # stringmy $s = "geeksforgeeks"; # using uc function &# displaying resultprint("To Upper Case: ");print(uc($s),"\n"); Output: To Upper Case: GEEKSFORGEEKS Example 2:# Perl program to demonstrate # string uc function # stringmy $s = "GeekS\n"; # using uc function &# displaying resultprint("To Upper Case: ");print(uc($s),"\n");Output:To Upper Case: GEEKS # Perl program to demonstrate # string uc function # stringmy $s = "GeekS\n"; # using uc function &# displaying resultprint("To Upper Case: ");print(uc($s),"\n"); Output: To Upper Case: GEEKS index(): This method will search a substring from a specified position in a string and returns the position of the first occurrence of the substring in the string. If the position is omitted, it will search from the beginning of the string. This method will take the two parameters i.e. the original string and the substring that has to be searched. Example : # Perl Program to illustrate # the index() function # !/usr/bin/perluse warnings;use strict; # stringmy $st = "GeeksforGeeks\n"; # substringmy $subs = "for"; # using index functionmy $r = index($st, $subs); # displaying resultprint(qq\The substring $subs found at position $r in string $st\); Output: The substring for found at position 5 in string GeeksforGeeks rindex() This function is same as index() except it returns the last occurrence of text in a string. Also, a third parameter can be given which returns position before or at that location. It searches from the end of the string instead of from the beginning. Below are the programs to illustrate this method. Example 1: # Perl Program to illustrate # the rindex() function # !/usr/bin/perluse warnings;use strict; # stringmy $st = "GeeksforGeeks\n"; # substringmy $subs = "for"; # using rindex functionmy $r = rindex($st, $subs); # displaying resultprint(qq\The substring $subs found at position $r in string $st\); Output: The substring for found at position 5 in string GeeksforGeeks Example 2: # Perl Program to illustrate # the rindex() function with # three parameters # !/usr/bin/perl # using rindex() function $p = rindex("GeeksForGFGGeeksgeeksforGFG", "GFG"); print "Founded position of GFG $p\n"; # Use the first position found # as the offset to the next search.# The length of the target string# is subtracted from the offset # to save time.$p = rindex("GeeksForGFGGeeksgeeksforGFG", "GFG", $p-7);print "Founded position of GFG $p\n"; Output: Founded position of GFG 24 Founded position of GFG 8 Perl-function Perl-String Perl-String-Functions Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | split() Function Perl | push() Function Perl | chomp() Function Perl | grep() Function Perl | substr() function Perl | exists() Function Perl Tutorial - Learn Perl With Examples Use of print() and say() in Perl Perl | substitution Operator Perl | length() Function
[ { "code": null, "e": 26659, "s": 26631, "text": "\n26 Jun, 2019" }, { "code": null, "e": 26962, "s": 26659, "text": "String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follows:" }, { "code": null, "e": 26971, "s": 26962, "text": "length()" }, { "code": null, "e": 26976, "s": 26971, "text": "lc()" }, { "code": null, "e": 26981, "s": 26976, "text": "uc()" }, { "code": null, "e": 26989, "s": 26981, "text": "index()" }, { "code": null, "e": 26998, "s": 26989, "text": "rindex()" }, { "code": null, "e": 27174, "s": 26998, "text": "length(): This function is used to find the number of characters in a string. This function returns the length of the string. Below are the programs to illustrate this method." }, { "code": null, "e": 27353, "s": 27174, "text": "Example 1:# Perl program to demonstrate # string length function # stringmy $s = \"geeksforgeeks\"; # using length function &# displaying lengthprint(length($s),\"\\n\"); Output:13\n" }, { "code": "# Perl program to demonstrate # string length function # stringmy $s = \"geeksforgeeks\"; # using length function &# displaying lengthprint(length($s),\"\\n\"); ", "e": 27512, "s": 27353, "text": null }, { "code": null, "e": 27520, "s": 27512, "text": "Output:" }, { "code": null, "e": 27524, "s": 27520, "text": "13\n" }, { "code": null, "e": 27711, "s": 27524, "text": "Example 2:# Perl program to demonstrate # string length function # stringmy $s = \"#$%HeLLo CSHARP &+#*\"; # using length function &# displaying lengthprint(length($s),\"\\n\"); Output:19\n" }, { "code": "# Perl program to demonstrate # string length function # stringmy $s = \"#$%HeLLo CSHARP &+#*\"; # using length function &# displaying lengthprint(length($s),\"\\n\"); ", "e": 27878, "s": 27711, "text": null }, { "code": null, "e": 27886, "s": 27878, "text": "Output:" }, { "code": null, "e": 27890, "s": 27886, "text": "19\n" }, { "code": null, "e": 28003, "s": 27890, "text": "lc(): This function return the lower case version of a string. Below are the programs to illustrate this method." }, { "code": null, "e": 28222, "s": 28003, "text": "Example 1:# Perl program to demonstrate # string lc function # stringmy $s = \"GEEKSFORGEEKS\\n\"; # using lc function &# displaying resultprint(\"To lower case: \");print(lc($s),\"\\n\");Output:To lower case: geeksforgeeks\n" }, { "code": "# Perl program to demonstrate # string lc function # stringmy $s = \"GEEKSFORGEEKS\\n\"; # using lc function &# displaying resultprint(\"To lower case: \");print(lc($s),\"\\n\");", "e": 28395, "s": 28222, "text": null }, { "code": null, "e": 28403, "s": 28395, "text": "Output:" }, { "code": null, "e": 28433, "s": 28403, "text": "To lower case: geeksforgeeks\n" }, { "code": null, "e": 28636, "s": 28433, "text": "Example 2:# Perl program to demonstrate # string lc function # stringmy $s = \"GEEKS\\n\"; # using lc function &# displaying resultprint(\"To lower case: \");print(lc($s),\"\\n\");Output:To lower case: geeks\n" }, { "code": "# Perl program to demonstrate # string lc function # stringmy $s = \"GEEKS\\n\"; # using lc function &# displaying resultprint(\"To lower case: \");print(lc($s),\"\\n\");", "e": 28801, "s": 28636, "text": null }, { "code": null, "e": 28809, "s": 28801, "text": "Output:" }, { "code": null, "e": 28831, "s": 28809, "text": "To lower case: geeks\n" }, { "code": null, "e": 28944, "s": 28831, "text": "uc(): This function return the upper case version of a string. Below are the programs to illustrate this method." }, { "code": null, "e": 29161, "s": 28944, "text": "Example 1:# Perl program to demonstrate # string uc function # stringmy $s = \"geeksforgeeks\"; # using uc function &# displaying resultprint(\"To Upper Case: \");print(uc($s),\"\\n\");Output:To Upper Case: GEEKSFORGEEKS\n" }, { "code": "# Perl program to demonstrate # string uc function # stringmy $s = \"geeksforgeeks\"; # using uc function &# displaying resultprint(\"To Upper Case: \");print(uc($s),\"\\n\");", "e": 29332, "s": 29161, "text": null }, { "code": null, "e": 29340, "s": 29332, "text": "Output:" }, { "code": null, "e": 29370, "s": 29340, "text": "To Upper Case: GEEKSFORGEEKS\n" }, { "code": null, "e": 29573, "s": 29370, "text": "Example 2:# Perl program to demonstrate # string uc function # stringmy $s = \"GeekS\\n\"; # using uc function &# displaying resultprint(\"To Upper Case: \");print(uc($s),\"\\n\");Output:To Upper Case: GEEKS\n" }, { "code": "# Perl program to demonstrate # string uc function # stringmy $s = \"GeekS\\n\"; # using uc function &# displaying resultprint(\"To Upper Case: \");print(uc($s),\"\\n\");", "e": 29738, "s": 29573, "text": null }, { "code": null, "e": 29746, "s": 29738, "text": "Output:" }, { "code": null, "e": 29768, "s": 29746, "text": "To Upper Case: GEEKS\n" }, { "code": null, "e": 30118, "s": 29768, "text": "index(): This method will search a substring from a specified position in a string and returns the position of the first occurrence of the substring in the string. If the position is omitted, it will search from the beginning of the string. This method will take the two parameters i.e. the original string and the substring that has to be searched." }, { "code": null, "e": 30128, "s": 30118, "text": "Example :" }, { "code": "# Perl Program to illustrate # the index() function # !/usr/bin/perluse warnings;use strict; # stringmy $st = \"GeeksforGeeks\\n\"; # substringmy $subs = \"for\"; # using index functionmy $r = index($st, $subs); # displaying resultprint(qq\\The substring $subs found at position $r in string $st\\);", "e": 30426, "s": 30128, "text": null }, { "code": null, "e": 30434, "s": 30426, "text": "Output:" }, { "code": null, "e": 30497, "s": 30434, "text": "The substring for found at position 5 in string GeeksforGeeks\n" }, { "code": null, "e": 30806, "s": 30497, "text": "rindex() This function is same as index() except it returns the last occurrence of text in a string. Also, a third parameter can be given which returns position before or at that location. It searches from the end of the string instead of from the beginning. Below are the programs to illustrate this method." }, { "code": null, "e": 30817, "s": 30806, "text": "Example 1:" }, { "code": "# Perl Program to illustrate # the rindex() function # !/usr/bin/perluse warnings;use strict; # stringmy $st = \"GeeksforGeeks\\n\"; # substringmy $subs = \"for\"; # using rindex functionmy $r = rindex($st, $subs); # displaying resultprint(qq\\The substring $subs found at position $r in string $st\\);", "e": 31118, "s": 30817, "text": null }, { "code": null, "e": 31126, "s": 31118, "text": "Output:" }, { "code": null, "e": 31189, "s": 31126, "text": "The substring for found at position 5 in string GeeksforGeeks\n" }, { "code": null, "e": 31200, "s": 31189, "text": "Example 2:" }, { "code": "# Perl Program to illustrate # the rindex() function with # three parameters # !/usr/bin/perl # using rindex() function $p = rindex(\"GeeksForGFGGeeksgeeksforGFG\", \"GFG\"); print \"Founded position of GFG $p\\n\"; # Use the first position found # as the offset to the next search.# The length of the target string# is subtracted from the offset # to save time.$p = rindex(\"GeeksForGFGGeeksgeeksforGFG\", \"GFG\", $p-7);print \"Founded position of GFG $p\\n\";", "e": 31653, "s": 31200, "text": null }, { "code": null, "e": 31661, "s": 31653, "text": "Output:" }, { "code": null, "e": 31715, "s": 31661, "text": "Founded position of GFG 24\nFounded position of GFG 8\n" }, { "code": null, "e": 31729, "s": 31715, "text": "Perl-function" }, { "code": null, "e": 31741, "s": 31729, "text": "Perl-String" }, { "code": null, "e": 31763, "s": 31741, "text": "Perl-String-Functions" }, { "code": null, "e": 31768, "s": 31763, "text": "Perl" }, { "code": null, "e": 31773, "s": 31768, "text": "Perl" }, { "code": null, "e": 31871, "s": 31773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31895, "s": 31871, "text": "Perl | split() Function" }, { "code": null, "e": 31918, "s": 31895, "text": "Perl | push() Function" }, { "code": null, "e": 31942, "s": 31918, "text": "Perl | chomp() Function" }, { "code": null, "e": 31965, "s": 31942, "text": "Perl | grep() Function" }, { "code": null, "e": 31990, "s": 31965, "text": "Perl | substr() function" }, { "code": null, "e": 32015, "s": 31990, "text": "Perl | exists() Function" }, { "code": null, "e": 32056, "s": 32015, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 32089, "s": 32056, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 32118, "s": 32089, "text": "Perl | substitution Operator" } ]
C++ Program to Display Fibonacci Series
The fibonacci series contains numbers in which each term is the sum of the previous two terms. This creates the following integer sequence − 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377....... The recurrence relation that defines the fibonacci numbers is as follows − F(n) = F(n-1) + F(n-2) F(0)=0 F(1)=1 There are two methods to display fibonacci series i.e. using dynamic programming and recursive programming. These are further explained as follows − #include<iostream> using namespace std; void fib(int n) { int f[n]; int i; f[0] = 0; f[1] = 1; for (i = 2; i < n; i++) { f[i] = f[i-1] + f[i-2]; } for (i = 0; i < n; i++) { cout<<f[i]<<" "; } } int main () { int n = 10; fib(n); getchar(); return 0; } The output of the above program is as follows. 0 1 1 2 3 5 8 13 21 34 In the program, main() is the driver function. The actual code for the creation of the fibonacci series is stored in the function fib() which is called from main. An array f[n] is created which will store the first n terms of the fibonacci series. The first and second elements of this array are initialized to 0 and 1 respectively. f[0] = 0; f[1] = 1; Then for loop is used to store each element in the array as the sum of its previous two elements. for (i = 2; i < n; i++) { f[i] = f[i-1] + f[i-2]; } Finally the fibonacci series is displayed. for (i = 0; i < n; i++) { cout<<f[i]<<" "; } Let us see how to display fibonacci series using recursion. #include<iostream> using namespace std; int fib(int n) { if (n <= 1) return n; return fib(n-1) + fib(n-2); } int main () { int n = 10, i; for(i=0;i<n;i++) cout<<fib(i)<<" "; return 0; } 0 1 1 2 3 5 8 13 21 34 In the above program, a for loop is set that creates each term of the fibonacci series using recursion. This is done by calling the function fib() for each term in the series. for(i=0;i<n;i++) cout<<fib(i)<<" "; The function fib() returns 0 or 1 if n is 0 or 1 respectively. If not, it calls itself recursively as the sum of the previous two terms until the correct value is returned. if (n <= 1) return n; return fib(n-1) + fib(n-2);
[ { "code": null, "e": 1203, "s": 1062, "text": "The fibonacci series contains numbers in which each term is the sum of the previous two terms. This creates the following integer sequence −" }, { "code": null, "e": 1265, "s": 1203, "text": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377......." }, { "code": null, "e": 1340, "s": 1265, "text": "The recurrence relation that defines the fibonacci numbers is as follows −" }, { "code": null, "e": 1377, "s": 1340, "text": "F(n) = F(n-1) + F(n-2) F(0)=0 F(1)=1" }, { "code": null, "e": 1526, "s": 1377, "text": "There are two methods to display fibonacci series i.e. using dynamic programming and recursive programming. These are further explained as follows −" }, { "code": null, "e": 1825, "s": 1526, "text": "#include<iostream>\nusing namespace std;\nvoid fib(int n) {\n int f[n];\n int i;\n f[0] = 0;\n f[1] = 1;\n for (i = 2; i < n; i++) {\n f[i] = f[i-1] + f[i-2];\n }\n for (i = 0; i < n; i++) {\n cout<<f[i]<<\" \";\n }\n}\nint main () {\n int n = 10;\n fib(n);\n getchar();\n return 0;\n}" }, { "code": null, "e": 1872, "s": 1825, "text": "The output of the above program is as follows." }, { "code": null, "e": 1895, "s": 1872, "text": "0 1 1 2 3 5 8 13 21 34" }, { "code": null, "e": 2058, "s": 1895, "text": "In the program, main() is the driver function. The actual code for the creation of the fibonacci series is stored in the function fib() which is called from main." }, { "code": null, "e": 2228, "s": 2058, "text": "An array f[n] is created which will store the first n terms of the fibonacci series. The first and second elements of this array are initialized to 0 and 1 respectively." }, { "code": null, "e": 2248, "s": 2228, "text": "f[0] = 0;\nf[1] = 1;" }, { "code": null, "e": 2346, "s": 2248, "text": "Then for loop is used to store each element in the array as the sum of its previous two elements." }, { "code": null, "e": 2401, "s": 2346, "text": "for (i = 2; i < n; i++) {\n f[i] = f[i-1] + f[i-2];\n}" }, { "code": null, "e": 2444, "s": 2401, "text": "Finally the fibonacci series is displayed." }, { "code": null, "e": 2492, "s": 2444, "text": "for (i = 0; i < n; i++) {\n cout<<f[i]<<\" \";\n}" }, { "code": null, "e": 2552, "s": 2492, "text": "Let us see how to display fibonacci series using recursion." }, { "code": null, "e": 2759, "s": 2552, "text": "#include<iostream>\nusing namespace std;\nint fib(int n) {\n if (n <= 1)\n return n;\n return fib(n-1) + fib(n-2);\n}\nint main () {\n int n = 10, i;\n for(i=0;i<n;i++)\n cout<<fib(i)<<\" \";\n return 0;\n}" }, { "code": null, "e": 2782, "s": 2759, "text": "0 1 1 2 3 5 8 13 21 34" }, { "code": null, "e": 2958, "s": 2782, "text": "In the above program, a for loop is set that creates each term of the fibonacci series using recursion. This is done by calling the function fib() for each term in the series." }, { "code": null, "e": 2994, "s": 2958, "text": "for(i=0;i<n;i++)\ncout<<fib(i)<<\" \";" }, { "code": null, "e": 3167, "s": 2994, "text": "The function fib() returns 0 or 1 if n is 0 or 1 respectively. If not, it calls itself recursively as the sum of the previous two terms until the correct value is returned." }, { "code": null, "e": 3217, "s": 3167, "text": "if (n <= 1)\nreturn n;\nreturn fib(n-1) + fib(n-2);" } ]
TypeScript - Array slice()
slice() method extracts a section of an array and returns a new array. array.slice( begin [,end] ); begin − Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. begin − Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. end − Zero-based index at which to end extraction. end − Zero-based index at which to end extraction. Returns the extracted array based on the passed parameters. var arr = ["orange", "mango", "banana", "sugar", "tea"]; console.log("arr.slice( 1, 2) : " + arr.slice( 1, 2) ); console.log("arr.slice( 1, 3) : " + arr.slice( 1, 3) ); On compiling, it will generate the same code in JavaScript. Its output is as follows − arr.slice( 1, 2) : mango arr.slice( 1, 3) : mango,banana 45 Lectures 4 hours Antonio Papa 41 Lectures 7 hours Haider Malik 60 Lectures 2.5 hours Skillbakerystudios 77 Lectures 8 hours Sean Bradley 77 Lectures 3.5 hours TELCOMA Global 19 Lectures 3 hours Christopher Frewin Print Add Notes Bookmark this page
[ { "code": null, "e": 2119, "s": 2048, "text": "slice() method extracts a section of an array and returns a new array." }, { "code": null, "e": 2149, "s": 2119, "text": "array.slice( begin [,end] );\n" }, { "code": null, "e": 2281, "s": 2149, "text": "begin − Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence." }, { "code": null, "e": 2413, "s": 2281, "text": "begin − Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence." }, { "code": null, "e": 2464, "s": 2413, "text": "end − Zero-based index at which to end extraction." }, { "code": null, "e": 2515, "s": 2464, "text": "end − Zero-based index at which to end extraction." }, { "code": null, "e": 2575, "s": 2515, "text": "Returns the extracted array based on the passed parameters." }, { "code": null, "e": 2748, "s": 2575, "text": "var arr = [\"orange\", \"mango\", \"banana\", \"sugar\", \"tea\"]; \nconsole.log(\"arr.slice( 1, 2) : \" + arr.slice( 1, 2) ); \nconsole.log(\"arr.slice( 1, 3) : \" + arr.slice( 1, 3) );\n" }, { "code": null, "e": 2808, "s": 2748, "text": "On compiling, it will generate the same code in JavaScript." }, { "code": null, "e": 2835, "s": 2808, "text": "Its output is as follows −" }, { "code": null, "e": 2894, "s": 2835, "text": "arr.slice( 1, 2) : mango \narr.slice( 1, 3) : mango,banana\n" }, { "code": null, "e": 2927, "s": 2894, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 2941, "s": 2927, "text": " Antonio Papa" }, { "code": null, "e": 2974, "s": 2941, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 2988, "s": 2974, "text": " Haider Malik" }, { "code": null, "e": 3023, "s": 2988, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3043, "s": 3023, "text": " Skillbakerystudios" }, { "code": null, "e": 3076, "s": 3043, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 3090, "s": 3076, "text": " Sean Bradley" }, { "code": null, "e": 3125, "s": 3090, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3141, "s": 3125, "text": " TELCOMA Global" }, { "code": null, "e": 3174, "s": 3141, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 3194, "s": 3174, "text": " Christopher Frewin" }, { "code": null, "e": 3201, "s": 3194, "text": " Print" }, { "code": null, "e": 3212, "s": 3201, "text": " Add Notes" } ]
Find the sum of the diagonal elements of the given N X N spiral matrix - GeeksforGeeks
13 Dec, 2021 Given N which is the size of the N X N spiral matrix of the form: 16 15 14 13 5 4 3 12 6 1 2 11 7 8 9 10 The task is to find the sum of the diagonal elements of this matrix.Examples: Input: N = 3 Output: 25 5 4 3 6 1 2 7 8 9 The sum of elements along its two diagonals will be 1 + 3 + 7 + 5 + 9 = 25 Input: N = 5 Output: 101 Recursive Approach: The idea behind the solution is to use recursion to compute sum of the diagonal elements. 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 to return the sum of both the// diagonal elements of the required matrixint findSum(int n){ // Base cases if(n == 0) { return 0; } if(n == 1) { return 1; } int ans = 0; // Computing for ans for (int i = 2; i <= n; i++) { ans =(4 * (i * i)) - 6 * (i - 1) + findSum(n - 2); } // Return ans; return ans;} // Driver codeint main(){ int n = 4; cout << findSum(n); return 0;} // Java implementation of the approachimport java.util.*; public class GFG{ // Function to return the sum of both the// diagonal elements of the required matrixstatic int findSum(int n){ // Base cases if(n == 0) { return 0; } if(n == 1) { return 1; } int ans = 0; // Computing for ans for (int i = 2; i <= n; i++) { ans =(4 * (i * i)) - 6 * (i - 1) + findSum(n - 2); } // Return ans; return ans;} // Driver codepublic static void main(String args[]){ int n = 4; System.out.println(findSum(n)); }}// This code is contributed by Samim Hossain Mondal. # Python 3 implementation of the approach # Function to return the sum of both the# diagonal elements of the required matrixdef findSum(n): # Base cases if(n == 0): return 0 if(n == 1): return 1 ans = 0 # Computing for ans for i in range(2, n + 1, 1): ans = ((4 * (i * i)) - 6 * (i - 1) + findSum(n - 2)) return ans # Driver codeif __name__ == '__main__': n = 4 print(findSum(n)) # This code is contributed by# Samim Hossain Mondal // C# implementation of the approachusing System; class GFG{ // Function to return the sum of both the// diagonal elements of the required matrixstatic int findSum(int n){ // Base cases if(n == 0) { return 0; } if(n == 1) { return 1; } int ans = 0; // Computing for ans for (int i = 2; i <= n; i++) { ans =(4 * (i * i)) - 6 * (i - 1) + findSum(n - 2); } // Return ans; return ans;} // Driver codepublic static void Main(){ int n = 4; Console.Write(findSum(n)); }}// This code is contributed by Samim Hossain Mondal. <script>// Javascript implementation of the approach // Function to return the sum of both the// diagonal elements of the required matrixfunction findSum(n){ // Base cases if(n == 0) { return 0; } if(n == 1) { return 1; } let ans = 0; // Computing for ans for (let i = 2; i <= n; i++) { ans =(4 * (i * i)) - 6 * (i - 1) + findSum(n - 2); } // Return ans; return ans;} // Driver codelet n = 4;document.write(findSum(n)); // This code is contributed by Samim Hossain Mondal.</script> 56 Time Complexity: O(2N) Auxiliary Space: 1 Dynamic Programming Approach: Idea behind the solution is to use the concept of Dynamic Programming. We will use array dp[] to store our solution. N given in the problem can either be even or odd. When i is odd, we have to add only 4 corner elements in dp[i – 2]. dp[i] = dp[i – 2] + (i – 2) * (i – 2) + (i – 1) + (i – 2) * (i – 2) + 2 * (i – 1) + (i – 2) * (i – 2) + 3 * (i – 1) + (i – 2) * (i – 2) + 4 * (i – 1) dp[i] = dp[i – 2] + 4 * (i – 2) * (i – 2) + 10 * (i – 1) dp[i] = dp[i – 2] + 4 * (i) * (i) – 6 * (i – 1) Similarly, we can check that the above formula is true when i is even.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of both the// diagonal elements of the required matrixint findSum(int n){ // Array to store sum of diagonal elements int dp[n + 1]; // Base cases dp[1] = 1; dp[0] = 0; // Computing the value of dp for (int i = 2; i <= n; i++) { dp[i] = (4 * (i * i)) - 6 * (i - 1) + dp[i - 2]; } return dp[n];} // Driver codeint main(){ int n = 4; cout << findSum(n); return 0;} // Java implementation of the approachclass GFG{ // Function to return the sum of both the// diagonal elements of the required matrixstatic int findSum(int n){ // Array to store sum of diagonal elements int[] dp = new int[n + 1]; // Base cases dp[1] = 1; dp[0] = 0; // Computing the value of dp for (int i = 2; i <= n; i++) { dp[i] = (4 * (i * i)) - 6 * (i - 1) + dp[i - 2]; } return dp[n];} // Driver codepublic static void main(String args[]){ int n = 4; System.out.println(findSum(n));}} // This code is contributed by Akanksha Rai # Python 3 implementation of the approach # Function to return the sum of both the# diagonal elements of the required matrixdef findSum(n): # Array to store sum of diagonal elements dp = [0 for i in range(n + 1)] # Base cases dp[1] = 1 dp[0] = 0 # Computing the value of dp for i in range(2, n + 1, 1): dp[i] = ((4 * (i * i)) - 6 * (i - 1) + dp[i - 2]) return dp[n] # Driver codeif __name__ == '__main__': n = 4 print(findSum(n)) # This code is contributed by# Surendra_Gangwar // C# implementation of the approach class GFG{ // Function to return the sum of both the// diagonal elements of the required matrixstatic int findSum(int n){ // Array to store sum of diagonal elements int[] dp = new int[n + 1]; // Base cases dp[1] = 1; dp[0] = 0; // Computing the value of dp for (int i = 2; i <= n; i++) { dp[i] = (4 * (i * i)) - 6 * (i - 1) + dp[i - 2]; } return dp[n];} // Driver codestatic void Main(){ int n = 4; System.Console.WriteLine(findSum(n));}} // This code is contributed by mits <?php// PHP implementation of the approach // Function to return the sum of both the// diagonal elements of the required matrixfunction findSum($n){ // Array to store sum of diagonal elements $dp = array(); // Base cases $dp[1] = 1; $dp[0] = 0; // Computing the value of dp for ($i = 2; $i <= $n; $i++) { $dp[$i] = (4 * ($i * $i)) - 6 * ($i - 1) + $dp[$i - 2]; } return $dp[$n];} // Driver code$n = 4; echo findSum($n); // This code is contributed by Akanksha Rai?> <script>// Javascript implementation of the approach // Function to return the sum of both the// diagonal elements of the required matrixlet findSum(n){ // Array to store sum of diagonal elements let dp = new Array(n + 1); // Base cases dp[1] = 1; dp[0] = 0; // Computing the value of dp for (let i = 2; i <= n; i++) { dp[i] = (4 * (i * i)) - 6 * (i - 1) + dp[i - 2]; } return dp[n];} // Driver codelet n = 4; document.write(findSum(n)); // This code is contributed by rishavmahato348.</script> 56 Time Complexity: O(N)Auxiliary Space: O(N) SURENDRA_GANGWAR Akanksha_Rai Mithun Kumar rishavmahato348 pankajsharmagfg samim2000 amartyaghoshgfg Algorithms Arrays Dynamic Programming Matrix Arrays Dynamic Programming Matrix Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? K means Clustering - Introduction Quadratic Probing in Hashing Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 26053, "s": 26025, "text": "\n13 Dec, 2021" }, { "code": null, "e": 26121, "s": 26053, "text": "Given N which is the size of the N X N spiral matrix of the form: " }, { "code": null, "e": 26169, "s": 26121, "text": "16 15 14 13\n5 4 3 12\n6 1 2 11\n7 8 9 10" }, { "code": null, "e": 26249, "s": 26169, "text": "The task is to find the sum of the diagonal elements of this matrix.Examples: " }, { "code": null, "e": 26393, "s": 26249, "text": "Input: N = 3\nOutput: 25\n5 4 3\n6 1 2\n7 8 9\nThe sum of elements along its two diagonals will be \n1 + 3 + 7 + 5 + 9 = 25\n\nInput: N = 5\nOutput: 101" }, { "code": null, "e": 26506, "s": 26395, "text": "Recursive Approach: The idea behind the solution is to use recursion to compute sum of the diagonal elements. " }, { "code": null, "e": 26558, "s": 26506, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26562, "s": 26558, "text": "C++" }, { "code": null, "e": 26567, "s": 26562, "text": "Java" }, { "code": null, "e": 26575, "s": 26567, "text": "Python3" }, { "code": null, "e": 26578, "s": 26575, "text": "C#" }, { "code": null, "e": 26589, "s": 26578, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of both the// diagonal elements of the required matrixint findSum(int n){ // Base cases if(n == 0) { return 0; } if(n == 1) { return 1; } int ans = 0; // Computing for ans for (int i = 2; i <= n; i++) { ans =(4 * (i * i)) - 6 * (i - 1) + findSum(n - 2); } // Return ans; return ans;} // Driver codeint main(){ int n = 4; cout << findSum(n); return 0;}", "e": 27138, "s": 26589, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; public class GFG{ // Function to return the sum of both the// diagonal elements of the required matrixstatic int findSum(int n){ // Base cases if(n == 0) { return 0; } if(n == 1) { return 1; } int ans = 0; // Computing for ans for (int i = 2; i <= n; i++) { ans =(4 * (i * i)) - 6 * (i - 1) + findSum(n - 2); } // Return ans; return ans;} // Driver codepublic static void main(String args[]){ int n = 4; System.out.println(findSum(n)); }}// This code is contributed by Samim Hossain Mondal.", "e": 27778, "s": 27138, "text": null }, { "code": "# Python 3 implementation of the approach # Function to return the sum of both the# diagonal elements of the required matrixdef findSum(n): # Base cases if(n == 0): return 0 if(n == 1): return 1 ans = 0 # Computing for ans for i in range(2, n + 1, 1): ans = ((4 * (i * i)) - 6 * (i - 1) + findSum(n - 2)) return ans # Driver codeif __name__ == '__main__': n = 4 print(findSum(n)) # This code is contributed by# Samim Hossain Mondal", "e": 28296, "s": 27778, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the sum of both the// diagonal elements of the required matrixstatic int findSum(int n){ // Base cases if(n == 0) { return 0; } if(n == 1) { return 1; } int ans = 0; // Computing for ans for (int i = 2; i <= n; i++) { ans =(4 * (i * i)) - 6 * (i - 1) + findSum(n - 2); } // Return ans; return ans;} // Driver codepublic static void Main(){ int n = 4; Console.Write(findSum(n)); }}// This code is contributed by Samim Hossain Mondal.", "e": 28903, "s": 28296, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the sum of both the// diagonal elements of the required matrixfunction findSum(n){ // Base cases if(n == 0) { return 0; } if(n == 1) { return 1; } let ans = 0; // Computing for ans for (let i = 2; i <= n; i++) { ans =(4 * (i * i)) - 6 * (i - 1) + findSum(n - 2); } // Return ans; return ans;} // Driver codelet n = 4;document.write(findSum(n)); // This code is contributed by Samim Hossain Mondal.</script>", "e": 29459, "s": 28903, "text": null }, { "code": null, "e": 29462, "s": 29459, "text": "56" }, { "code": null, "e": 29485, "s": 29462, "text": "Time Complexity: O(2N)" }, { "code": null, "e": 29504, "s": 29485, "text": "Auxiliary Space: 1" }, { "code": null, "e": 29770, "s": 29504, "text": "Dynamic Programming Approach: Idea behind the solution is to use the concept of Dynamic Programming. We will use array dp[] to store our solution. N given in the problem can either be even or odd. When i is odd, we have to add only 4 corner elements in dp[i – 2]. " }, { "code": null, "e": 30027, "s": 29770, "text": "dp[i] = dp[i – 2] + (i – 2) * (i – 2) + (i – 1) + (i – 2) * (i – 2) + 2 * (i – 1) + (i – 2) * (i – 2) + 3 * (i – 1) + (i – 2) * (i – 2) + 4 * (i – 1) dp[i] = dp[i – 2] + 4 * (i – 2) * (i – 2) + 10 * (i – 1) dp[i] = dp[i – 2] + 4 * (i) * (i) – 6 * (i – 1) " }, { "code": null, "e": 30150, "s": 30027, "text": "Similarly, we can check that the above formula is true when i is even.Below is the implementation of the above approach: " }, { "code": null, "e": 30154, "s": 30150, "text": "C++" }, { "code": null, "e": 30159, "s": 30154, "text": "Java" }, { "code": null, "e": 30167, "s": 30159, "text": "Python3" }, { "code": null, "e": 30170, "s": 30167, "text": "C#" }, { "code": null, "e": 30174, "s": 30170, "text": "PHP" }, { "code": null, "e": 30185, "s": 30174, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of both the// diagonal elements of the required matrixint findSum(int n){ // Array to store sum of diagonal elements int dp[n + 1]; // Base cases dp[1] = 1; dp[0] = 0; // Computing the value of dp for (int i = 2; i <= n; i++) { dp[i] = (4 * (i * i)) - 6 * (i - 1) + dp[i - 2]; } return dp[n];} // Driver codeint main(){ int n = 4; cout << findSum(n); return 0;}", "e": 30722, "s": 30185, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the sum of both the// diagonal elements of the required matrixstatic int findSum(int n){ // Array to store sum of diagonal elements int[] dp = new int[n + 1]; // Base cases dp[1] = 1; dp[0] = 0; // Computing the value of dp for (int i = 2; i <= n; i++) { dp[i] = (4 * (i * i)) - 6 * (i - 1) + dp[i - 2]; } return dp[n];} // Driver codepublic static void main(String args[]){ int n = 4; System.out.println(findSum(n));}} // This code is contributed by Akanksha Rai", "e": 31327, "s": 30722, "text": null }, { "code": "# Python 3 implementation of the approach # Function to return the sum of both the# diagonal elements of the required matrixdef findSum(n): # Array to store sum of diagonal elements dp = [0 for i in range(n + 1)] # Base cases dp[1] = 1 dp[0] = 0 # Computing the value of dp for i in range(2, n + 1, 1): dp[i] = ((4 * (i * i)) - 6 * (i - 1) + dp[i - 2]) return dp[n] # Driver codeif __name__ == '__main__': n = 4 print(findSum(n)) # This code is contributed by# Surendra_Gangwar", "e": 31872, "s": 31327, "text": null }, { "code": "// C# implementation of the approach class GFG{ // Function to return the sum of both the// diagonal elements of the required matrixstatic int findSum(int n){ // Array to store sum of diagonal elements int[] dp = new int[n + 1]; // Base cases dp[1] = 1; dp[0] = 0; // Computing the value of dp for (int i = 2; i <= n; i++) { dp[i] = (4 * (i * i)) - 6 * (i - 1) + dp[i - 2]; } return dp[n];} // Driver codestatic void Main(){ int n = 4; System.Console.WriteLine(findSum(n));}} // This code is contributed by mits", "e": 32450, "s": 31872, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the sum of both the// diagonal elements of the required matrixfunction findSum($n){ // Array to store sum of diagonal elements $dp = array(); // Base cases $dp[1] = 1; $dp[0] = 0; // Computing the value of dp for ($i = 2; $i <= $n; $i++) { $dp[$i] = (4 * ($i * $i)) - 6 * ($i - 1) + $dp[$i - 2]; } return $dp[$n];} // Driver code$n = 4; echo findSum($n); // This code is contributed by Akanksha Rai?>", "e": 32983, "s": 32450, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the sum of both the// diagonal elements of the required matrixlet findSum(n){ // Array to store sum of diagonal elements let dp = new Array(n + 1); // Base cases dp[1] = 1; dp[0] = 0; // Computing the value of dp for (let i = 2; i <= n; i++) { dp[i] = (4 * (i * i)) - 6 * (i - 1) + dp[i - 2]; } return dp[n];} // Driver codelet n = 4; document.write(findSum(n)); // This code is contributed by rishavmahato348.</script>", "e": 33531, "s": 32983, "text": null }, { "code": null, "e": 33534, "s": 33531, "text": "56" }, { "code": null, "e": 33577, "s": 33534, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 33594, "s": 33577, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33607, "s": 33594, "text": "Akanksha_Rai" }, { "code": null, "e": 33620, "s": 33607, "text": "Mithun Kumar" }, { "code": null, "e": 33636, "s": 33620, "text": "rishavmahato348" }, { "code": null, "e": 33652, "s": 33636, "text": "pankajsharmagfg" }, { "code": null, "e": 33662, "s": 33652, "text": "samim2000" }, { "code": null, "e": 33678, "s": 33662, "text": "amartyaghoshgfg" }, { "code": null, "e": 33689, "s": 33678, "text": "Algorithms" }, { "code": null, "e": 33696, "s": 33689, "text": "Arrays" }, { "code": null, "e": 33716, "s": 33696, "text": "Dynamic Programming" }, { "code": null, "e": 33723, "s": 33716, "text": "Matrix" }, { "code": null, "e": 33730, "s": 33723, "text": "Arrays" }, { "code": null, "e": 33750, "s": 33730, "text": "Dynamic Programming" }, { "code": null, "e": 33757, "s": 33750, "text": "Matrix" }, { "code": null, "e": 33768, "s": 33757, "text": "Algorithms" }, { "code": null, "e": 33866, "s": 33768, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33891, "s": 33866, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33918, "s": 33891, "text": "How to Start Learning DSA?" }, { "code": null, "e": 33952, "s": 33918, "text": "K means Clustering - Introduction" }, { "code": null, "e": 33981, "s": 33952, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 34048, "s": 33981, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 34063, "s": 34048, "text": "Arrays in Java" }, { "code": null, "e": 34079, "s": 34063, "text": "Arrays in C/C++" }, { "code": null, "e": 34147, "s": 34079, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34193, "s": 34147, "text": "Write a program to reverse an array or string" } ]
Count of permutations such that sum of K numbers from given range is even - GeeksforGeeks
29 Jun, 2021 Given a range [low, high], both inclusive, and an integer K, the task is to select K numbers from the range(a number can be chosen multiple times) such that the sum of those K numbers is even. Print the number of all such permutations. Examples: Input: low = 4, high = 5, k = 3 Output: 4 Explanation: There are 4 valid permutation. They are {4, 4, 4}, {4, 5, 5}, {5, 4, 5} and {5, 5, 4} which sum up to an even number. Input: low = 1, high = 10, k = 2 Output: 50 Explanation: There are 50 valid permutations. They are {1, 1}, {1, 3}, .. {1, 9} {2, 2}, {2, 4}, ..., {2, 10}, ..., {10, 2}, {10, 4}, ... {10, 10}. These 50 permutations, each sum up to an even number. Naive Approach: The idea is to find all subset of size K such that the sum of the subset is even and also calculate permutation for each required subset. Time Complexity: O(K * (2K)) Auxiliary Space: O(K) Efficient Approach: The idea is to use the fact that the sum of two even and odd numbers is always even. Follow the steps below to solve the problem: Find the total count of even and odd numbers in the given range [low, high].Initialize variable even_sum = 1 and odd_sum = 0 to store way to get even sum and odd sum respectively.Iterate a loop K times and store the previous even sum as prev_even = even_sum and the previous odd sum as prev_odd = odd_sum where even_sum = (prev_even*even_count) + (prev_odd*odd_count) and odd_sum = (prev_even*odd_count) + (prev_odd*even_count).Print the even_sum at the end as there is a count for the odd sum because the previous odd_sum will contribute to the next even_sum. Find the total count of even and odd numbers in the given range [low, high]. Initialize variable even_sum = 1 and odd_sum = 0 to store way to get even sum and odd sum respectively. Iterate a loop K times and store the previous even sum as prev_even = even_sum and the previous odd sum as prev_odd = odd_sum where even_sum = (prev_even*even_count) + (prev_odd*odd_count) and odd_sum = (prev_even*odd_count) + (prev_odd*even_count). Print the even_sum at the end as there is a count for the odd sum because the previous odd_sum will contribute to the next even_sum. 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 to return the number// of all permutations such that// sum of K numbers in range is evenint countEvenSum(int low, int high, int k){ // Find total count of even and // odd number in given range int even_count = high / 2 - (low - 1) / 2; int odd_count = (high + 1) / 2 - low / 2; long even_sum = 1; long odd_sum = 0; // Iterate loop k times and update // even_sum & odd_sum using // previous values for(int i = 0; i < k; i++) { // Update the prev_even and // odd_sum long prev_even = even_sum; long prev_odd = odd_sum; // Even sum even_sum = (prev_even * even_count) + (prev_odd * odd_count); // Odd sum odd_sum = (prev_even * odd_count) + (prev_odd * even_count); } // Return even_sum cout << (even_sum);} // Driver Codeint main(){ // Given ranges int low = 4; int high = 5; // Length of permutation int K = 3; // Function call countEvenSum(low, high, K);} // This code is contributed by Stream_Cipher // Java program for the above approachimport java.util.*; class GFG { // Function to return the number // of all permutations such that // sum of K numbers in range is even public static void countEvenSum(int low, int high, int k) { // Find total count of even and // odd number in given range int even_count = high / 2 - (low - 1) / 2; int odd_count = (high + 1) / 2 - low / 2; long even_sum = 1; long odd_sum = 0; // Iterate loop k times and update // even_sum & odd_sum using // previous values for (int i = 0; i < k; i++) { // Update the prev_even and // odd_sum long prev_even = even_sum; long prev_odd = odd_sum; // Even sum even_sum = (prev_even * even_count) + (prev_odd * odd_count); // Odd sum odd_sum = (prev_even * odd_count) + (prev_odd * even_count); } // Return even_sum System.out.println(even_sum); } // Driver Code public static void main(String[] args) { // Given ranges int low = 4; int high = 5; // Length of permutation int K = 3; // Function call countEvenSum(low, high, K); }} # Python3 program for the above approach # Function to return the number# of all permutations such that# sum of K numbers in range is evendef countEvenSum(low, high, k): # Find total count of even and # odd number in given range even_count = high / 2 - (low - 1) / 2 odd_count = (high + 1) / 2 - low / 2 even_sum = 1 odd_sum = 0 # Iterate loop k times and update # even_sum & odd_sum using # previous values for i in range(0, k): # Update the prev_even and # odd_sum prev_even = even_sum prev_odd = odd_sum # Even sum even_sum = ((prev_even * even_count) + (prev_odd * odd_count)) # Odd sum odd_sum = ((prev_even * odd_count) + (prev_odd * even_count)) # Return even_sum print(int(even_sum)) # Driver Code # Given rangeslow = 4;high = 5; # Length of permutationK = 3; # Function callcountEvenSum(low, high, K); # This code is contributed by Stream_Cipher // C# program for the above approachusing System; class GFG{ // Function to return the number// of all permutations such that// sum of K numbers in range is evenpublic static void countEvenSum(int low, int high, int k){ // Find total count of even and // odd number in given range int even_count = high / 2 - (low - 1) / 2; int odd_count = (high + 1) / 2 - low / 2; long even_sum = 1; long odd_sum = 0; // Iterate loop k times and update // even_sum & odd_sum using // previous values for(int i = 0; i < k; i++) { // Update the prev_even and // odd_sum long prev_even = even_sum; long prev_odd = odd_sum; // Even sum even_sum = (prev_even * even_count) + (prev_odd * odd_count); // Odd sum odd_sum = (prev_even * odd_count) + (prev_odd * even_count); } // Return even_sum Console.WriteLine(even_sum);} // Driver Codepublic static void Main(String[] args){ // Given ranges int low = 4; int high = 5; // Length of permutation int K = 3; // Function call countEvenSum(low, high, K);}} // This code is contributed by amal kumar choubey <script> // JavaScript program for the above approach // Function to return the number // of all permutations such that // sum of K numbers in range is even function countEvenSum(low, high, k) { // Find total count of even and // odd number in given range let even_count = high / 2 - (low - 1) / 2; let odd_count = (high + 1) / 2 - low / 2; let even_sum = 1; let odd_sum = 0; // Iterate loop k times and update // even_sum & odd_sum using // previous values for (let i = 0; i < k; i++) { // Update the prev_even and // odd_sum let prev_even = even_sum; let prev_odd = odd_sum; // Even sum even_sum = (prev_even * even_count) + (prev_odd * odd_count); // Odd sum odd_sum = (prev_even * odd_count) + (prev_odd * even_count); } // Return even_sum document.write(even_sum); } // Driver Code // Given ranges let low = 4; let high = 5; // Length of permutation let K = 3; // Function call countEvenSum(low, high, K); </script> 4 Time Complexity: O(K)Auxiliary Space: O(1) Amal Kumar Choubey Stream_Cipher susmitakundugoaldanga saurabh1990aror Adobe array-range-queries permutation Permutation and Combination Arrays Dynamic Programming Greedy Mathematical Adobe Arrays Dynamic Programming Greedy Mathematical permutation 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 Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26707, "s": 26679, "text": "\n29 Jun, 2021" }, { "code": null, "e": 26943, "s": 26707, "text": "Given a range [low, high], both inclusive, and an integer K, the task is to select K numbers from the range(a number can be chosen multiple times) such that the sum of those K numbers is even. Print the number of all such permutations." }, { "code": null, "e": 26953, "s": 26943, "text": "Examples:" }, { "code": null, "e": 27126, "s": 26953, "text": "Input: low = 4, high = 5, k = 3 Output: 4 Explanation: There are 4 valid permutation. They are {4, 4, 4}, {4, 5, 5}, {5, 4, 5} and {5, 5, 4} which sum up to an even number." }, { "code": null, "e": 27372, "s": 27126, "text": "Input: low = 1, high = 10, k = 2 Output: 50 Explanation: There are 50 valid permutations. They are {1, 1}, {1, 3}, .. {1, 9} {2, 2}, {2, 4}, ..., {2, 10}, ..., {10, 2}, {10, 4}, ... {10, 10}. These 50 permutations, each sum up to an even number." }, { "code": null, "e": 27577, "s": 27372, "text": "Naive Approach: The idea is to find all subset of size K such that the sum of the subset is even and also calculate permutation for each required subset. Time Complexity: O(K * (2K)) Auxiliary Space: O(K)" }, { "code": null, "e": 27729, "s": 27577, "text": "Efficient Approach: The idea is to use the fact that the sum of two even and odd numbers is always even. Follow the steps below to solve the problem: " }, { "code": null, "e": 28290, "s": 27729, "text": "Find the total count of even and odd numbers in the given range [low, high].Initialize variable even_sum = 1 and odd_sum = 0 to store way to get even sum and odd sum respectively.Iterate a loop K times and store the previous even sum as prev_even = even_sum and the previous odd sum as prev_odd = odd_sum where even_sum = (prev_even*even_count) + (prev_odd*odd_count) and odd_sum = (prev_even*odd_count) + (prev_odd*even_count).Print the even_sum at the end as there is a count for the odd sum because the previous odd_sum will contribute to the next even_sum." }, { "code": null, "e": 28367, "s": 28290, "text": "Find the total count of even and odd numbers in the given range [low, high]." }, { "code": null, "e": 28471, "s": 28367, "text": "Initialize variable even_sum = 1 and odd_sum = 0 to store way to get even sum and odd sum respectively." }, { "code": null, "e": 28721, "s": 28471, "text": "Iterate a loop K times and store the previous even sum as prev_even = even_sum and the previous odd sum as prev_odd = odd_sum where even_sum = (prev_even*even_count) + (prev_odd*odd_count) and odd_sum = (prev_even*odd_count) + (prev_odd*even_count)." }, { "code": null, "e": 28854, "s": 28721, "text": "Print the even_sum at the end as there is a count for the odd sum because the previous odd_sum will contribute to the next even_sum." }, { "code": null, "e": 28906, "s": 28854, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28910, "s": 28906, "text": "C++" }, { "code": null, "e": 28915, "s": 28910, "text": "Java" }, { "code": null, "e": 28923, "s": 28915, "text": "Python3" }, { "code": null, "e": 28926, "s": 28923, "text": "C#" }, { "code": null, "e": 28937, "s": 28926, "text": "Javascript" }, { "code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to return the number// of all permutations such that// sum of K numbers in range is evenint countEvenSum(int low, int high, int k){ // Find total count of even and // odd number in given range int even_count = high / 2 - (low - 1) / 2; int odd_count = (high + 1) / 2 - low / 2; long even_sum = 1; long odd_sum = 0; // Iterate loop k times and update // even_sum & odd_sum using // previous values for(int i = 0; i < k; i++) { // Update the prev_even and // odd_sum long prev_even = even_sum; long prev_odd = odd_sum; // Even sum even_sum = (prev_even * even_count) + (prev_odd * odd_count); // Odd sum odd_sum = (prev_even * odd_count) + (prev_odd * even_count); } // Return even_sum cout << (even_sum);} // Driver Codeint main(){ // Given ranges int low = 4; int high = 5; // Length of permutation int K = 3; // Function call countEvenSum(low, high, K);} // This code is contributed by Stream_Cipher", "e": 30117, "s": 28937, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG { // Function to return the number // of all permutations such that // sum of K numbers in range is even public static void countEvenSum(int low, int high, int k) { // Find total count of even and // odd number in given range int even_count = high / 2 - (low - 1) / 2; int odd_count = (high + 1) / 2 - low / 2; long even_sum = 1; long odd_sum = 0; // Iterate loop k times and update // even_sum & odd_sum using // previous values for (int i = 0; i < k; i++) { // Update the prev_even and // odd_sum long prev_even = even_sum; long prev_odd = odd_sum; // Even sum even_sum = (prev_even * even_count) + (prev_odd * odd_count); // Odd sum odd_sum = (prev_even * odd_count) + (prev_odd * even_count); } // Return even_sum System.out.println(even_sum); } // Driver Code public static void main(String[] args) { // Given ranges int low = 4; int high = 5; // Length of permutation int K = 3; // Function call countEvenSum(low, high, K); }}", "e": 31448, "s": 30117, "text": null }, { "code": "# Python3 program for the above approach # Function to return the number# of all permutations such that# sum of K numbers in range is evendef countEvenSum(low, high, k): # Find total count of even and # odd number in given range even_count = high / 2 - (low - 1) / 2 odd_count = (high + 1) / 2 - low / 2 even_sum = 1 odd_sum = 0 # Iterate loop k times and update # even_sum & odd_sum using # previous values for i in range(0, k): # Update the prev_even and # odd_sum prev_even = even_sum prev_odd = odd_sum # Even sum even_sum = ((prev_even * even_count) + (prev_odd * odd_count)) # Odd sum odd_sum = ((prev_even * odd_count) + (prev_odd * even_count)) # Return even_sum print(int(even_sum)) # Driver Code # Given rangeslow = 4;high = 5; # Length of permutationK = 3; # Function callcountEvenSum(low, high, K); # This code is contributed by Stream_Cipher", "e": 32449, "s": 31448, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to return the number// of all permutations such that// sum of K numbers in range is evenpublic static void countEvenSum(int low, int high, int k){ // Find total count of even and // odd number in given range int even_count = high / 2 - (low - 1) / 2; int odd_count = (high + 1) / 2 - low / 2; long even_sum = 1; long odd_sum = 0; // Iterate loop k times and update // even_sum & odd_sum using // previous values for(int i = 0; i < k; i++) { // Update the prev_even and // odd_sum long prev_even = even_sum; long prev_odd = odd_sum; // Even sum even_sum = (prev_even * even_count) + (prev_odd * odd_count); // Odd sum odd_sum = (prev_even * odd_count) + (prev_odd * even_count); } // Return even_sum Console.WriteLine(even_sum);} // Driver Codepublic static void Main(String[] args){ // Given ranges int low = 4; int high = 5; // Length of permutation int K = 3; // Function call countEvenSum(low, high, K);}} // This code is contributed by amal kumar choubey", "e": 33694, "s": 32449, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to return the number // of all permutations such that // sum of K numbers in range is even function countEvenSum(low, high, k) { // Find total count of even and // odd number in given range let even_count = high / 2 - (low - 1) / 2; let odd_count = (high + 1) / 2 - low / 2; let even_sum = 1; let odd_sum = 0; // Iterate loop k times and update // even_sum & odd_sum using // previous values for (let i = 0; i < k; i++) { // Update the prev_even and // odd_sum let prev_even = even_sum; let prev_odd = odd_sum; // Even sum even_sum = (prev_even * even_count) + (prev_odd * odd_count); // Odd sum odd_sum = (prev_even * odd_count) + (prev_odd * even_count); } // Return even_sum document.write(even_sum); } // Driver Code // Given ranges let low = 4; let high = 5; // Length of permutation let K = 3; // Function call countEvenSum(low, high, K); </script>", "e": 34936, "s": 33694, "text": null }, { "code": null, "e": 34938, "s": 34936, "text": "4" }, { "code": null, "e": 34983, "s": 34940, "text": "Time Complexity: O(K)Auxiliary Space: O(1)" }, { "code": null, "e": 35002, "s": 34983, "text": "Amal Kumar Choubey" }, { "code": null, "e": 35016, "s": 35002, "text": "Stream_Cipher" }, { "code": null, "e": 35038, "s": 35016, "text": "susmitakundugoaldanga" }, { "code": null, "e": 35054, "s": 35038, "text": "saurabh1990aror" }, { "code": null, "e": 35060, "s": 35054, "text": "Adobe" }, { "code": null, "e": 35080, "s": 35060, "text": "array-range-queries" }, { "code": null, "e": 35092, "s": 35080, "text": "permutation" }, { "code": null, "e": 35120, "s": 35092, "text": "Permutation and Combination" }, { "code": null, "e": 35127, "s": 35120, "text": "Arrays" }, { "code": null, "e": 35147, "s": 35127, "text": "Dynamic Programming" }, { "code": null, "e": 35154, "s": 35147, "text": "Greedy" }, { "code": null, "e": 35167, "s": 35154, "text": "Mathematical" }, { "code": null, "e": 35173, "s": 35167, "text": "Adobe" }, { "code": null, "e": 35180, "s": 35173, "text": "Arrays" }, { "code": null, "e": 35200, "s": 35180, "text": "Dynamic Programming" }, { "code": null, "e": 35207, "s": 35200, "text": "Greedy" }, { "code": null, "e": 35220, "s": 35207, "text": "Mathematical" }, { "code": null, "e": 35232, "s": 35220, "text": "permutation" }, { "code": null, "e": 35330, "s": 35232, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35398, "s": 35330, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 35421, "s": 35398, "text": "Introduction to Arrays" }, { "code": null, "e": 35453, "s": 35421, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35467, "s": 35453, "text": "Linear Search" }, { "code": null, "e": 35488, "s": 35467, "text": "Linked List vs Array" }, { "code": null, "e": 35517, "s": 35488, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 35547, "s": 35517, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35581, "s": 35547, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 35612, "s": 35581, "text": "Bellman–Ford Algorithm | DP-23" } ]
ES6 - Array Method push()
push() method appends the given element(s) in the last of the array and returns the length of the new array. array.push(element1, ..., elementN); element1, ..., elementN: The elements to add to the end of the array. element1, ..., elementN: The elements to add to the end of the array. Returns the length of the new array. var numbers = new Array(1, 4, 9); var length = numbers.push(10); console.log("new numbers is : " + numbers ); length = numbers.push(20); console.log("new numbers is : " + numbers ); new numbers is : 1,4,9,10 new numbers is : 1,4,9,10,20 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2386, "s": 2277, "text": "push() method appends the given element(s) in the last of the array and returns the length of the new array." }, { "code": null, "e": 2428, "s": 2386, "text": "array.push(element1, ..., elementN); \n" }, { "code": null, "e": 2498, "s": 2428, "text": "element1, ..., elementN: The elements to add to the end of the array." }, { "code": null, "e": 2568, "s": 2498, "text": "element1, ..., elementN: The elements to add to the end of the array." }, { "code": null, "e": 2605, "s": 2568, "text": "Returns the length of the new array." }, { "code": null, "e": 2795, "s": 2605, "text": "var numbers = new Array(1, 4, 9);\nvar length = numbers.push(10); \nconsole.log(\"new numbers is : \" + numbers ); \nlength = numbers.push(20); \nconsole.log(\"new numbers is : \" + numbers ); " }, { "code": null, "e": 2852, "s": 2795, "text": "new numbers is : 1,4,9,10 \nnew numbers is : 1,4,9,10,20\n" }, { "code": null, "e": 2887, "s": 2852, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2901, "s": 2887, "text": " Sharad Kumar" }, { "code": null, "e": 2934, "s": 2901, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 2952, "s": 2934, "text": " Richa Maheshwari" }, { "code": null, "e": 2985, "s": 2952, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 2999, "s": 2985, "text": " Anadi Sharma" }, { "code": null, "e": 3034, "s": 2999, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3051, "s": 3034, "text": " Gowthami Swarna" }, { "code": null, "e": 3084, "s": 3051, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 3100, "s": 3084, "text": " Deepti Trivedi" }, { "code": null, "e": 3135, "s": 3100, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3143, "s": 3135, "text": " Shweta" }, { "code": null, "e": 3150, "s": 3143, "text": " Print" }, { "code": null, "e": 3161, "s": 3150, "text": " Add Notes" } ]
PHP program to check if a year is leap year or not
To check if a year is leap year or not in PHP, the code is as follows − Live Demo <?php function year_check($my_year){ if ($my_year % 400 == 0) print("It is a leap year"); else if ($my_year % 100 == 0) print("It is not a leap year"); else if ($my_year % 4 == 0) print("It is a leap year"); else print("It is not a leap year"); } $my_year = 1900; year_check($my_year); ?> It is not a leap year A function named ‘year_check’ is defined that takes a year as a parameter. It checks to see if the year can be divided by 400 or 4 completely, if yes, it means it is a leap year. Otherwise, it is a leap year. The value for year is defined outside the function, and the function is called by passing this year as a parameter to it. Relevant output is displayed on the console.
[ { "code": null, "e": 1134, "s": 1062, "text": "To check if a year is leap year or not in PHP, the code is as follows −" }, { "code": null, "e": 1145, "s": 1134, "text": " Live Demo" }, { "code": null, "e": 1506, "s": 1145, "text": "<?php\n function year_check($my_year){\n if ($my_year % 400 == 0)\n print(\"It is a leap year\");\n else if ($my_year % 100 == 0)\n print(\"It is not a leap year\");\n else if ($my_year % 4 == 0)\n print(\"It is a leap year\");\n else\n print(\"It is not a leap year\");\n }\n $my_year = 1900;\n year_check($my_year);\n?>" }, { "code": null, "e": 1528, "s": 1506, "text": "It is not a leap year" }, { "code": null, "e": 1904, "s": 1528, "text": "A function named ‘year_check’ is defined that takes a year as a parameter. It checks to see if the year can be divided by 400 or 4 completely, if yes, it means it is a leap year. Otherwise, it is a leap year. The value for year is defined outside the function, and the function is called by passing this year as a parameter to it. Relevant output is displayed on the console." } ]
What is onsubmit event in JavaScript?
The onsubmit event is an event that occurs when you try to submit a form. You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the web server. If validate() function returns true, the form will be submitted, otherwise, it'll not submit the data. The following example is a code snippet showing the usage of the onsubmit event − <html> <head> <script> <!-- function validation() { all validation goes here ......... return either true or false } //--> </script> </head> <body> <form method = "POST" action = "t.cgi" onsubmit = "return validate()"> ....... <input type = "submit" value = "Submit" /> </form> </body> </html>
[ { "code": null, "e": 1437, "s": 1062, "text": "The onsubmit event is an event that occurs when you try to submit a form. You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the web server. If validate() function returns true, the form will be submitted, otherwise, it'll not submit the data." }, { "code": null, "e": 1519, "s": 1437, "text": "The following example is a code snippet showing the usage of the onsubmit event −" }, { "code": null, "e": 1954, "s": 1519, "text": "<html>\n <head>\n <script>\n <!--\n function validation() {\n all validation goes here\n .........\n return either true or false\n }\n //-->\n </script>\n </head>\n <body>\n <form method = \"POST\" action = \"t.cgi\" onsubmit = \"return validate()\">\n .......\n <input type = \"submit\" value = \"Submit\" />\n </form>\n </body>\n</html>" } ]
Exception Handling in PHP - GeeksforGeeks
31 Oct, 2018 An exception is unexpected program result that can be handled by the program itself. Exception Handling in PHP is almost similar to exception handling in all programming languages.PHP provides following specialized keywords for this purpose. try: It represent block of code in which exception can arise. catch: It represent block of code that will be executed when a particular exception has been thrown. throw: It is used to throw an exception. It is also used to list the exceptions that a function throws, but doesn’t handle itself. finally: It is used in place of catch block or after catch block basically it is put for cleanup activity in PHP code. Why Exception Handling in PHP ?Following are the main advantages of exception handling over error handling Separation of error handling code from normal code: In traditional error handling code there is always if else block to handle errors. These conditions and code to handle errors got mixed so that becomes unreadable. With try Catch block code becomes readable. Grouping of error types: In PHP both basic types and objects can be thrown as exception. It can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types. Exception handling in PHP: Following code explains the flow of normal try catch block in PHP:<?php // PHP Program to illustrate normal// try catch block codefunction demo($var) { echo " Before try block"; try { echo "\n Inside try block"; // If var is zero then only if will be executed if($var == 0) { // If var is zero then only exception is thrown throw new Exception('Number is zero.'); // This line will never be executed echo "\n After throw (It will never be executed)"; } } // Catch block will be executed only // When Exception has been thrown by try block catch(Exception $e) { echo "\n Exception Caught", $e->getMessage(); } // This line will be executed whether // Exception has been thrown or not echo "\n After catch (will be always executed)";} // Exception will not be riseddemo(5); // Exception will be rised heredemo(0);?>Output: Before try block Inside try block After catch (will be always executed) Before try block Inside try block Exception CaughtNumber is zero. After catch (will be always executed) <?php // PHP Program to illustrate normal// try catch block codefunction demo($var) { echo " Before try block"; try { echo "\n Inside try block"; // If var is zero then only if will be executed if($var == 0) { // If var is zero then only exception is thrown throw new Exception('Number is zero.'); // This line will never be executed echo "\n After throw (It will never be executed)"; } } // Catch block will be executed only // When Exception has been thrown by try block catch(Exception $e) { echo "\n Exception Caught", $e->getMessage(); } // This line will be executed whether // Exception has been thrown or not echo "\n After catch (will be always executed)";} // Exception will not be riseddemo(5); // Exception will be rised heredemo(0);?> Before try block Inside try block After catch (will be always executed) Before try block Inside try block Exception CaughtNumber is zero. After catch (will be always executed) Following code explains the flow of normal try catch and finally block in PHP<?php // PHP Program to illustrate normal// try catch block codefunction demo($var) { echo " Before try block"; try { echo "\n Inside try block"; // If var is zerothen only if will be executed if($var == 0) { // If var is zero then only exception is thrown throw new Exception('Number is zero.'); // This line will never be executed echo "\n After throw it will never be executed"; } } // Catch block will be executed only // When Exception has been thrown by try block catch(Exception $e) { echo "\n Exception Caught" . $e->getMessage(); } finally { echo "\n Here cleanup activity will be done"; } // This line will be executed whether // Exception has been thrown or not echo "\n After catch it will be always executed";} // Exception will not be riseddemo(5); // Exception will be rised heredemo(0);?>Output: Before try block Inside try block Here cleanup activity will be done After catch (will be always executed) Before try block Inside try block Exception CaughtNumber is zero. Here cleanup activity will be done After catch (will be always executed) <?php // PHP Program to illustrate normal// try catch block codefunction demo($var) { echo " Before try block"; try { echo "\n Inside try block"; // If var is zerothen only if will be executed if($var == 0) { // If var is zero then only exception is thrown throw new Exception('Number is zero.'); // This line will never be executed echo "\n After throw it will never be executed"; } } // Catch block will be executed only // When Exception has been thrown by try block catch(Exception $e) { echo "\n Exception Caught" . $e->getMessage(); } finally { echo "\n Here cleanup activity will be done"; } // This line will be executed whether // Exception has been thrown or not echo "\n After catch it will be always executed";} // Exception will not be riseddemo(5); // Exception will be rised heredemo(0);?> Before try block Inside try block Here cleanup activity will be done After catch (will be always executed) Before try block Inside try block Exception CaughtNumber is zero. Here cleanup activity will be done After catch (will be always executed) Using Custom Exception Class<?phpclass myException extends Exception { function get_Message() { // Error message $errorMsg = 'Error on line '.$this->getLine(). ' in '.$this->getFile() .$this->getMessage().' is number zero'; return $errorMsg; }} function demo($a) { try { // Check if if($a == 0) { throw new myException($a); } } catch (myException $e) { // Display custom message echo $e->get_Message(); }} // This will not generate any exceptiondemo(5); // It will cause an exceptiondemo(0);?> Output:Error on line 20 in /home/45ae8dc582d50df2790517e912980806.php0 is number zero <?phpclass myException extends Exception { function get_Message() { // Error message $errorMsg = 'Error on line '.$this->getLine(). ' in '.$this->getFile() .$this->getMessage().' is number zero'; return $errorMsg; }} function demo($a) { try { // Check if if($a == 0) { throw new myException($a); } } catch (myException $e) { // Display custom message echo $e->get_Message(); }} // This will not generate any exceptiondemo(5); // It will cause an exceptiondemo(0);?> Error on line 20 in /home/45ae8dc582d50df2790517e912980806.php0 is number zero Set a Top Level Exception Handler: The set_exception_handler() function set all user defined function to all uncaught exception.<?php // PHP Program to illustrate normal// try catch block code // Function for Uncaught Exceptionfunction myException($exception) { // Details of Uncaught Exception echo "\nException: " . $exception->getMessage();} // Set Uncaught Exception handlerset_exception_handler('myException');function demo($var) { echo " Before try block"; try { echo "\n Inside try block"; // If var is zero then only if will be executed if($var == 0) { // If var is zero then only exception is thrown throw new Exception('Number is zero.'); // This line will never be executed echo "\n After throw (it will never be executed)"; } } // Catch block will be executed only // When Exception has been thrown by try block catch(Exception $e) { echo "\n Exception Caught", $e->getMessage(); } // This line will be executed whether // Exception has been thrown or not echo "\n After catch (will be always executed)"; if($var < 0) { // Uncaught Exception throw new Exception('Uncaught Exception occurred'); }} // Exception will not be riseddemo(5); // Exception will be rised heredemo(0); // Uncaught Exceptiondemo (-3);?>Output: Before try block Inside try block After catch (will be always executed) Before try block Inside try block Exception CaughtNumber is zero. After catch (will be always executed) Before try block Inside try block After catch (will be always executed) Exception: Uncaught Exception occurred <?php // PHP Program to illustrate normal// try catch block code // Function for Uncaught Exceptionfunction myException($exception) { // Details of Uncaught Exception echo "\nException: " . $exception->getMessage();} // Set Uncaught Exception handlerset_exception_handler('myException');function demo($var) { echo " Before try block"; try { echo "\n Inside try block"; // If var is zero then only if will be executed if($var == 0) { // If var is zero then only exception is thrown throw new Exception('Number is zero.'); // This line will never be executed echo "\n After throw (it will never be executed)"; } } // Catch block will be executed only // When Exception has been thrown by try block catch(Exception $e) { echo "\n Exception Caught", $e->getMessage(); } // This line will be executed whether // Exception has been thrown or not echo "\n After catch (will be always executed)"; if($var < 0) { // Uncaught Exception throw new Exception('Uncaught Exception occurred'); }} // Exception will not be riseddemo(5); // Exception will be rised heredemo(0); // Uncaught Exceptiondemo (-3);?> Before try block Inside try block After catch (will be always executed) Before try block Inside try block Exception CaughtNumber is zero. After catch (will be always executed) Before try block Inside try block After catch (will be always executed) Exception: Uncaught Exception occurred PHP PHP Programs Web Technologies 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 execute PHP code using command line ? How to pop an alert message box using PHP ? PHP in_array() Function How to convert array to string in PHP ? How to Insert Form Data into Database using PHP ? How to execute PHP code using command line ? How to pop an alert message box using PHP ? How to convert array to string in PHP ? How to delete an array element based on key in PHP?
[ { "code": null, "e": 40529, "s": 40501, "text": "\n31 Oct, 2018" }, { "code": null, "e": 40771, "s": 40529, "text": "An exception is unexpected program result that can be handled by the program itself. Exception Handling in PHP is almost similar to exception handling in all programming languages.PHP provides following specialized keywords for this purpose." }, { "code": null, "e": 40833, "s": 40771, "text": "try: It represent block of code in which exception can arise." }, { "code": null, "e": 40934, "s": 40833, "text": "catch: It represent block of code that will be executed when a particular exception has been thrown." }, { "code": null, "e": 41065, "s": 40934, "text": "throw: It is used to throw an exception. It is also used to list the exceptions that a function throws, but doesn’t handle itself." }, { "code": null, "e": 41184, "s": 41065, "text": "finally: It is used in place of catch block or after catch block basically it is put for cleanup activity in PHP code." }, { "code": null, "e": 41291, "s": 41184, "text": "Why Exception Handling in PHP ?Following are the main advantages of exception handling over error handling" }, { "code": null, "e": 41551, "s": 41291, "text": "Separation of error handling code from normal code: In traditional error handling code there is always if else block to handle errors. These conditions and code to handle errors got mixed so that becomes unreadable. With try Catch block code becomes readable." }, { "code": null, "e": 41767, "s": 41551, "text": "Grouping of error types: In PHP both basic types and objects can be thrown as exception. It can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types." }, { "code": null, "e": 41794, "s": 41767, "text": "Exception handling in PHP:" }, { "code": null, "e": 43009, "s": 41794, "text": "Following code explains the flow of normal try catch block in PHP:<?php // PHP Program to illustrate normal// try catch block codefunction demo($var) { echo \" Before try block\"; try { echo \"\\n Inside try block\"; // If var is zero then only if will be executed if($var == 0) { // If var is zero then only exception is thrown throw new Exception('Number is zero.'); // This line will never be executed echo \"\\n After throw (It will never be executed)\"; } } // Catch block will be executed only // When Exception has been thrown by try block catch(Exception $e) { echo \"\\n Exception Caught\", $e->getMessage(); } // This line will be executed whether // Exception has been thrown or not echo \"\\n After catch (will be always executed)\";} // Exception will not be riseddemo(5); // Exception will be rised heredemo(0);?>Output: Before try block\n Inside try block\n After catch (will be always executed)\n Before try block\n Inside try block\n Exception CaughtNumber is zero.\n After catch (will be always executed)\n" }, { "code": "<?php // PHP Program to illustrate normal// try catch block codefunction demo($var) { echo \" Before try block\"; try { echo \"\\n Inside try block\"; // If var is zero then only if will be executed if($var == 0) { // If var is zero then only exception is thrown throw new Exception('Number is zero.'); // This line will never be executed echo \"\\n After throw (It will never be executed)\"; } } // Catch block will be executed only // When Exception has been thrown by try block catch(Exception $e) { echo \"\\n Exception Caught\", $e->getMessage(); } // This line will be executed whether // Exception has been thrown or not echo \"\\n After catch (will be always executed)\";} // Exception will not be riseddemo(5); // Exception will be rised heredemo(0);?>", "e": 43968, "s": 43009, "text": null }, { "code": null, "e": 44152, "s": 43968, "text": " Before try block\n Inside try block\n After catch (will be always executed)\n Before try block\n Inside try block\n Exception CaughtNumber is zero.\n After catch (will be always executed)\n" }, { "code": null, "e": 45499, "s": 44152, "text": "Following code explains the flow of normal try catch and finally block in PHP<?php // PHP Program to illustrate normal// try catch block codefunction demo($var) { echo \" Before try block\"; try { echo \"\\n Inside try block\"; // If var is zerothen only if will be executed if($var == 0) { // If var is zero then only exception is thrown throw new Exception('Number is zero.'); // This line will never be executed echo \"\\n After throw it will never be executed\"; } } // Catch block will be executed only // When Exception has been thrown by try block catch(Exception $e) { echo \"\\n Exception Caught\" . $e->getMessage(); } finally { echo \"\\n Here cleanup activity will be done\"; } // This line will be executed whether // Exception has been thrown or not echo \"\\n After catch it will be always executed\";} // Exception will not be riseddemo(5); // Exception will be rised heredemo(0);?>Output: Before try block\n Inside try block\n Here cleanup activity will be done\n After catch (will be always executed)\n Before try block\n Inside try block\n Exception CaughtNumber is zero.\n Here cleanup activity will be done\n After catch (will be always executed)\n" }, { "code": "<?php // PHP Program to illustrate normal// try catch block codefunction demo($var) { echo \" Before try block\"; try { echo \"\\n Inside try block\"; // If var is zerothen only if will be executed if($var == 0) { // If var is zero then only exception is thrown throw new Exception('Number is zero.'); // This line will never be executed echo \"\\n After throw it will never be executed\"; } } // Catch block will be executed only // When Exception has been thrown by try block catch(Exception $e) { echo \"\\n Exception Caught\" . $e->getMessage(); } finally { echo \"\\n Here cleanup activity will be done\"; } // This line will be executed whether // Exception has been thrown or not echo \"\\n After catch it will be always executed\";} // Exception will not be riseddemo(5); // Exception will be rised heredemo(0);?>", "e": 46507, "s": 45499, "text": null }, { "code": null, "e": 46763, "s": 46507, "text": " Before try block\n Inside try block\n Here cleanup activity will be done\n After catch (will be always executed)\n Before try block\n Inside try block\n Exception CaughtNumber is zero.\n Here cleanup activity will be done\n After catch (will be always executed)\n" }, { "code": null, "e": 47486, "s": 46763, "text": "Using Custom Exception Class<?phpclass myException extends Exception { function get_Message() { // Error message $errorMsg = 'Error on line '.$this->getLine(). ' in '.$this->getFile() .$this->getMessage().' is number zero'; return $errorMsg; }} function demo($a) { try { // Check if if($a == 0) { throw new myException($a); } } catch (myException $e) { // Display custom message echo $e->get_Message(); }} // This will not generate any exceptiondemo(5); // It will cause an exceptiondemo(0);?> Output:Error on line 20 in /home/45ae8dc582d50df2790517e912980806.php0 is number zero\n" }, { "code": "<?phpclass myException extends Exception { function get_Message() { // Error message $errorMsg = 'Error on line '.$this->getLine(). ' in '.$this->getFile() .$this->getMessage().' is number zero'; return $errorMsg; }} function demo($a) { try { // Check if if($a == 0) { throw new myException($a); } } catch (myException $e) { // Display custom message echo $e->get_Message(); }} // This will not generate any exceptiondemo(5); // It will cause an exceptiondemo(0);?> ", "e": 48095, "s": 47486, "text": null }, { "code": null, "e": 48175, "s": 48095, "text": "Error on line 20 in /home/45ae8dc582d50df2790517e912980806.php0 is number zero\n" }, { "code": null, "e": 49955, "s": 48175, "text": "Set a Top Level Exception Handler: The set_exception_handler() function set all user defined function to all uncaught exception.<?php // PHP Program to illustrate normal// try catch block code // Function for Uncaught Exceptionfunction myException($exception) { // Details of Uncaught Exception echo \"\\nException: \" . $exception->getMessage();} // Set Uncaught Exception handlerset_exception_handler('myException');function demo($var) { echo \" Before try block\"; try { echo \"\\n Inside try block\"; // If var is zero then only if will be executed if($var == 0) { // If var is zero then only exception is thrown throw new Exception('Number is zero.'); // This line will never be executed echo \"\\n After throw (it will never be executed)\"; } } // Catch block will be executed only // When Exception has been thrown by try block catch(Exception $e) { echo \"\\n Exception Caught\", $e->getMessage(); } // This line will be executed whether // Exception has been thrown or not echo \"\\n After catch (will be always executed)\"; if($var < 0) { // Uncaught Exception throw new Exception('Uncaught Exception occurred'); }} // Exception will not be riseddemo(5); // Exception will be rised heredemo(0); // Uncaught Exceptiondemo (-3);?>Output: Before try block\n Inside try block\n After catch (will be always executed)\n Before try block\n Inside try block\n Exception CaughtNumber is zero.\n After catch (will be always executed)\n Before try block\n Inside try block\n After catch (will be always executed)\n Exception: Uncaught Exception occurred\n" }, { "code": "<?php // PHP Program to illustrate normal// try catch block code // Function for Uncaught Exceptionfunction myException($exception) { // Details of Uncaught Exception echo \"\\nException: \" . $exception->getMessage();} // Set Uncaught Exception handlerset_exception_handler('myException');function demo($var) { echo \" Before try block\"; try { echo \"\\n Inside try block\"; // If var is zero then only if will be executed if($var == 0) { // If var is zero then only exception is thrown throw new Exception('Number is zero.'); // This line will never be executed echo \"\\n After throw (it will never be executed)\"; } } // Catch block will be executed only // When Exception has been thrown by try block catch(Exception $e) { echo \"\\n Exception Caught\", $e->getMessage(); } // This line will be executed whether // Exception has been thrown or not echo \"\\n After catch (will be always executed)\"; if($var < 0) { // Uncaught Exception throw new Exception('Uncaught Exception occurred'); }} // Exception will not be riseddemo(5); // Exception will be rised heredemo(0); // Uncaught Exceptiondemo (-3);?>", "e": 51302, "s": 49955, "text": null }, { "code": null, "e": 51601, "s": 51302, "text": " Before try block\n Inside try block\n After catch (will be always executed)\n Before try block\n Inside try block\n Exception CaughtNumber is zero.\n After catch (will be always executed)\n Before try block\n Inside try block\n After catch (will be always executed)\n Exception: Uncaught Exception occurred\n" }, { "code": null, "e": 51605, "s": 51601, "text": "PHP" }, { "code": null, "e": 51618, "s": 51605, "text": "PHP Programs" }, { "code": null, "e": 51635, "s": 51618, "text": "Web Technologies" }, { "code": null, "e": 51639, "s": 51635, "text": "PHP" }, { "code": null, "e": 51737, "s": 51639, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51746, "s": 51737, "text": "Comments" }, { "code": null, "e": 51759, "s": 51746, "text": "Old Comments" }, { "code": null, "e": 51809, "s": 51759, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 51854, "s": 51809, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 51898, "s": 51854, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 51922, "s": 51898, "text": "PHP in_array() Function" }, { "code": null, "e": 51962, "s": 51922, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 52012, "s": 51962, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 52057, "s": 52012, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 52101, "s": 52057, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 52141, "s": 52101, "text": "How to convert array to string in PHP ?" } ]
Tryit Editor v3.7
HTML Input types Tryit: input type = url
[ { "code": null, "e": 27, "s": 10, "text": "HTML Input types" } ]
Understanding Edge Relaxation for Dijkstra’s Algorithm and Bellman-Ford Algorithm | by Yasufumi TANIGUCHI | Towards Data Science
The purpose of the shortest paths problem is to find the shortest path from the starting vertex to the goal vertex. We widely use the algorithms to solve the shortest paths problem from competitive programming to Google Maps directions search. By understanding the key notion, “edge relaxation”, it is really easier to understand the concrete algorithms, say Dijsktra’s algorithm or Bellman-Ford algorithm. In other words, it might be difficult to make these algorithms your own without understanding edge relaxation. In this post, I focus on edge relaxation and explain the general structure to solve the shortest paths problem. Also, we’ll go through the easy algorithm and its implementation for better understanding. I use Python for the implementation. This post is structured as follows: What is the shortest paths problem?What is edge relaxation?The order of the relaxationThe shortest path on DAG and its implementation What is the shortest paths problem? What is edge relaxation? The order of the relaxation The shortest path on DAG and its implementation Please note that we don’t treat Dijkstra’s algorithm or Bellman-ford algorithm. In this post, I explain the single-source shortest paths problems out of the shortest paths problems, in which we need to find all the paths from one starting vertex to all other vertices. I define the shortest paths as the smallest weighted path from the starting vertex to the goal vertex out of all other paths in the weighted graph. Here, you can think “weighted” in the weighted path means the reaching cost to the goal vertex (some vertex). From here onward, when I say a just graph, it means a weighted graph. In the graph below, let’s think about the shortest paths from the starting vertex S to the other vertices A and B. The shortest path from the vertex S to the vertex A becomes “S→A”. In the graph above, there is the only one path from the vertex S to the vertex A, so we don’t need to care about the weights. On the other hand, we can find the two paths from the vertex S to the vertex B, which are “S→B” and “S→A→B”, and the shortest path becomes “S→A→B”. In “S→B”, the weight of the path is 3, but in “S→A→B”, the weight of the path becomes 2 and it’s shortest: 1+1=2. We can think the weight of the shortest path as the shortest distance from the starting vertex to one vertex. Here, I’ll explain the important and commonly used notion, edge relaxation, to solve the shortest paths problem. Generally, you can solve all the shortest paths problem by using edge relaxation. The edge relaxation is the operation to calculate the reaching cost to the vertex lower. More concretely, the operation will become: For the edge from the vertex u to the vertex v, if d[u]+w(u,v)<d[v] is satisfied, update d[v] to d[u]+w(u,v) The vertices u and v stand the neighbors in the graph and d[u] and d[v] stand the reaching cost to the vertices u and v respectively. Also, w(u,v) stands the weight of the edge from the vertex u to the vertex v. To summarize things up to now, we can make this figure below. Now we know we can reach the vertex u from the starting vertex S through two vertices and that path costs d[u]. Also, we can reach the vertex v from the starting vertex S through four vertices and that path costs d[v]. Here, edge relaxation updates d[v] to d[u]+w(u,v) when d[u]+w(u,v) is less than d[v]. In other words, it updates the current reaching cost to the vertex v (d[v]) to the lower reaching cost (d[u]+w(u,v)). The reason why it updates the cost is that the path through the vertex u can be shorter because the reaching cost of the path through the vertex u will be lower than the cost of the current path. Actually, the algorithms for the shortest paths problem solve the problem by repeatedly using the edge relaxation. I’ll show the example that we can solve the shortest paths problem by repeatedly using the edge relaxation. Let’s find the shortest paths for the same graph as before by the edge relaxation. I assume the starting vertex S and apply the edge relaxation to the graph to obtain the shortest paths to the vertices A and B. To apply the edge relaxation, we need to know the reaching cost, but there is no way to know it before searching, so we initialize the reaching costs for the vertices A and B as infinity (∞). The infinity cost for the vertex means that we cannot reach that vertex. On the other hands, the reaching cost from the starting vertex to the starting vertex is zero, so we set the d value of the vertex S as 0. We choose and relax the edges out-going from the vertex S first, then the edge out-going from the vertex A. First of all, we apply the edge relaxation to the edge SA. The edge SA satisfies d[S]+w(S, A)<d[A], we set d[A] as d[S]+w(S, A)=1. Here, Π[A] stands the vertex reaching before the vertex A in the path of the reaching cost d[A]. In this case, Π[A] is S. Π[A]=S means the path of the reaching cost d[A] always uses the sub-path, A←S. The details will be described below, but we can reconstruct the path by using Π. We’re relaxing the edge SB in the same way. The edge SB satisfies d[S]+w(S, B)<d[B], so we set d[B] as d[S]+w(S, B)=3. For the d[B] path reconstruction, we set Π[B] as S. Subsequently, we relax the edge AB out-going from the vertex A. The edge AB satisfies d[A]+w(A, B)<d[B], so we set d[B] as d[A]+w(A, B)=2. Once we update the d value of B, we also update Π[B] as A. From the figure above, you can find that the shortest distances from the vertex S to the vertices A and B equal to the reaching cost d. We cannot update the d value lower, so we finish the edge relaxation. Here, let’s confirm that we can reconstruct the shortest path by using Π[A]=S and Π[B]=A. In the graph above, we’re going to reconstruct the shortest path from the vertex S to vertex B as an example. From Π[B]=A, we can know we should visit the vertex A before reaching vertex B in the path to vertex B. From Π[A]=S, we can know we should visit the vertex S first and then reaching vertex A. The vertex S is the starting vertex, so we cannot traverse backward anymore. By reversing the vertices we obtained up to now, we can get the shortest path from the vertex S to vertex B, “S→A→B”. Generally, we can reconstruct the shortest path for the vertex v by back-tracking Π[v], Π[Π[v]], Π[Π[Π[v]]], ... and reversing the obtained vertices. In the section before, we don’t care about the order to relax edges, but how should we decide the order? Or do we really care about it? It seems that we can obtain the shortest path by randomly relaxing edges. This is not correct, though. Here, I’ll explain the reason why we should care about the order and how to choose the edge to relax. To tell the truth, the really bad case in computation efficiency exists if you choose and relax the edge randomly. For example, let’s think about the following graph. I assume the d values in this graph is already initialized. First, let’s relax the straight line edges from left to right. Next, we relax the edge EG. Then, we relax the edge CE. Here, you might find that we can relax the edge EG again. Also, when we relax the edge AC, we can relax the edges CE and EG again. So if we don’t pay attention to the order, we would relax the same edge again and again. In the example above, we can relax the edges efficiently if we relax these from left to right. However, there are too dense graphs to visualize like the example above. So it seems not realistic to find an efficient order in advance. This is the reason why we should care about the relaxing order. Well, how we should choose and relax the edges. In fact, the shortest paths algorithms like Dijkstra’s algorithm or Bellman-Ford algorithm give us a relaxing order. What it means that every shortest paths algorithm basically repeats the edge relaxation and designs the relaxing order depending on the graph’s nature (positive or negative weights, DAG, ..., etc). In other words, we should look for the way how to choose and relax the edges by observing the graph’s nature. In summary, every shortest paths algorithm has this general structure below: 1. Initialize d and Π in the graph2. Choose the edge somehow (it depends on the algorithm) and Relax it. In the section before, I said that we should choose the way for the edge relaxation by observing the graph’s nature. Here, I’ll explain the simple and easy shortest paths algorithm for DAG (Directed acyclic graph) with Python implementation. DAG is the graph has no cyclic. In this section, I’ll explain the algorithm as you know the topological order. If you are not familiar with it, check my article: Understanding the Depth-First Search and the Topological Sort with Python? In the shortest paths algorithm on DAG, we can obtain the shortest paths by choosing and relaxing the out-going edges in the topological order. This is the concrete algorithm as follows: 1. Initialize the d value of the starting vertex as 0 and the other vertices as ∞2. Relax the out-going edges in topological order Let’s see how the algorithm works. I show the graph which I initialized the ds and topological-sorted as follows. I assume the starting vertex is B. Let’s try to solve the shortest paths problem. Each vertex is topological-sorted, so we just relax the out-going edges from left to right. We cannot relax the out-going edge from the most left vertex A, so we don’t update d. Next, we relax the out-going edges from vertex B, which are BC and BD. Once we relax the edges, we update the Π. We set Π[C] as B and Π[D] as B. Then, we relax the out-going edges from the vertex C. We cannot relax the out-going edge to vertex D, so we only update d[E] and d[F]. Also, we update Π[E] as C, Π[F] as C. We update the out-going edge from the vertex D. We only update d[E] and Π[E] as D. We update the out-going edge from the vertex E. We also update Π[F] as E. There is no out-going edge from the vertex F. We finish the edge relaxation. Finally, we obtain the shortest distances as follows: We don’t check if it works here, but we can reconstruct the shortest paths from Π. Subsequently, let’s implement the shortest paths algorithm on DAG in Python for better understanding. The implementation is below: In this implementation, this code solves the shortest paths problem on the graph used in the above explanation. This code evaluates d and Π to solve the problem. I assume we’ve already known the topological order beforehand. First, let’s look at the way how the graph and its weights are expressed. In the code above, the graph is implemented as follows: graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D', 'E', 'F'], 'D': ['E', 'F'], 'E': ['F'], 'F': []}weights = {('A', 'B'): 5, ('A', 'C'): 2, ('B', 'C'): 2, ('B', 'D'): 6, ('C', 'D'): 7, ('C', 'E'): 4, ('C', 'F'): 2, ('D', 'E'): -1, ('D', 'F'): 1, ('E', 'F'): -2} The corresponding figure for the graph is below: For example, when we look at the vertex C, graph[‘C’] returns [‘D’, ‘E’, ‘F’] which are the reachable neighbors from the vertex C. So these vertices construct the out-going edges from the vertex C. Also, you find out that weights[u, v] corresponds the weight of the edge uv. Next, let’s look at each line’s role of dag_shortest_path to obtain the shortest paths. The lines from 2 to 4 is the initialization as follow: Set the d of the starting vertex as 0, the other vertices as ∞. Also, these lines initialize the Π to reconstruct the path. d = {v: INF for v in graph}d[s] = 0pi = {s: None} The lines from 9 to 12 correspond to the edge relaxation. d_temp < d[v] in the code corresponds to the d[u]+w(u,v)<d[v] in the condition of the edge relaxation. When this condition is satisfied, it updates the d[v]. Once it updates the d, it also updates the Π. d_temp = d[u] + weights[u, v]if d_temp < d[v]: d[v] = d_temp pi[v] = u The code repeats this process to the out-going edges from each vertex in the topological order. This repeating process is worked out by the two for-loops. The torder holds the vertices in the topological order. Also, the graph returns the vertices to construct the outgoing edges from the vertex. So, we obtain the edge uv by regarding the vertex from the torder as u and the graph[u] as v. for u in torder: for v in graph[u]: # relax(u, v) That’s all for the code explanation. We don’t check the result, but you can execute the code by the following command in your terminal: You’ll find out that you can get the d and Π correctly. curl -s https://gist.githubusercontent.com/yasufumy/e6477c836baa85735f6019bc0b0c1460/raw/ee4885e5d21f009ee490038525887d8fcf80f8d8/dag_shortest_path.py | python3 Finally, let’s think about the time complexity of this algorithm. In this algorithm, there are two main computation parts. One is for the topological sorting. The other is for edge relaxation. In the code above, we don’t do the topological sort, but actually, we need to do it. So we should take it into account. We can do the topological sort by the depth-first search, so the time complexity is O(|V|+|E|). The number of the loops only affects the time complexity of the edge relaxation because the processes in the loop run in constant time. The number of loops for the torder is |V| and the number of loops for the graph[u] is |E|. So the time complexity of the edge relaxation is O(|V|+|E|). In summary, the entire time complexity of the algorithm is O(|V|+|E|). In this post, I focus on the edge relaxation and explain the shortest paths problem and its algorithm. When you understand the edge relaxation, you can easily understand Dijsktra’s algorithm or Bellman-Ford algorithm. Also, you can know the difference between these algorithms. Thank you for reading my article. MIT OpenCourseWare 6.006 Lecture 15: Single-Source Shortest Paths Problem MIT OpenCourseWare 6.006 Recitation 15: Shortest Paths
[ { "code": null, "e": 966, "s": 172, "text": "The purpose of the shortest paths problem is to find the shortest path from the starting vertex to the goal vertex. We widely use the algorithms to solve the shortest paths problem from competitive programming to Google Maps directions search. By understanding the key notion, “edge relaxation”, it is really easier to understand the concrete algorithms, say Dijsktra’s algorithm or Bellman-Ford algorithm. In other words, it might be difficult to make these algorithms your own without understanding edge relaxation. In this post, I focus on edge relaxation and explain the general structure to solve the shortest paths problem. Also, we’ll go through the easy algorithm and its implementation for better understanding. I use Python for the implementation. This post is structured as follows:" }, { "code": null, "e": 1100, "s": 966, "text": "What is the shortest paths problem?What is edge relaxation?The order of the relaxationThe shortest path on DAG and its implementation" }, { "code": null, "e": 1136, "s": 1100, "text": "What is the shortest paths problem?" }, { "code": null, "e": 1161, "s": 1136, "text": "What is edge relaxation?" }, { "code": null, "e": 1189, "s": 1161, "text": "The order of the relaxation" }, { "code": null, "e": 1237, "s": 1189, "text": "The shortest path on DAG and its implementation" }, { "code": null, "e": 1317, "s": 1237, "text": "Please note that we don’t treat Dijkstra’s algorithm or Bellman-ford algorithm." }, { "code": null, "e": 1834, "s": 1317, "text": "In this post, I explain the single-source shortest paths problems out of the shortest paths problems, in which we need to find all the paths from one starting vertex to all other vertices. I define the shortest paths as the smallest weighted path from the starting vertex to the goal vertex out of all other paths in the weighted graph. Here, you can think “weighted” in the weighted path means the reaching cost to the goal vertex (some vertex). From here onward, when I say a just graph, it means a weighted graph." }, { "code": null, "e": 1949, "s": 1834, "text": "In the graph below, let’s think about the shortest paths from the starting vertex S to the other vertices A and B." }, { "code": null, "e": 2514, "s": 1949, "text": "The shortest path from the vertex S to the vertex A becomes “S→A”. In the graph above, there is the only one path from the vertex S to the vertex A, so we don’t need to care about the weights. On the other hand, we can find the two paths from the vertex S to the vertex B, which are “S→B” and “S→A→B”, and the shortest path becomes “S→A→B”. In “S→B”, the weight of the path is 3, but in “S→A→B”, the weight of the path becomes 2 and it’s shortest: 1+1=2. We can think the weight of the shortest path as the shortest distance from the starting vertex to one vertex." }, { "code": null, "e": 2842, "s": 2514, "text": "Here, I’ll explain the important and commonly used notion, edge relaxation, to solve the shortest paths problem. Generally, you can solve all the shortest paths problem by using edge relaxation. The edge relaxation is the operation to calculate the reaching cost to the vertex lower. More concretely, the operation will become:" }, { "code": null, "e": 2951, "s": 2842, "text": "For the edge from the vertex u to the vertex v, if d[u]+w(u,v)<d[v] is satisfied, update d[v] to d[u]+w(u,v)" }, { "code": null, "e": 3225, "s": 2951, "text": "The vertices u and v stand the neighbors in the graph and d[u] and d[v] stand the reaching cost to the vertices u and v respectively. Also, w(u,v) stands the weight of the edge from the vertex u to the vertex v. To summarize things up to now, we can make this figure below." }, { "code": null, "e": 3444, "s": 3225, "text": "Now we know we can reach the vertex u from the starting vertex S through two vertices and that path costs d[u]. Also, we can reach the vertex v from the starting vertex S through four vertices and that path costs d[v]." }, { "code": null, "e": 3959, "s": 3444, "text": "Here, edge relaxation updates d[v] to d[u]+w(u,v) when d[u]+w(u,v) is less than d[v]. In other words, it updates the current reaching cost to the vertex v (d[v]) to the lower reaching cost (d[u]+w(u,v)). The reason why it updates the cost is that the path through the vertex u can be shorter because the reaching cost of the path through the vertex u will be lower than the cost of the current path. Actually, the algorithms for the shortest paths problem solve the problem by repeatedly using the edge relaxation." }, { "code": null, "e": 4278, "s": 3959, "text": "I’ll show the example that we can solve the shortest paths problem by repeatedly using the edge relaxation. Let’s find the shortest paths for the same graph as before by the edge relaxation. I assume the starting vertex S and apply the edge relaxation to the graph to obtain the shortest paths to the vertices A and B." }, { "code": null, "e": 4682, "s": 4278, "text": "To apply the edge relaxation, we need to know the reaching cost, but there is no way to know it before searching, so we initialize the reaching costs for the vertices A and B as infinity (∞). The infinity cost for the vertex means that we cannot reach that vertex. On the other hands, the reaching cost from the starting vertex to the starting vertex is zero, so we set the d value of the vertex S as 0." }, { "code": null, "e": 4849, "s": 4682, "text": "We choose and relax the edges out-going from the vertex S first, then the edge out-going from the vertex A. First of all, we apply the edge relaxation to the edge SA." }, { "code": null, "e": 5203, "s": 4849, "text": "The edge SA satisfies d[S]+w(S, A)<d[A], we set d[A] as d[S]+w(S, A)=1. Here, Π[A] stands the vertex reaching before the vertex A in the path of the reaching cost d[A]. In this case, Π[A] is S. Π[A]=S means the path of the reaching cost d[A] always uses the sub-path, A←S. The details will be described below, but we can reconstruct the path by using Π." }, { "code": null, "e": 5247, "s": 5203, "text": "We’re relaxing the edge SB in the same way." }, { "code": null, "e": 5438, "s": 5247, "text": "The edge SB satisfies d[S]+w(S, B)<d[B], so we set d[B] as d[S]+w(S, B)=3. For the d[B] path reconstruction, we set Π[B] as S. Subsequently, we relax the edge AB out-going from the vertex A." }, { "code": null, "e": 5778, "s": 5438, "text": "The edge AB satisfies d[A]+w(A, B)<d[B], so we set d[B] as d[A]+w(A, B)=2. Once we update the d value of B, we also update Π[B] as A. From the figure above, you can find that the shortest distances from the vertex S to the vertices A and B equal to the reaching cost d. We cannot update the d value lower, so we finish the edge relaxation." }, { "code": null, "e": 6515, "s": 5778, "text": "Here, let’s confirm that we can reconstruct the shortest path by using Π[A]=S and Π[B]=A. In the graph above, we’re going to reconstruct the shortest path from the vertex S to vertex B as an example. From Π[B]=A, we can know we should visit the vertex A before reaching vertex B in the path to vertex B. From Π[A]=S, we can know we should visit the vertex S first and then reaching vertex A. The vertex S is the starting vertex, so we cannot traverse backward anymore. By reversing the vertices we obtained up to now, we can get the shortest path from the vertex S to vertex B, “S→A→B”. Generally, we can reconstruct the shortest path for the vertex v by back-tracking Π[v], Π[Π[v]], Π[Π[Π[v]]], ... and reversing the obtained vertices." }, { "code": null, "e": 6856, "s": 6515, "text": "In the section before, we don’t care about the order to relax edges, but how should we decide the order? Or do we really care about it? It seems that we can obtain the shortest path by randomly relaxing edges. This is not correct, though. Here, I’ll explain the reason why we should care about the order and how to choose the edge to relax." }, { "code": null, "e": 7083, "s": 6856, "text": "To tell the truth, the really bad case in computation efficiency exists if you choose and relax the edge randomly. For example, let’s think about the following graph. I assume the d values in this graph is already initialized." }, { "code": null, "e": 7146, "s": 7083, "text": "First, let’s relax the straight line edges from left to right." }, { "code": null, "e": 7174, "s": 7146, "text": "Next, we relax the edge EG." }, { "code": null, "e": 7202, "s": 7174, "text": "Then, we relax the edge CE." }, { "code": null, "e": 7260, "s": 7202, "text": "Here, you might find that we can relax the edge EG again." }, { "code": null, "e": 7719, "s": 7260, "text": "Also, when we relax the edge AC, we can relax the edges CE and EG again. So if we don’t pay attention to the order, we would relax the same edge again and again. In the example above, we can relax the edges efficiently if we relax these from left to right. However, there are too dense graphs to visualize like the example above. So it seems not realistic to find an efficient order in advance. This is the reason why we should care about the relaxing order." }, { "code": null, "e": 8269, "s": 7719, "text": "Well, how we should choose and relax the edges. In fact, the shortest paths algorithms like Dijkstra’s algorithm or Bellman-Ford algorithm give us a relaxing order. What it means that every shortest paths algorithm basically repeats the edge relaxation and designs the relaxing order depending on the graph’s nature (positive or negative weights, DAG, ..., etc). In other words, we should look for the way how to choose and relax the edges by observing the graph’s nature. In summary, every shortest paths algorithm has this general structure below:" }, { "code": null, "e": 8374, "s": 8269, "text": "1. Initialize d and Π in the graph2. Choose the edge somehow (it depends on the algorithm) and Relax it." }, { "code": null, "e": 8853, "s": 8374, "text": "In the section before, I said that we should choose the way for the edge relaxation by observing the graph’s nature. Here, I’ll explain the simple and easy shortest paths algorithm for DAG (Directed acyclic graph) with Python implementation. DAG is the graph has no cyclic. In this section, I’ll explain the algorithm as you know the topological order. If you are not familiar with it, check my article: Understanding the Depth-First Search and the Topological Sort with Python?" }, { "code": null, "e": 9040, "s": 8853, "text": "In the shortest paths algorithm on DAG, we can obtain the shortest paths by choosing and relaxing the out-going edges in the topological order. This is the concrete algorithm as follows:" }, { "code": null, "e": 9171, "s": 9040, "text": "1. Initialize the d value of the starting vertex as 0 and the other vertices as ∞2. Relax the out-going edges in topological order" }, { "code": null, "e": 9367, "s": 9171, "text": "Let’s see how the algorithm works. I show the graph which I initialized the ds and topological-sorted as follows. I assume the starting vertex is B. Let’s try to solve the shortest paths problem." }, { "code": null, "e": 9545, "s": 9367, "text": "Each vertex is topological-sorted, so we just relax the out-going edges from left to right. We cannot relax the out-going edge from the most left vertex A, so we don’t update d." }, { "code": null, "e": 9690, "s": 9545, "text": "Next, we relax the out-going edges from vertex B, which are BC and BD. Once we relax the edges, we update the Π. We set Π[C] as B and Π[D] as B." }, { "code": null, "e": 9863, "s": 9690, "text": "Then, we relax the out-going edges from the vertex C. We cannot relax the out-going edge to vertex D, so we only update d[E] and d[F]. Also, we update Π[E] as C, Π[F] as C." }, { "code": null, "e": 9946, "s": 9863, "text": "We update the out-going edge from the vertex D. We only update d[E] and Π[E] as D." }, { "code": null, "e": 10020, "s": 9946, "text": "We update the out-going edge from the vertex E. We also update Π[F] as E." }, { "code": null, "e": 10234, "s": 10020, "text": "There is no out-going edge from the vertex F. We finish the edge relaxation. Finally, we obtain the shortest distances as follows: We don’t check if it works here, but we can reconstruct the shortest paths from Π." }, { "code": null, "e": 10590, "s": 10234, "text": "Subsequently, let’s implement the shortest paths algorithm on DAG in Python for better understanding. The implementation is below: In this implementation, this code solves the shortest paths problem on the graph used in the above explanation. This code evaluates d and Π to solve the problem. I assume we’ve already known the topological order beforehand." }, { "code": null, "e": 10720, "s": 10590, "text": "First, let’s look at the way how the graph and its weights are expressed. In the code above, the graph is implemented as follows:" }, { "code": null, "e": 11065, "s": 10720, "text": "graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D', 'E', 'F'], 'D': ['E', 'F'], 'E': ['F'], 'F': []}weights = {('A', 'B'): 5, ('A', 'C'): 2, ('B', 'C'): 2, ('B', 'D'): 6, ('C', 'D'): 7, ('C', 'E'): 4, ('C', 'F'): 2, ('D', 'E'): -1, ('D', 'F'): 1, ('E', 'F'): -2}" }, { "code": null, "e": 11114, "s": 11065, "text": "The corresponding figure for the graph is below:" }, { "code": null, "e": 11389, "s": 11114, "text": "For example, when we look at the vertex C, graph[‘C’] returns [‘D’, ‘E’, ‘F’] which are the reachable neighbors from the vertex C. So these vertices construct the out-going edges from the vertex C. Also, you find out that weights[u, v] corresponds the weight of the edge uv." }, { "code": null, "e": 11656, "s": 11389, "text": "Next, let’s look at each line’s role of dag_shortest_path to obtain the shortest paths. The lines from 2 to 4 is the initialization as follow: Set the d of the starting vertex as 0, the other vertices as ∞. Also, these lines initialize the Π to reconstruct the path." }, { "code": null, "e": 11706, "s": 11656, "text": "d = {v: INF for v in graph}d[s] = 0pi = {s: None}" }, { "code": null, "e": 11968, "s": 11706, "text": "The lines from 9 to 12 correspond to the edge relaxation. d_temp < d[v] in the code corresponds to the d[u]+w(u,v)<d[v] in the condition of the edge relaxation. When this condition is satisfied, it updates the d[v]. Once it updates the d, it also updates the Π." }, { "code": null, "e": 12041, "s": 11968, "text": "d_temp = d[u] + weights[u, v]if d_temp < d[v]: d[v] = d_temp pi[v] = u" }, { "code": null, "e": 12432, "s": 12041, "text": "The code repeats this process to the out-going edges from each vertex in the topological order. This repeating process is worked out by the two for-loops. The torder holds the vertices in the topological order. Also, the graph returns the vertices to construct the outgoing edges from the vertex. So, we obtain the edge uv by regarding the vertex from the torder as u and the graph[u] as v." }, { "code": null, "e": 12486, "s": 12432, "text": "for u in torder: for v in graph[u]: # relax(u, v)" }, { "code": null, "e": 12678, "s": 12486, "text": "That’s all for the code explanation. We don’t check the result, but you can execute the code by the following command in your terminal: You’ll find out that you can get the d and Π correctly." }, { "code": null, "e": 12839, "s": 12678, "text": "curl -s https://gist.githubusercontent.com/yasufumy/e6477c836baa85735f6019bc0b0c1460/raw/ee4885e5d21f009ee490038525887d8fcf80f8d8/dag_shortest_path.py | python3" }, { "code": null, "e": 13607, "s": 12839, "text": "Finally, let’s think about the time complexity of this algorithm. In this algorithm, there are two main computation parts. One is for the topological sorting. The other is for edge relaxation. In the code above, we don’t do the topological sort, but actually, we need to do it. So we should take it into account. We can do the topological sort by the depth-first search, so the time complexity is O(|V|+|E|). The number of the loops only affects the time complexity of the edge relaxation because the processes in the loop run in constant time. The number of loops for the torder is |V| and the number of loops for the graph[u] is |E|. So the time complexity of the edge relaxation is O(|V|+|E|). In summary, the entire time complexity of the algorithm is O(|V|+|E|)." }, { "code": null, "e": 13919, "s": 13607, "text": "In this post, I focus on the edge relaxation and explain the shortest paths problem and its algorithm. When you understand the edge relaxation, you can easily understand Dijsktra’s algorithm or Bellman-Ford algorithm. Also, you can know the difference between these algorithms. Thank you for reading my article." }, { "code": null, "e": 13993, "s": 13919, "text": "MIT OpenCourseWare 6.006 Lecture 15: Single-Source Shortest Paths Problem" } ]
Effective Modular Design in Software Engineering - GeeksforGeeks
20 Dec, 2019 The role of effective modular design in software engineering:Any software comprises of many systems which contains several sub-systems and those sub-systems further contains their sub-systems. So, designing a complete system in one go comprising of each and every required functionality is a hectic work and the process can have many errors because of its vast size. Thus in order to solve this problem the developing team breakdown the complete software into various modules. A module is defined as the unique and addressable components of the software which can be solved and modified independently without disturbing ( or affecting in very small amount ) other modules of the software. Thus every software design should follow modularity. The process of breaking down a software into multiple independent modules where each module is developed separately is called Modularization. Effective modular design can be achieved if the partitioned modules are separately solvable, modifiable as well as compilable. Here separate compilable modules means that after making changes in a module there is no need of recompiling the whole software system. In order to build a software with effective modular design there is a factor “Functional Independence” which comes into play. The meaning of Functional Independence is that a function is atomic in nature so that it performs only a single task of the software without or with least interaction with other modules. Functional Independence is considered as a sign of growth in modularity i.e., presence of larger functional independence results in a software system of good design and design further affects the quality of the software. Benefits of Independent modules/functions in a software design:Since the functionality of the software have been broken down into atomic levels, thus developers get a clear requirement of each and every functions and hence designing of the software becomes easy and error free. As the modules are independent they have limited or almost no dependency on other modules. So, making changes in a module without affecting the whole system is possible in this approach.Error propagation from one module to another and further in whole system can be neglected and it saves time during testing and debugging. Independence of modules of a software system can be measured using 2 criteria : Cohesion, and Coupling. These are explained as following below. Cohesion:Cohesion is a measure of strength in relationship between various functions within a module. It is of 7 types which are listed below in the order of high to low cohesion: 1. Functional cohesion 2. Sequential cohesion 3. Communicational cohesion 4. Procedural cohesion 5. Temporal cohesion 6. Logical cohesion 7. Co-incidental cohesion Coupling:Coupling is a measure of strength in relationship between various modules within a software. It is of 6 types which are listed below in the order of low to high coupling: 1. Data Coupling 2. Stamp Coupling 3. Control Coupling 4. External Coupling 5. Common Coupling 6. Content Coupling A good software design requires high cohesion and low coupling. Software Engineering Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Software Engineering | Seven Principles of software testing Software Development Life Cycle (SDLC) Architecture of Cloud Computing Software Engineering | Black box testing Use Case Diagram for Library Management System What is DFD(Data Flow Diagram)? System Testing Non-functional Requirements in Software Engineering Elements of the Requirements Model Software Engineering | Control Flow Graph (CFG)
[ { "code": null, "e": 24581, "s": 24553, "text": "\n20 Dec, 2019" }, { "code": null, "e": 24948, "s": 24581, "text": "The role of effective modular design in software engineering:Any software comprises of many systems which contains several sub-systems and those sub-systems further contains their sub-systems. So, designing a complete system in one go comprising of each and every required functionality is a hectic work and the process can have many errors because of its vast size." }, { "code": null, "e": 25323, "s": 24948, "text": "Thus in order to solve this problem the developing team breakdown the complete software into various modules. A module is defined as the unique and addressable components of the software which can be solved and modified independently without disturbing ( or affecting in very small amount ) other modules of the software. Thus every software design should follow modularity." }, { "code": null, "e": 25465, "s": 25323, "text": "The process of breaking down a software into multiple independent modules where each module is developed separately is called Modularization." }, { "code": null, "e": 25728, "s": 25465, "text": "Effective modular design can be achieved if the partitioned modules are separately solvable, modifiable as well as compilable. Here separate compilable modules means that after making changes in a module there is no need of recompiling the whole software system." }, { "code": null, "e": 26262, "s": 25728, "text": "In order to build a software with effective modular design there is a factor “Functional Independence” which comes into play. The meaning of Functional Independence is that a function is atomic in nature so that it performs only a single task of the software without or with least interaction with other modules. Functional Independence is considered as a sign of growth in modularity i.e., presence of larger functional independence results in a software system of good design and design further affects the quality of the software." }, { "code": null, "e": 26540, "s": 26262, "text": "Benefits of Independent modules/functions in a software design:Since the functionality of the software have been broken down into atomic levels, thus developers get a clear requirement of each and every functions and hence designing of the software becomes easy and error free." }, { "code": null, "e": 26864, "s": 26540, "text": "As the modules are independent they have limited or almost no dependency on other modules. So, making changes in a module without affecting the whole system is possible in this approach.Error propagation from one module to another and further in whole system can be neglected and it saves time during testing and debugging." }, { "code": null, "e": 27008, "s": 26864, "text": "Independence of modules of a software system can be measured using 2 criteria : Cohesion, and Coupling. These are explained as following below." }, { "code": null, "e": 27188, "s": 27008, "text": "Cohesion:Cohesion is a measure of strength in relationship between various functions within a module. It is of 7 types which are listed below in the order of high to low cohesion:" }, { "code": null, "e": 27353, "s": 27188, "text": "1. Functional cohesion\n2. Sequential cohesion\n3. Communicational cohesion\n4. Procedural cohesion\n5. Temporal cohesion\n6. Logical cohesion\n7. Co-incidental cohesion " }, { "code": null, "e": 27533, "s": 27353, "text": "Coupling:Coupling is a measure of strength in relationship between various modules within a software. It is of 6 types which are listed below in the order of low to high coupling:" }, { "code": null, "e": 27649, "s": 27533, "text": "1. Data Coupling\n2. Stamp Coupling\n3. Control Coupling\n4. External Coupling\n5. Common Coupling\n6. Content Coupling " }, { "code": null, "e": 27713, "s": 27649, "text": "A good software design requires high cohesion and low coupling." }, { "code": null, "e": 27734, "s": 27713, "text": "Software Engineering" }, { "code": null, "e": 27753, "s": 27734, "text": "Technical Scripter" }, { "code": null, "e": 27851, "s": 27753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27860, "s": 27851, "text": "Comments" }, { "code": null, "e": 27873, "s": 27860, "text": "Old Comments" }, { "code": null, "e": 27933, "s": 27873, "text": "Software Engineering | Seven Principles of software testing" }, { "code": null, "e": 27972, "s": 27933, "text": "Software Development Life Cycle (SDLC)" }, { "code": null, "e": 28004, "s": 27972, "text": "Architecture of Cloud Computing" }, { "code": null, "e": 28045, "s": 28004, "text": "Software Engineering | Black box testing" }, { "code": null, "e": 28092, "s": 28045, "text": "Use Case Diagram for Library Management System" }, { "code": null, "e": 28124, "s": 28092, "text": "What is DFD(Data Flow Diagram)?" }, { "code": null, "e": 28139, "s": 28124, "text": "System Testing" }, { "code": null, "e": 28191, "s": 28139, "text": "Non-functional Requirements in Software Engineering" }, { "code": null, "e": 28226, "s": 28191, "text": "Elements of the Requirements Model" } ]
3D Surface plotting in Python using Matplotlib - GeeksforGeeks
12 Oct, 2021 A Surface Plot is a representation of three-dimensional dataset. It describes a functional relationship between two independent variables X and Z and a designated dependent variable Y, rather than showing the individual data points. It is a companion plot of the contour plot. It is similar to the wireframe plot, but each face of the wireframe is a filled polygon. This helps to create the topology of the surface which is being visualized. The axes3d present in Matplotlib’s mpl_toolkits.mplot3d toolkit provides the necessary functions used to create 3D surface plots.Surface plots are created by using ax.plot_surface() function.Syntax: ax.plot_surface(X, Y, Z) where X and Y are 2D array of points of x and y while Z is 2D array of heights.Some more attributes of ax.plot_surface() function are listed below: Example: Let’s create a 3D surface by using the above function Python3 # Import librariesfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # Creating datasetx = np.outer(np.linspace(-3, 3, 32), np.ones(32))y = x.copy().T # transposez = (np.sin(x **2) + np.cos(y **2) ) # Creating figurefig = plt.figure(figsize =(14, 9))ax = plt.axes(projection ='3d') # Creating plotax.plot_surface(x, y, z) # show plotplt.show() Output: Gradient surface plot is a combination of 3D surface plot with a 2D contour plot. In this plot the 3D surface is colored like 2D contour plot. The parts which are high on the surface contains different color than the parts which are low at the surface.Syntax: surf = ax.plot_surface(X, Y, Z, cmap=, linewidth=0, antialiased=False) The attribute cmap= stes the color of the surface. A color bar can also be added by calling fig.colorbar. The code below create a gradient surface plot:Example: Python3 # Import librariesfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # Creating datasetx = np.outer(np.linspace(-3, 3, 32), np.ones(32))y = x.copy().T # transposez = (np.sin(x **2) + np.cos(y **2) ) # Creating figurefig = plt.figure(figsize =(14, 9))ax = plt.axes(projection ='3d') # Creating color mapmy_cmap = plt.get_cmap('hot') # Creating plotsurf = ax.plot_surface(x, y, z, cmap = my_cmap, edgecolor ='none') fig.colorbar(surf, ax = ax, shrink = 0.5, aspect = 5) ax.set_title('Surface plot') # show plotplt.show() Output: 3D surface plots plotted with Matplotlib can be projected on 2D surfaces. The code below creates a 3D plots and visualizes its projection on 2D contour plot:Example: Python3 # Import librariesfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # Creating datasetx = np.outer(np.linspace(-3, 3, 32), np.ones(32))y = x.copy().T # transposez = (np.sin(x **2) + np.cos(y **2) ) # Creating figurefig = plt.figure(figsize =(14, 9))ax = plt.axes(projection ='3d') # Creating color mapmy_cmap = plt.get_cmap('hot') # Creating plotsurf = ax.plot_surface(x, y, z, rstride = 8, cstride = 8, alpha = 0.8, cmap = my_cmap)cset = ax.contourf(x, y, z, zdir ='z', offset = np.min(z), cmap = my_cmap)cset = ax.contourf(x, y, z, zdir ='x', offset =-5, cmap = my_cmap)cset = ax.contourf(x, y, z, zdir ='y', offset = 5, cmap = my_cmap)fig.colorbar(surf, ax = ax, shrink = 0.5, aspect = 5) # Adding labelsax.set_xlabel('X-axis')ax.set_xlim(-5, 5)ax.set_ylabel('Y-axis')ax.set_ylim(-5, 5)ax.set_zlabel('Z-axis')ax.set_zlim(np.min(z), np.max(z))ax.set_title('3D surface having 2D contour plot projections') # show plotplt.show() Output: surindertarika1234 surinderdawra388 Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 29937, "s": 29909, "text": "\n12 Oct, 2021" }, { "code": null, "e": 30380, "s": 29937, "text": "A Surface Plot is a representation of three-dimensional dataset. It describes a functional relationship between two independent variables X and Z and a designated dependent variable Y, rather than showing the individual data points. It is a companion plot of the contour plot. It is similar to the wireframe plot, but each face of the wireframe is a filled polygon. This helps to create the topology of the surface which is being visualized. " }, { "code": null, "e": 30580, "s": 30380, "text": "The axes3d present in Matplotlib’s mpl_toolkits.mplot3d toolkit provides the necessary functions used to create 3D surface plots.Surface plots are created by using ax.plot_surface() function.Syntax: " }, { "code": null, "e": 30605, "s": 30580, "text": "ax.plot_surface(X, Y, Z)" }, { "code": null, "e": 30754, "s": 30605, "text": "where X and Y are 2D array of points of x and y while Z is 2D array of heights.Some more attributes of ax.plot_surface() function are listed below: " }, { "code": null, "e": 30818, "s": 30754, "text": "Example: Let’s create a 3D surface by using the above function " }, { "code": null, "e": 30826, "s": 30818, "text": "Python3" }, { "code": "# Import librariesfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # Creating datasetx = np.outer(np.linspace(-3, 3, 32), np.ones(32))y = x.copy().T # transposez = (np.sin(x **2) + np.cos(y **2) ) # Creating figurefig = plt.figure(figsize =(14, 9))ax = plt.axes(projection ='3d') # Creating plotax.plot_surface(x, y, z) # show plotplt.show()", "e": 31202, "s": 30826, "text": null }, { "code": null, "e": 31211, "s": 31202, "text": "Output: " }, { "code": null, "e": 31473, "s": 31213, "text": "Gradient surface plot is a combination of 3D surface plot with a 2D contour plot. In this plot the 3D surface is colored like 2D contour plot. The parts which are high on the surface contains different color than the parts which are low at the surface.Syntax:" }, { "code": null, "e": 31544, "s": 31473, "text": "surf = ax.plot_surface(X, Y, Z, cmap=, linewidth=0, antialiased=False)" }, { "code": null, "e": 31705, "s": 31544, "text": "The attribute cmap= stes the color of the surface. A color bar can also be added by calling fig.colorbar. The code below create a gradient surface plot:Example:" }, { "code": null, "e": 31713, "s": 31705, "text": "Python3" }, { "code": "# Import librariesfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # Creating datasetx = np.outer(np.linspace(-3, 3, 32), np.ones(32))y = x.copy().T # transposez = (np.sin(x **2) + np.cos(y **2) ) # Creating figurefig = plt.figure(figsize =(14, 9))ax = plt.axes(projection ='3d') # Creating color mapmy_cmap = plt.get_cmap('hot') # Creating plotsurf = ax.plot_surface(x, y, z, cmap = my_cmap, edgecolor ='none') fig.colorbar(surf, ax = ax, shrink = 0.5, aspect = 5) ax.set_title('Surface plot') # show plotplt.show()", "e": 32319, "s": 31713, "text": null }, { "code": null, "e": 32328, "s": 32319, "text": "Output: " }, { "code": null, "e": 32497, "s": 32330, "text": "3D surface plots plotted with Matplotlib can be projected on 2D surfaces. The code below creates a 3D plots and visualizes its projection on 2D contour plot:Example: " }, { "code": null, "e": 32505, "s": 32497, "text": "Python3" }, { "code": "# Import librariesfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # Creating datasetx = np.outer(np.linspace(-3, 3, 32), np.ones(32))y = x.copy().T # transposez = (np.sin(x **2) + np.cos(y **2) ) # Creating figurefig = plt.figure(figsize =(14, 9))ax = plt.axes(projection ='3d') # Creating color mapmy_cmap = plt.get_cmap('hot') # Creating plotsurf = ax.plot_surface(x, y, z, rstride = 8, cstride = 8, alpha = 0.8, cmap = my_cmap)cset = ax.contourf(x, y, z, zdir ='z', offset = np.min(z), cmap = my_cmap)cset = ax.contourf(x, y, z, zdir ='x', offset =-5, cmap = my_cmap)cset = ax.contourf(x, y, z, zdir ='y', offset = 5, cmap = my_cmap)fig.colorbar(surf, ax = ax, shrink = 0.5, aspect = 5) # Adding labelsax.set_xlabel('X-axis')ax.set_xlim(-5, 5)ax.set_ylabel('Y-axis')ax.set_ylim(-5, 5)ax.set_zlabel('Z-axis')ax.set_zlim(np.min(z), np.max(z))ax.set_title('3D surface having 2D contour plot projections') # show plotplt.show()", "e": 33740, "s": 32505, "text": null }, { "code": null, "e": 33749, "s": 33740, "text": "Output: " }, { "code": null, "e": 33768, "s": 33749, "text": "surindertarika1234" }, { "code": null, "e": 33785, "s": 33768, "text": "surinderdawra388" }, { "code": null, "e": 33803, "s": 33785, "text": "Python-matplotlib" }, { "code": null, "e": 33810, "s": 33803, "text": "Python" }, { "code": null, "e": 33908, "s": 33810, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33917, "s": 33908, "text": "Comments" }, { "code": null, "e": 33930, "s": 33917, "text": "Old Comments" }, { "code": null, "e": 33958, "s": 33930, "text": "Read JSON file using Python" }, { "code": null, "e": 34008, "s": 33958, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 34030, "s": 34008, "text": "Python map() function" }, { "code": null, "e": 34074, "s": 34030, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 34092, "s": 34074, "text": "Python Dictionary" }, { "code": null, "e": 34115, "s": 34092, "text": "Taking input in Python" }, { "code": null, "e": 34150, "s": 34115, "text": "Read a file line by line in Python" }, { "code": null, "e": 34172, "s": 34150, "text": "Enumerate() in Python" }, { "code": null, "e": 34204, "s": 34172, "text": "How to Install PIP on Windows ?" } ]
X-Ray Medical Image Analysis : Deep Learning with TensorFlow | Towards Data Science
In the past few years, we have seen a rapid increase in using Deep Learning for medical diagnosis in various forms, specially in the analysis of medical images. Here we will set up a pipeline to classify chest x-ray images of patients with and without pneumonia. The complete dataset is available in Kaggle under Creative Commons License. Before we set up the pipeline, let’s see what you can expect to learn from this post — Binary Classification using Deep Neural Network (DNN). Using TensorFlow Dataset to Create a Faster Data Analysis Pipeline. Better techniques (ex: standardization) for data pre-processing. Augmentation, Rescaling etc as lambda layers within a TensorFlow Model. Class Imbalance and Building Custom Weighted Cross-Entropy Loss. Without any delay let’s begin! [All the codes used here are available in Kaggle Notebook]. Since we will directly access the data from the Kaggle input directory, let’s just see the distribution of labels ‘Normal’ and ‘Pneumonia’ in the Train, Validation and Test Folders. Below is the code-block I used for checking the number of files in each folder — First, we see that training images are class imbalanced with way more images labelled ‘Pneumonia’ than ‘Normal’. Also, the validation folder contains very few examples (8 Normal and 8 Pneumonia images to be exact). tot_normal_train = len(train_im_n) + len(valid_im_n) tot_pneumonia_train = len(train_im_p) + len(valid_im_p)print ('total normal xray images: ', tot_normal_train)print ('total pneumonia xray images: ', tot_pneumonia_train)>>> total normal xray images: 1349total pneumonia xray images: 3883 We can also visualize some of the examples Normal and Pneumonia images as below — Similarly, we can also view ‘Pneumonia’ images — After reading some online resources like this one, I noticed that the usual way to find Pneumonia is to search for opacity in chest x-rays. From the pics above, the images, in general, look opaque compared to normal x-rays. But it is also important to remember that, chest x-rays may not tell the whole story all the time and sometimes the visual result can be misleading. We will adjust our image data such that the new mean of the data will be zero, and the standard deviation of the data will be 1. Later on, we will use the TensorFlow dataset and we will define a function where each pixel value in the image will be replaced with a new value which is calculated by subtracting the mean and dividing by the standard deviation ( x−μ)/σ. Let’s see how standardization helps us to distribute the pixel values in some random examples — To include this type of standardization, we create a function that will be used as a lambda layer in model building. So the GPU power will also be utilized for this process — #### define a function that will be added as lambda layer laterdef standardize_layer(tensor): tensor_mean = tf.math.reduce_mean(tensor) tensor_std = tf.math.reduce_std(tensor) new_tensor = (tensor-tensor_mean)/tensor_std return new_tensor In a post before, I described in detail how building an input pipeline including augmentation using TensorFlow Dataset API can accelerate DNN training. I will follow similar steps. Since the image data are available in train, test, validation folders we can get started with image_dataset_from_directory function — As we checked before there are only 16 files in the validation directory, using only 16 images for validation isn’t a good idea. So we need to add the training and validation datasets and then split them with some reasonable percentages. First, let’s check the number of elements in ‘train’ and ‘valid’ datasets. num_elements = tf.data.experimental.cardinality(train_dir).numpy()print (num_elements)num_elements_val = tf.data.experimental.cardinality(val_dir).numpy()print (num_elements_val)>>> 821 We see that there are 82 training batches and 1 validation batch. To increase the validation batch, first, let’s concatenate ‘train’ and ‘validation’ datasets. Then we assign 20% of the total dataset to validation and use dataset.take and dataset.skip to create the new datasets using the code block below — new_train_ds = train_dir.concatenate(val_dir)print (new_train_ds, train_dir)train_size = int(0.8 * 83) # 83 is the elements in dataset (train + valid)val_size = int(0.2 * 83) train_ds = new_train_ds.take(train_size)val_ds = new_train_ds.skip(train_size).take(val_size)#### check the dataset size back again num_elements_train = tf.data.experimental.cardinality(train_ds).numpy()print (num_elements_train)num_elements_val_ds = tf.data.experimental.cardinality(val_ds).numpy()print (num_elements_val_ds)>>> <ConcatenateDataset shapes: ((None, 300, 300, 1), (None, 1)), types: (tf.float32, tf.float32)> <BatchDataset shapes: ((None, 300, 300, 1), (None, 1)), types: (tf.float32, tf.float32)>6616 I have already described the ‘Prefetching’ technique and how much it is faster than ImageDataGenerator. Let’s add this — autotune = tf.data.AUTOTUNE ### most important function for speed up trainingtrain_data_batches = train_ds.cache().prefetch(buffer_size=autotune)valid_data_batches = val_ds.cache().prefetch(buffer_size=autotune)test_data_batches = test_dir.cache().prefetch(buffer_size=autotune) I will also add a rescaling layer and some augmentations also as layers and, this all will be included in the model as lambda layers. Let’s define them as below — from tensorflow.keras import layersrescale_layer = tf.keras.Sequential([layers.experimental.preprocessing.Rescaling(1./255)])data_augmentation = tf.keras.Sequential([ layers.experimental.preprocessing.RandomFlip(), layers.experimental.preprocessing.RandomRotation(10), layers.experimental.preprocessing.RandomZoom(0.1) ]) The idea behind using a weighted BCE loss is that since we have many more x-ray images with ‘Pneumonia’ than the ‘Normal’, the model weights them heavy for misclassification. So we shift this bias and try to force the model to weigh normal and pneumonia images as same. We calculate frequency terms based on the number of images for each class divided by the total number of images. These weights are then used to construct the custom weighted BCE loss function. The code block below is an example of such that was used for the given problem — After defining the appropriate custom loss function, we are left with building a model including the rescaling and augmentations as lambda layers. For the given work I used InceptionResNetV2 pre-trained model and you can check the Keras module here. In Kaggle competitions we are not allowed to use the internet, so I needed to download the pre-trained weights, so that explains the weights argument inside the InceptionResNetV2 function. Rescaling, standardization & augmentation are all added as lambda layers before feeding the image batches to the model. Let’s see the code block below — After compiling including some ‘Callbacks’ we are ready to train the model. To evaluate the performance of the model on the test data we can plot the confusion matrix and ROC curve. y_pred = model.predict(test_data_batches)true_categories = tf.concat([y for x, y in test_data_batches], axis=0) Let’s set a threshold of 0.75 for assigning label ‘1’ and anything below to label ‘0’. y_pred_th = (y_pred > 0.75).astype(np.float32)from sklearn.metrics import confusion_matrixcm = confusion_matrix(y_pred_th, true_categories)class_names = train_dir.class_namesplt.figure(figsize=(8,8))plt.title('CM for threshold 0.75')sns_hmp = sns.heatmap(cm, annot=True, xticklabels = [class_names[i] for i in range(len(class_names))], yticklabels = [class_names[i] for i in range(len(class_names))], fmt="d")fig = sns_hmp.get_figure() The code blocks above resulted in the confusion matrix below — Similarly, we can also plot the ROC curve and the results are shown — All the codes used above are available on my GitHub and you can also check the Kaggle Notebook. The dataset used is available in Kaggle under the License Creative Commons so we are free to use and adapt. Finally, to conclude, we went through a data analysis pipeline including class imbalance dataset and learnt to use TensorFlow Dataset effectively. Stay strong and Cheers!
[ { "code": null, "e": 597, "s": 171, "text": "In the past few years, we have seen a rapid increase in using Deep Learning for medical diagnosis in various forms, specially in the analysis of medical images. Here we will set up a pipeline to classify chest x-ray images of patients with and without pneumonia. The complete dataset is available in Kaggle under Creative Commons License. Before we set up the pipeline, let’s see what you can expect to learn from this post —" }, { "code": null, "e": 652, "s": 597, "text": "Binary Classification using Deep Neural Network (DNN)." }, { "code": null, "e": 720, "s": 652, "text": "Using TensorFlow Dataset to Create a Faster Data Analysis Pipeline." }, { "code": null, "e": 785, "s": 720, "text": "Better techniques (ex: standardization) for data pre-processing." }, { "code": null, "e": 857, "s": 785, "text": "Augmentation, Rescaling etc as lambda layers within a TensorFlow Model." }, { "code": null, "e": 922, "s": 857, "text": "Class Imbalance and Building Custom Weighted Cross-Entropy Loss." }, { "code": null, "e": 1013, "s": 922, "text": "Without any delay let’s begin! [All the codes used here are available in Kaggle Notebook]." }, { "code": null, "e": 1276, "s": 1013, "text": "Since we will directly access the data from the Kaggle input directory, let’s just see the distribution of labels ‘Normal’ and ‘Pneumonia’ in the Train, Validation and Test Folders. Below is the code-block I used for checking the number of files in each folder —" }, { "code": null, "e": 1491, "s": 1276, "text": "First, we see that training images are class imbalanced with way more images labelled ‘Pneumonia’ than ‘Normal’. Also, the validation folder contains very few examples (8 Normal and 8 Pneumonia images to be exact)." }, { "code": null, "e": 1783, "s": 1491, "text": "tot_normal_train = len(train_im_n) + len(valid_im_n) tot_pneumonia_train = len(train_im_p) + len(valid_im_p)print ('total normal xray images: ', tot_normal_train)print ('total pneumonia xray images: ', tot_pneumonia_train)>>> total normal xray images: 1349total pneumonia xray images: 3883" }, { "code": null, "e": 1865, "s": 1783, "text": "We can also visualize some of the examples Normal and Pneumonia images as below —" }, { "code": null, "e": 1914, "s": 1865, "text": "Similarly, we can also view ‘Pneumonia’ images —" }, { "code": null, "e": 2287, "s": 1914, "text": "After reading some online resources like this one, I noticed that the usual way to find Pneumonia is to search for opacity in chest x-rays. From the pics above, the images, in general, look opaque compared to normal x-rays. But it is also important to remember that, chest x-rays may not tell the whole story all the time and sometimes the visual result can be misleading." }, { "code": null, "e": 2750, "s": 2287, "text": "We will adjust our image data such that the new mean of the data will be zero, and the standard deviation of the data will be 1. Later on, we will use the TensorFlow dataset and we will define a function where each pixel value in the image will be replaced with a new value which is calculated by subtracting the mean and dividing by the standard deviation ( x−μ)/σ. Let’s see how standardization helps us to distribute the pixel values in some random examples —" }, { "code": null, "e": 2925, "s": 2750, "text": "To include this type of standardization, we create a function that will be used as a lambda layer in model building. So the GPU power will also be utilized for this process —" }, { "code": null, "e": 3176, "s": 2925, "text": "#### define a function that will be added as lambda layer laterdef standardize_layer(tensor): tensor_mean = tf.math.reduce_mean(tensor) tensor_std = tf.math.reduce_std(tensor) new_tensor = (tensor-tensor_mean)/tensor_std return new_tensor" }, { "code": null, "e": 3491, "s": 3176, "text": "In a post before, I described in detail how building an input pipeline including augmentation using TensorFlow Dataset API can accelerate DNN training. I will follow similar steps. Since the image data are available in train, test, validation folders we can get started with image_dataset_from_directory function —" }, { "code": null, "e": 3804, "s": 3491, "text": "As we checked before there are only 16 files in the validation directory, using only 16 images for validation isn’t a good idea. So we need to add the training and validation datasets and then split them with some reasonable percentages. First, let’s check the number of elements in ‘train’ and ‘valid’ datasets." }, { "code": null, "e": 3990, "s": 3804, "text": "num_elements = tf.data.experimental.cardinality(train_dir).numpy()print (num_elements)num_elements_val = tf.data.experimental.cardinality(val_dir).numpy()print (num_elements_val)>>> 821" }, { "code": null, "e": 4298, "s": 3990, "text": "We see that there are 82 training batches and 1 validation batch. To increase the validation batch, first, let’s concatenate ‘train’ and ‘validation’ datasets. Then we assign 20% of the total dataset to validation and use dataset.take and dataset.skip to create the new datasets using the code block below —" }, { "code": null, "e": 4994, "s": 4298, "text": "new_train_ds = train_dir.concatenate(val_dir)print (new_train_ds, train_dir)train_size = int(0.8 * 83) # 83 is the elements in dataset (train + valid)val_size = int(0.2 * 83) train_ds = new_train_ds.take(train_size)val_ds = new_train_ds.skip(train_size).take(val_size)#### check the dataset size back again num_elements_train = tf.data.experimental.cardinality(train_ds).numpy()print (num_elements_train)num_elements_val_ds = tf.data.experimental.cardinality(val_ds).numpy()print (num_elements_val_ds)>>> <ConcatenateDataset shapes: ((None, 300, 300, 1), (None, 1)), types: (tf.float32, tf.float32)> <BatchDataset shapes: ((None, 300, 300, 1), (None, 1)), types: (tf.float32, tf.float32)>6616" }, { "code": null, "e": 5115, "s": 4994, "text": "I have already described the ‘Prefetching’ technique and how much it is faster than ImageDataGenerator. Let’s add this —" }, { "code": null, "e": 5394, "s": 5115, "text": "autotune = tf.data.AUTOTUNE ### most important function for speed up trainingtrain_data_batches = train_ds.cache().prefetch(buffer_size=autotune)valid_data_batches = val_ds.cache().prefetch(buffer_size=autotune)test_data_batches = test_dir.cache().prefetch(buffer_size=autotune)" }, { "code": null, "e": 5557, "s": 5394, "text": "I will also add a rescaling layer and some augmentations also as layers and, this all will be included in the model as lambda layers. Let’s define them as below —" }, { "code": null, "e": 5883, "s": 5557, "text": "from tensorflow.keras import layersrescale_layer = tf.keras.Sequential([layers.experimental.preprocessing.Rescaling(1./255)])data_augmentation = tf.keras.Sequential([ layers.experimental.preprocessing.RandomFlip(), layers.experimental.preprocessing.RandomRotation(10), layers.experimental.preprocessing.RandomZoom(0.1) ])" }, { "code": null, "e": 6427, "s": 5883, "text": "The idea behind using a weighted BCE loss is that since we have many more x-ray images with ‘Pneumonia’ than the ‘Normal’, the model weights them heavy for misclassification. So we shift this bias and try to force the model to weigh normal and pneumonia images as same. We calculate frequency terms based on the number of images for each class divided by the total number of images. These weights are then used to construct the custom weighted BCE loss function. The code block below is an example of such that was used for the given problem —" }, { "code": null, "e": 7019, "s": 6427, "text": "After defining the appropriate custom loss function, we are left with building a model including the rescaling and augmentations as lambda layers. For the given work I used InceptionResNetV2 pre-trained model and you can check the Keras module here. In Kaggle competitions we are not allowed to use the internet, so I needed to download the pre-trained weights, so that explains the weights argument inside the InceptionResNetV2 function. Rescaling, standardization & augmentation are all added as lambda layers before feeding the image batches to the model. Let’s see the code block below —" }, { "code": null, "e": 7201, "s": 7019, "text": "After compiling including some ‘Callbacks’ we are ready to train the model. To evaluate the performance of the model on the test data we can plot the confusion matrix and ROC curve." }, { "code": null, "e": 7313, "s": 7201, "text": "y_pred = model.predict(test_data_batches)true_categories = tf.concat([y for x, y in test_data_batches], axis=0)" }, { "code": null, "e": 7400, "s": 7313, "text": "Let’s set a threshold of 0.75 for assigning label ‘1’ and anything below to label ‘0’." }, { "code": null, "e": 7858, "s": 7400, "text": "y_pred_th = (y_pred > 0.75).astype(np.float32)from sklearn.metrics import confusion_matrixcm = confusion_matrix(y_pred_th, true_categories)class_names = train_dir.class_namesplt.figure(figsize=(8,8))plt.title('CM for threshold 0.75')sns_hmp = sns.heatmap(cm, annot=True, xticklabels = [class_names[i] for i in range(len(class_names))], yticklabels = [class_names[i] for i in range(len(class_names))], fmt=\"d\")fig = sns_hmp.get_figure()" }, { "code": null, "e": 7921, "s": 7858, "text": "The code blocks above resulted in the confusion matrix below —" }, { "code": null, "e": 7991, "s": 7921, "text": "Similarly, we can also plot the ROC curve and the results are shown —" }, { "code": null, "e": 8342, "s": 7991, "text": "All the codes used above are available on my GitHub and you can also check the Kaggle Notebook. The dataset used is available in Kaggle under the License Creative Commons so we are free to use and adapt. Finally, to conclude, we went through a data analysis pipeline including class imbalance dataset and learnt to use TensorFlow Dataset effectively." } ]
Files deleteIfExists() method in Java with Examples - GeeksforGeeks
30 Jul, 2019 The deleteIfExists() method of java.nio.file.Files help us to delete a file if the file exists at the path. we pass the path of the file as a parameter to this method. This method will return true if the file was deleted by this method; false if the file could not be deleted because it did not exist. If the file is a symbolic link then the symbolic link itself, not the final target of the link, is deleted. If the file is a directory then this method will delete that file only when the directory is empty. In some implementations, a directory has entries for special files or links that are created when the directory is created. In such implementations, a directory is considered empty when only the special entries exist. In such cases, Directories can be delete using this method. On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs. Syntax: public static boolean deleteIfExists(Path path) throws IOException Parameters: This method accepts a parameter path which is the path to the file to deleted. Return value: This method returns true if the file was deleted by this method; false if the file could not be deleted because it did not exist. Exception: This method will throw following exceptions: DirectoryNotEmptyException – if the file is a directory and could not otherwise be deleted because the directory is not emptyIOException – if an I/O error occursSecurityException – In the case of the default provider, and a security manager is installed, the SecurityManager.checkdelete(String) method is invoked to check to delete access to the file DirectoryNotEmptyException – if the file is a directory and could not otherwise be deleted because the directory is not empty IOException – if an I/O error occurs SecurityException – In the case of the default provider, and a security manager is installed, the SecurityManager.checkdelete(String) method is invoked to check to delete access to the file Below programs illustrate deleteIfExists(Path) method:Program 1: // Java program to demonstrate// java.nio.file.Files.deleteIfExists() method import java.io.IOException;import java.nio.file.*; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get("D:\\Work\\Test\\file1.txt"); // deleteIfExists File try { Files.deleteIfExists(path); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }} Before deleting the file: The file is present in the path “D:\\Work\\Test\\file1.txt” Program 2: // Java program to demonstrate// java.nio.file.Files.deleteIfExists() method import java.io.IOException;import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path pathOfFile = Paths.get("D:\\Work\\Test\\" + "text1.txt"); // delete both File if file exists try { boolean result = Files.deleteIfExists(pathOfFile); if (result) System.out.println("File is deleted"); else System.out.println("File does not exists"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }} References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Files.html#deleteIfExists(java.nio.file.Path) Java-Files Java-Functions java.nio.file package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23948, "s": 23920, "text": "\n30 Jul, 2019" }, { "code": null, "e": 24250, "s": 23948, "text": "The deleteIfExists() method of java.nio.file.Files help us to delete a file if the file exists at the path. we pass the path of the file as a parameter to this method. This method will return true if the file was deleted by this method; false if the file could not be deleted because it did not exist." }, { "code": null, "e": 24877, "s": 24250, "text": "If the file is a symbolic link then the symbolic link itself, not the final target of the link, is deleted. If the file is a directory then this method will delete that file only when the directory is empty. In some implementations, a directory has entries for special files or links that are created when the directory is created. In such implementations, a directory is considered empty when only the special entries exist. In such cases, Directories can be delete using this method. On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs." }, { "code": null, "e": 24885, "s": 24877, "text": "Syntax:" }, { "code": null, "e": 24972, "s": 24885, "text": "public static boolean deleteIfExists(Path path)\n throws IOException\n" }, { "code": null, "e": 25063, "s": 24972, "text": "Parameters: This method accepts a parameter path which is the path to the file to deleted." }, { "code": null, "e": 25207, "s": 25063, "text": "Return value: This method returns true if the file was deleted by this method; false if the file could not be deleted because it did not exist." }, { "code": null, "e": 25263, "s": 25207, "text": "Exception: This method will throw following exceptions:" }, { "code": null, "e": 25614, "s": 25263, "text": "DirectoryNotEmptyException – if the file is a directory and could not otherwise be deleted because the directory is not emptyIOException – if an I/O error occursSecurityException – In the case of the default provider, and a security manager is installed, the SecurityManager.checkdelete(String) method is invoked to check to delete access to the file" }, { "code": null, "e": 25740, "s": 25614, "text": "DirectoryNotEmptyException – if the file is a directory and could not otherwise be deleted because the directory is not empty" }, { "code": null, "e": 25777, "s": 25740, "text": "IOException – if an I/O error occurs" }, { "code": null, "e": 25967, "s": 25777, "text": "SecurityException – In the case of the default provider, and a security manager is installed, the SecurityManager.checkdelete(String) method is invoked to check to delete access to the file" }, { "code": null, "e": 26032, "s": 25967, "text": "Below programs illustrate deleteIfExists(Path) method:Program 1:" }, { "code": "// Java program to demonstrate// java.nio.file.Files.deleteIfExists() method import java.io.IOException;import java.nio.file.*; public class GFG { public static void main(String[] args) { // create object of Path Path path = Paths.get(\"D:\\\\Work\\\\Test\\\\file1.txt\"); // deleteIfExists File try { Files.deleteIfExists(path); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}", "e": 26553, "s": 26032, "text": null }, { "code": null, "e": 26639, "s": 26553, "text": "Before deleting the file: The file is present in the path “D:\\\\Work\\\\Test\\\\file1.txt”" }, { "code": null, "e": 26650, "s": 26639, "text": "Program 2:" }, { "code": "// Java program to demonstrate// java.nio.file.Files.deleteIfExists() method import java.io.IOException;import java.nio.file.*; public class GFG { public static void main(String[] args) { // create an object of Path Path pathOfFile = Paths.get(\"D:\\\\Work\\\\Test\\\\\" + \"text1.txt\"); // delete both File if file exists try { boolean result = Files.deleteIfExists(pathOfFile); if (result) System.out.println(\"File is deleted\"); else System.out.println(\"File does not exists\"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}", "e": 27412, "s": 26650, "text": null }, { "code": null, "e": 27527, "s": 27412, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Files.html#deleteIfExists(java.nio.file.Path)" }, { "code": null, "e": 27538, "s": 27527, "text": "Java-Files" }, { "code": null, "e": 27553, "s": 27538, "text": "Java-Functions" }, { "code": null, "e": 27575, "s": 27553, "text": "java.nio.file package" }, { "code": null, "e": 27580, "s": 27575, "text": "Java" }, { "code": null, "e": 27585, "s": 27580, "text": "Java" }, { "code": null, "e": 27683, "s": 27585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27698, "s": 27683, "text": "Stream In Java" }, { "code": null, "e": 27744, "s": 27698, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27765, "s": 27744, "text": "Constructors in Java" }, { "code": null, "e": 27784, "s": 27765, "text": "Exceptions in Java" }, { "code": null, "e": 27801, "s": 27784, "text": "Generics in Java" }, { "code": null, "e": 27831, "s": 27801, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27874, "s": 27831, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27903, "s": 27874, "text": "HashMap get() Method in Java" }, { "code": null, "e": 27919, "s": 27903, "text": "Strings in Java" } ]
How to find the second largest element in a user-input JavaScript array?
Let’s say following is our array − var numbers=[10,50,80,60,89]; To find the second largest element, the code is as follows − var numbers=[10,50,80,60,89]; var firstLargerNumber = Number.MIN_SAFE_INTEGER; var secondlargerNumber = firstLargerNumber; for(var tempNumber of numbers){ if(tempNumber > firstLargerNumber){ secondlargerNumber = firstLargerNumber; firstLargerNumber = tempNumber; } else if(tempNumber > secondlargerNumber){ secondlargerNumber = tempNumber; } } console.log("The second largest number="+secondlargerNumber); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo138.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo138.js The second largest number=80
[ { "code": null, "e": 1097, "s": 1062, "text": "Let’s say following is our array −" }, { "code": null, "e": 1127, "s": 1097, "text": "var numbers=[10,50,80,60,89];" }, { "code": null, "e": 1188, "s": 1127, "text": "To find the second largest element, the code is as follows −" }, { "code": null, "e": 1624, "s": 1188, "text": "var numbers=[10,50,80,60,89];\nvar firstLargerNumber = Number.MIN_SAFE_INTEGER;\nvar secondlargerNumber = firstLargerNumber;\nfor(var tempNumber of numbers){\n if(tempNumber > firstLargerNumber){\n secondlargerNumber = firstLargerNumber;\n firstLargerNumber = tempNumber;\n }\n else if(tempNumber > secondlargerNumber){\n secondlargerNumber = tempNumber;\n }\n}\nconsole.log(\"The second largest number=\"+secondlargerNumber);" }, { "code": null, "e": 1690, "s": 1624, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1708, "s": 1690, "text": "node fileName.js." }, { "code": null, "e": 1742, "s": 1708, "text": "Here, my file name is demo138.js." }, { "code": null, "e": 1783, "s": 1742, "text": "This will produce the following output −" }, { "code": null, "e": 1862, "s": 1783, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo138.js\nThe second largest number=80" } ]
Using csv module to read the data in Pandas - GeeksforGeeks
05 Aug, 2021 The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. There were various formats of CSV until its standardization. The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. For that purpose, we will use Python’s csv library to read and write tabular data in CSV format.For link to the CSV file used in the code click here.Code #1: We will use csv.DictReader() function to import the data file into the Python’s environment. Python3 # importing the csv moduleimport csv # Now let's read the file named 'auto-mpg.csv'# After reading as a dictionary convert# it to Python's listwith open('auto-mpg.csv') as csvfile: mpg_data = list(csv.DictReader(csvfile)) # Let's visualize the data# We are printing only first three elementsprint(mpg_data[:3]) Output : As we can see the data is stored as a list of ordered dictionary. Let’s perform some operations on the data for better understanding.Code #2: Python3 # Let's find all the keys in the dictionaryprint(mpg_data[0].keys) # Now we would like to find out the number of# unique values of cylinders in the car in our dataset# We create a set containing the cylinders valueunique_cyl = set(data['cylinders'] for data in mpg_data) # Let's print the valuesprint(unique_cyl) Output : As we can see in the output, we have 5 unique values of cylinders in our dataset.Code #3: Now let’s find out the value of average mpg for each value of cylinders. Python3 # Let's create an empty list to store the values# of average mpg for each cylinderavg_mpg = [] # c is the current cylinder sizefor c in unique_cyl: # for storing the sum of mpg mpgbycyl = 0 # for storing the sum of cylinder # in each category cylcount = 0 # iterate over all the data in mpg for x in mpg_data: # Check if current value matches c if x['cylinders']== c: # Add the mpg values for c mpgbycyl += float(x['mpg']) # increment the count of cylinder cylcount += 1 # Find the average mpg for size c avg = mpgbycyl/cylcount # Append the average mpg to list avg_mpg.append((c, avg)) # Sort the listavg_mpg.sort(key = lambda x : x[0]) # Print the listprint(avg_mpg) Output : As we can see in the output, the program has successfully returned a list of tuples containing the average mpg for each unique cylinder type in our dataset. rajeev0719singh CSV data-science Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n05 Aug, 2021" }, { "code": null, "e": 24953, "s": 24292, "text": "The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. There were various formats of CSV until its standardization. The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. For that purpose, we will use Python’s csv library to read and write tabular data in CSV format.For link to the CSV file used in the code click here.Code #1: We will use csv.DictReader() function to import the data file into the Python’s environment. " }, { "code": null, "e": 24961, "s": 24953, "text": "Python3" }, { "code": "# importing the csv moduleimport csv # Now let's read the file named 'auto-mpg.csv'# After reading as a dictionary convert# it to Python's listwith open('auto-mpg.csv') as csvfile: mpg_data = list(csv.DictReader(csvfile)) # Let's visualize the data# We are printing only first three elementsprint(mpg_data[:3])", "e": 25275, "s": 24961, "text": null }, { "code": null, "e": 25286, "s": 25275, "text": "Output : " }, { "code": null, "e": 25430, "s": 25286, "text": "As we can see the data is stored as a list of ordered dictionary. Let’s perform some operations on the data for better understanding.Code #2: " }, { "code": null, "e": 25438, "s": 25430, "text": "Python3" }, { "code": "# Let's find all the keys in the dictionaryprint(mpg_data[0].keys) # Now we would like to find out the number of# unique values of cylinders in the car in our dataset# We create a set containing the cylinders valueunique_cyl = set(data['cylinders'] for data in mpg_data) # Let's print the valuesprint(unique_cyl)", "e": 25751, "s": 25438, "text": null }, { "code": null, "e": 25762, "s": 25751, "text": "Output : " }, { "code": null, "e": 25928, "s": 25764, "text": "As we can see in the output, we have 5 unique values of cylinders in our dataset.Code #3: Now let’s find out the value of average mpg for each value of cylinders. " }, { "code": null, "e": 25936, "s": 25928, "text": "Python3" }, { "code": "# Let's create an empty list to store the values# of average mpg for each cylinderavg_mpg = [] # c is the current cylinder sizefor c in unique_cyl: # for storing the sum of mpg mpgbycyl = 0 # for storing the sum of cylinder # in each category cylcount = 0 # iterate over all the data in mpg for x in mpg_data: # Check if current value matches c if x['cylinders']== c: # Add the mpg values for c mpgbycyl += float(x['mpg']) # increment the count of cylinder cylcount += 1 # Find the average mpg for size c avg = mpgbycyl/cylcount # Append the average mpg to list avg_mpg.append((c, avg)) # Sort the listavg_mpg.sort(key = lambda x : x[0]) # Print the listprint(avg_mpg)", "e": 26698, "s": 25936, "text": null }, { "code": null, "e": 26709, "s": 26698, "text": "Output : " }, { "code": null, "e": 26867, "s": 26709, "text": "As we can see in the output, the program has successfully returned a list of tuples containing the average mpg for each unique cylinder type in our dataset. " }, { "code": null, "e": 26883, "s": 26867, "text": "rajeev0719singh" }, { "code": null, "e": 26887, "s": 26883, "text": "CSV" }, { "code": null, "e": 26900, "s": 26887, "text": "data-science" }, { "code": null, "e": 26914, "s": 26900, "text": "Python-pandas" }, { "code": null, "e": 26921, "s": 26914, "text": "Python" }, { "code": null, "e": 27019, "s": 26921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27028, "s": 27019, "text": "Comments" }, { "code": null, "e": 27041, "s": 27028, "text": "Old Comments" }, { "code": null, "e": 27073, "s": 27041, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27115, "s": 27073, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27170, "s": 27115, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27226, "s": 27170, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27268, "s": 27226, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27290, "s": 27268, "text": "Defaultdict in Python" }, { "code": null, "e": 27329, "s": 27290, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27360, "s": 27329, "text": "Python | os.path.join() method" }, { "code": null, "e": 27389, "s": 27360, "text": "Create a directory in Python" } ]
How to print a name multiple times without loop statement using C language?
Try to print a name 10 times without using any loop or goto statement in C programming language. Generally, looping statements are used to repeat the block of code until condition is false. In this program, we are trying to print a name 10 times without using loop or goto statements. Live Demo #include <stdio.h> void printname(char* name,int count){ printf("%03d : %s\n",count+1,name); count+=1; if(count<10) printname(name,count); } int main(){ char name[50]; printf("\nEnter you name :"); scanf("%s",name); printname(name,0); return 0; } Enter you name :tutorialspoint 001 : tutorialspoint 002 : tutorialspoint 003 : tutorialspoint 004 : tutorialspoint 005 : tutorialspoint 006 : tutorialspoint 007 : tutorialspoint 008 : tutorialspoint 009 : tutorialspoint 010 : tutorialspoint Below is the program to print your name 10 times using any loop or goto statement − Live Demo #include <stdio.h> int main(){ char name[50],i; printf("\nEnter you name :"); scanf("%s",name); for(i=0;i<10;i++){ printf("%s\n",name); } return 0; } Enter you name :TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint TutorialsPoint
[ { "code": null, "e": 1159, "s": 1062, "text": "Try to print a name 10 times without using any loop or goto statement in C programming language." }, { "code": null, "e": 1252, "s": 1159, "text": "Generally, looping statements are used to repeat the block of code until condition is false." }, { "code": null, "e": 1347, "s": 1252, "text": "In this program, we are trying to print a name 10 times without using loop or goto statements." }, { "code": null, "e": 1358, "s": 1347, "text": " Live Demo" }, { "code": null, "e": 1635, "s": 1358, "text": "#include <stdio.h>\nvoid printname(char* name,int count){\n printf(\"%03d : %s\\n\",count+1,name);\n count+=1;\n if(count<10)\n printname(name,count);\n}\nint main(){\n char name[50];\n printf(\"\\nEnter you name :\");\n scanf(\"%s\",name);\n printname(name,0);\n return 0;\n}" }, { "code": null, "e": 1876, "s": 1635, "text": "Enter you name :tutorialspoint\n001 : tutorialspoint\n002 : tutorialspoint\n003 : tutorialspoint\n004 : tutorialspoint\n005 : tutorialspoint\n006 : tutorialspoint\n007 : tutorialspoint\n008 : tutorialspoint\n009 : tutorialspoint\n010 : tutorialspoint" }, { "code": null, "e": 1960, "s": 1876, "text": "Below is the program to print your name 10 times using any loop or goto statement −" }, { "code": null, "e": 1971, "s": 1960, "text": " Live Demo" }, { "code": null, "e": 2145, "s": 1971, "text": "#include <stdio.h>\nint main(){\n char name[50],i;\n printf(\"\\nEnter you name :\");\n scanf(\"%s\",name);\n for(i=0;i<10;i++){\n printf(\"%s\\n\",name);\n }\n return 0;\n}" }, { "code": null, "e": 2326, "s": 2145, "text": "Enter you name :TutorialsPoint\nTutorialsPoint\nTutorialsPoint\nTutorialsPoint\nTutorialsPoint\nTutorialsPoint\nTutorialsPoint\nTutorialsPoint\nTutorialsPoint\nTutorialsPoint\nTutorialsPoint" } ]
Change the order of a Pandas DataFrame columns in Python - GeeksforGeeks
11 Aug, 2021 Let us see how to change the order of a DataFrame’s columns. Algorithm : Create a DataFrame. Reassign the same DataFrame with the order of the columns changed. Print the DataFrame. Example 1 : Python3 # importing the modulesimport pandas as pdimport numpy as np # creating the DataFramemy_data = {'Sr.no': [1, 2, 3, 4, 5], 'Name': ['Ram', 'Sham', 'Sonu', 'Tinu', 'Monu'], 'Maths Score': [45, 67, 89, 74, 56]}df = pd.DataFrame(data = my_data) # printing the original DataFrameprint("My Original DataFrame")print(df) # altering the DataFramedf = df[['Sr.no', 'Maths Score', 'Name']] # printing the altered DataFrameprint('After altering Name and Maths Score')print(df) Output: Example 2 : Python3 # importing the modulesimport pandas as pd # creating the DataFramel1 =["Amar", "Barsha", "Carlos", "Tanmay", "Misbah"]l2 =["Alpha", "Bravo", "Charlie", "Tango", "Mike"]l3 =[23, 25, 22, 27, 29]l4 =[69, 54, 73, 70, 74]df = pd.DataFrame(list(zip(l1, l2, l3, l4)))df.columns =['Name', 'Code', 'Age', 'Weight'] # printing the original DataFrameprint("My Original DataFrame")print(df) # altering the DataFramedf = df[['Name', 'Code', 'Weight', 'Age']] # printing the altered DataFrameprint('After altering Weight and Age')print(df) Output : saurabh1990aror surinderdawra388 Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python 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": 25054, "s": 25026, "text": "\n11 Aug, 2021" }, { "code": null, "e": 25116, "s": 25054, "text": "Let us see how to change the order of a DataFrame’s columns. " }, { "code": null, "e": 25130, "s": 25116, "text": "Algorithm : " }, { "code": null, "e": 25150, "s": 25130, "text": "Create a DataFrame." }, { "code": null, "e": 25217, "s": 25150, "text": "Reassign the same DataFrame with the order of the columns changed." }, { "code": null, "e": 25238, "s": 25217, "text": "Print the DataFrame." }, { "code": null, "e": 25250, "s": 25238, "text": "Example 1 :" }, { "code": null, "e": 25258, "s": 25250, "text": "Python3" }, { "code": "# importing the modulesimport pandas as pdimport numpy as np # creating the DataFramemy_data = {'Sr.no': [1, 2, 3, 4, 5], 'Name': ['Ram', 'Sham', 'Sonu', 'Tinu', 'Monu'], 'Maths Score': [45, 67, 89, 74, 56]}df = pd.DataFrame(data = my_data) # printing the original DataFrameprint(\"My Original DataFrame\")print(df) # altering the DataFramedf = df[['Sr.no', 'Maths Score', 'Name']] # printing the altered DataFrameprint('After altering Name and Maths Score')print(df)", "e": 25763, "s": 25258, "text": null }, { "code": null, "e": 25773, "s": 25763, "text": "Output: " }, { "code": null, "e": 25787, "s": 25775, "text": "Example 2 :" }, { "code": null, "e": 25795, "s": 25787, "text": "Python3" }, { "code": "# importing the modulesimport pandas as pd # creating the DataFramel1 =[\"Amar\", \"Barsha\", \"Carlos\", \"Tanmay\", \"Misbah\"]l2 =[\"Alpha\", \"Bravo\", \"Charlie\", \"Tango\", \"Mike\"]l3 =[23, 25, 22, 27, 29]l4 =[69, 54, 73, 70, 74]df = pd.DataFrame(list(zip(l1, l2, l3, l4)))df.columns =['Name', 'Code', 'Age', 'Weight'] # printing the original DataFrameprint(\"My Original DataFrame\")print(df) # altering the DataFramedf = df[['Name', 'Code', 'Weight', 'Age']] # printing the altered DataFrameprint('After altering Weight and Age')print(df)", "e": 26325, "s": 25795, "text": null }, { "code": null, "e": 26336, "s": 26325, "text": "Output : " }, { "code": null, "e": 26356, "s": 26340, "text": "saurabh1990aror" }, { "code": null, "e": 26373, "s": 26356, "text": "surinderdawra388" }, { "code": null, "e": 26397, "s": 26373, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26411, "s": 26397, "text": "Python-pandas" }, { "code": null, "e": 26418, "s": 26411, "text": "Python" }, { "code": null, "e": 26516, "s": 26418, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26525, "s": 26516, "text": "Comments" }, { "code": null, "e": 26538, "s": 26525, "text": "Old Comments" }, { "code": null, "e": 26556, "s": 26538, "text": "Python Dictionary" }, { "code": null, "e": 26591, "s": 26556, "text": "Read a file line by line in Python" }, { "code": null, "e": 26623, "s": 26591, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26645, "s": 26623, "text": "Enumerate() in Python" }, { "code": null, "e": 26675, "s": 26645, "text": "Iterate over a list in Python" }, { "code": null, "e": 26717, "s": 26675, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26743, "s": 26717, "text": "Python String | replace()" }, { "code": null, "e": 26786, "s": 26743, "text": "Python program to convert a list to string" }, { "code": null, "e": 26823, "s": 26786, "text": "Create a Pandas DataFrame from Lists" } ]
Check if all bits can be made same by single flip - GeeksforGeeks
25 Aug, 2021 Given a binary string, find if it is possible to make all its digits equal (either all 0’s or all 1’s) by flipping exactly one bit. Input: 101 Output: Yes Explanation: In 101, the 0 can be flipped to make it all 1 Input: 11 Output: No Explanation: No matter whichever digit you flip, you will not get the desired string. Input: 1 Output: Yes Explanation: We can flip 1, to make all 0's Method 1 (Counting 0’s and 1’s) If all digits of a string can be made identical by doing exactly one flip, that means the string has all its digits equal to one another except this digit which has to be flipped, and this digit must be different than all other digits of the string. The value of this digit could be either zero or one. Hence, this string will either have exactly one digit equal to zero, and all other digits equal to one, or exactly one digit equal to one, and all other digit equal to zero.Therefore, we only need to check whether the string has exactly one digit equal to zero/one, and if so, the answer is yes; otherwise the answer is no. Below is the implementation of above idea. C++ Java Python3 C# PHP Javascript // C++ program to check if a single bit can// be flipped tp make all ones#include <bits/stdc++.h>using namespace std; // This function returns true if we can// bits same in given binary string str.bool canMakeAllSame(string str){ int zeros = 0, ones = 0; // Traverse through given string and // count numbers of 0's and 1's for (char ch : str) (ch == '0') ? ++zeros : ++ones; // Return true if any of the two counts // is 1 return (zeros == 1 || ones == 1);} // Driver codeint main(){ canMakeAllSame("101") ? printf("Yes\n") : printf("No\n"); return 0;} // Java program to check if a single bit can// be flipped to make all onespublic class GFG { // This function returns true if we can // bits same in given binary string str. static boolean canMakeAllSame(String str) { int zeros = 0, ones = 0; // Traverse through given string and // count numbers of 0's and 1's for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == '0') ++zeros; else ++ones; } // Return true if any of the two counts // is 1 return (zeros == 1 || ones == 1); } // Driver code public static void main(String args[]) { System.out.println(canMakeAllSame("101") ? "Yes" : "No"); }}// This code is contributed by Sumit Ghosh # python program to check if a single# bit can be flipped tp make all ones # This function returns true if we can# bits same in given binary string str.def canMakeAllSame(str): zeros = 0 ones = 0 # Traverse through given string and # count numbers of 0's and 1's for i in range(0, len(str)): ch = str[i]; if (ch == '0'): zeros = zeros + 1 else: ones = ones + 1 # Return true if any of the two # counts is 1 return (zeros == 1 or ones == 1); # Driver codeif(canMakeAllSame("101")): print("Yes\n")else: print("No\n") # This code is contributed by Sam007. // C# program to check if a single bit can// be flipped to make all onesusing System; class GFG { // This function returns true if we can // bits same in given binary string str. static bool canMakeAllSame(string str) { int zeros = 0, ones = 0; // Traverse through given string and // count numbers of 0's and 1's for (int i = 0; i < str.Length; i++) { char ch = str[i]; if (ch == '0') ++zeros; else ++ones; } // Return true if any of the two counts // is 1 return (zeros == 1 || ones == 1); } // Driver code public static void Main() { Console.WriteLine(canMakeAllSame("101") ? "Yes" : "No"); }} // This code is contributed by Sam007 <?php // PHP program to check if a single bit can// be flipped tp make all ones // This function returns true if we can// bits same in given binary string str.function canMakeAllSame($str){ $zeros = 0; $ones = 0; // Traverse through given string and // count numbers of 0's and 1's for($i=0;$i<strlen($str);$i++) { $ch = $str[$i]; if ($ch == '0') ++$zeros ; else ++$ones; } // Return true if any of the two counts // is 1 return ($zeros == 1 || $ones == 1);} // Driver code if (canMakeAllSame("101") ) echo "Yes\n" ; else echo "No\n"; return 0;?> <script>// Javascript program to check if a single bit can// be flipped to make all ones // This function returns true if we can // bits same in given binary string str. function canMakeAllSame(str) { let zeros = 0, ones = 0; // Traverse through given string and // count numbers of 0's and 1's for (let i = 0; i < str.length; i++) { let ch = str[i]; if (ch == '0') ++zeros; else ++ones; } // Return true if any of the two counts // is 1 return (zeros == 1 || ones == 1); } // Driver code document.write(canMakeAllSame("101") ? "Yes" : "No"); // This code is contributed by rag2127</script> Output: Yes Time complexity : O(n) where n is the length of the string. Method 2 (Counting 0’s and 1’s) The idea is to compute sum of all bits. If sum is n-1 or 1, then output is true, else false. This solution doesn’t require a comparison in a loop. Below is the implementation of above idea. C++ Java Python3 C# PHP Javascript // Check if all bits can be made same by single flip// Idea is to add the integer value all the elements// in the given string.// If the sum is 1 it indicates that there is// only single '1' in the string.// If the sum is 0 it indicates that there is only// single '0' in the string.// It takes O(n) time. #include <bits/stdc++.h>using namespace std; bool isOneFlip(string str){ int sum = 0; int n = str.length(); // Traverse through given string and // count the total sum of numbers for (int i = 0; i < n; i++) sum += str[i] - '0'; // Return true if any of the two counts // is 1 return (sum == n - 1 || sum == 1);} // Main functionint main(){ isOneFlip("101111111111") ? printf("Yes\n") : printf("No\n"); return 0;} /*Check if all bits can be made same by singleflip. Idea is to add the integer value all theelements in the given string.If the sum is 1 it indicates that there is only single '1' in the string.If the sum is 0 it indicates that there is only single '0' in the string.It takes O(n) time.*/public class GFG { static boolean isOneFlip(String str) { int sum = 0; int n = str.length(); // Traverse through given string and // count the total sum of numbers for (int i = 0; i < n; i++) sum += str.charAt(i) - '0'; // Return true if any of the two counts // is 1 return (sum == n - 1 || sum == 1); } // Main function public static void main(String args[]) { System.out.println(isOneFlip("101111111111") ? "Yes" : "No"); }}// This code is contributed by Sumit Ghosh # Check if all bits can be made same# by single flip Idea is to add the# integer value all the elements in# the given string. If the sum is 1# it indicates that there is only# single '1' in the string. If the# sum is 0 it indicates that there# is only single '0' in the string.# It takes O(n) time. def isOneFlip(str): sum = 0 n = len(str) # Traverse through given string # and count the total sum of # numbers for i in range( 0, n ): sum += int(str[i]) - int('0') # Return true if any of the two # counts is 1 return (sum == n - 1 or sum == 1) # Main function(print("Yes") if isOneFlip("101111111111") else print("No")) # This code is contributed by Smitha /*Check if all bits can be made same by single flip. Idea is to add the integer value all the elements in the given string. If the sum is 1 it indicates that there is only single '1' in the string. If the sum is 0 it indicates that there is only single '0' in the string. It takes O(n) time.*/using System; class GFG { static bool isOneFlip(string str) { int sum = 0; int n = str.Length; // Traverse through given string and // count the total sum of numbers for (int i = 0; i < n; i++) sum += str[i] - '0'; // Return true if any of the two counts // is 1 return (sum == n - 1 || sum == 1); } // Driver code public static void Main() { Console.WriteLine(isOneFlip("101111111111") ? "Yes" : "No"); }} // This code is contributed by Sam007 <?php// Check if all bits can be made same by// single flip Idea is to add the integer// value all the elements in the given// string. If the sum is 1 it indicates// that there is only single '1' in the// string. If the sum is 0 it indicates// that there is only single '0' in the// string. It takes O(n) time. function isOneFlip($str){ $sum = 0; $n = strlen($str); // Traverse through given string and // count the total sum of numbers for ( $i = 0; $i < $n; $i++) $sum += $str[$i] - '0'; // Return true if any of the two counts // is 1 return ($sum == $n - 1 || $sum == 1);} // Main function if(isOneFlip("101111111111") ) echo "Yes\n"; else echo "No\n"; // This code is contributed by aj_36?> <script> /*Check if all bits can be made same by singleflip. Idea is to add the integer value all theelements in the given string.If the sum is 1 it indicates that there is only single '1' in the string.If the sum is 0 it indicates that there is only single '0' in the string.It takes O(n) time.*/function isOneFlip(str){ let sum = 0; let n = str.length; // Traverse through given string and // count the total sum of numbers for(let i = 0; i < n; i++) sum += str[i] - '0'; // Return true if any of the two counts // is 1 return (sum == n - 1 || sum == 1);} // Driver codedocument.write(isOneFlip("101111111111") ? "Yes" : "No"); // This code is contributed by avanitrachhadiya2155 </script> Output: Yes Time Complexity: O(N)Auxiliary Space: O(1) Thanks to Sourabh Gavhale for suggesting this solution This article is contributed by Subrata Ghosh. 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. Sam007 Smitha Dinesh Semwal jit_t ukasp rag2127 avanitrachhadiya2155 pankajsharmagfg rs1686740 binary-string Algorithms Arrays Arrays Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms Playfair Cipher with Examples How to write a Pseudo Code? Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Write a program to reverse an array or string
[ { "code": null, "e": 25155, "s": 25127, "text": "\n25 Aug, 2021" }, { "code": null, "e": 25288, "s": 25155, "text": "Given a binary string, find if it is possible to make all its digits equal (either all 0’s or all 1’s) by flipping exactly one bit. " }, { "code": null, "e": 25560, "s": 25288, "text": "Input: 101\nOutput: Yes\nExplanation: In 101, the 0 can be flipped\n to make it all 1\n\nInput: 11\nOutput: No\nExplanation: No matter whichever digit you \n flip, you will not get the desired string.\n\nInput: 1\nOutput: Yes\nExplanation: We can flip 1, to make all 0's" }, { "code": null, "e": 26219, "s": 25560, "text": "Method 1 (Counting 0’s and 1’s) If all digits of a string can be made identical by doing exactly one flip, that means the string has all its digits equal to one another except this digit which has to be flipped, and this digit must be different than all other digits of the string. The value of this digit could be either zero or one. Hence, this string will either have exactly one digit equal to zero, and all other digits equal to one, or exactly one digit equal to one, and all other digit equal to zero.Therefore, we only need to check whether the string has exactly one digit equal to zero/one, and if so, the answer is yes; otherwise the answer is no." }, { "code": null, "e": 26264, "s": 26219, "text": "Below is the implementation of above idea. " }, { "code": null, "e": 26268, "s": 26264, "text": "C++" }, { "code": null, "e": 26273, "s": 26268, "text": "Java" }, { "code": null, "e": 26281, "s": 26273, "text": "Python3" }, { "code": null, "e": 26284, "s": 26281, "text": "C#" }, { "code": null, "e": 26288, "s": 26284, "text": "PHP" }, { "code": null, "e": 26299, "s": 26288, "text": "Javascript" }, { "code": "// C++ program to check if a single bit can// be flipped tp make all ones#include <bits/stdc++.h>using namespace std; // This function returns true if we can// bits same in given binary string str.bool canMakeAllSame(string str){ int zeros = 0, ones = 0; // Traverse through given string and // count numbers of 0's and 1's for (char ch : str) (ch == '0') ? ++zeros : ++ones; // Return true if any of the two counts // is 1 return (zeros == 1 || ones == 1);} // Driver codeint main(){ canMakeAllSame(\"101\") ? printf(\"Yes\\n\") : printf(\"No\\n\"); return 0;}", "e": 26889, "s": 26299, "text": null }, { "code": "// Java program to check if a single bit can// be flipped to make all onespublic class GFG { // This function returns true if we can // bits same in given binary string str. static boolean canMakeAllSame(String str) { int zeros = 0, ones = 0; // Traverse through given string and // count numbers of 0's and 1's for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == '0') ++zeros; else ++ones; } // Return true if any of the two counts // is 1 return (zeros == 1 || ones == 1); } // Driver code public static void main(String args[]) { System.out.println(canMakeAllSame(\"101\") ? \"Yes\" : \"No\"); }}// This code is contributed by Sumit Ghosh", "e": 27706, "s": 26889, "text": null }, { "code": "# python program to check if a single# bit can be flipped tp make all ones # This function returns true if we can# bits same in given binary string str.def canMakeAllSame(str): zeros = 0 ones = 0 # Traverse through given string and # count numbers of 0's and 1's for i in range(0, len(str)): ch = str[i]; if (ch == '0'): zeros = zeros + 1 else: ones = ones + 1 # Return true if any of the two # counts is 1 return (zeros == 1 or ones == 1); # Driver codeif(canMakeAllSame(\"101\")): print(\"Yes\\n\")else: print(\"No\\n\") # This code is contributed by Sam007.", "e": 28334, "s": 27706, "text": null }, { "code": "// C# program to check if a single bit can// be flipped to make all onesusing System; class GFG { // This function returns true if we can // bits same in given binary string str. static bool canMakeAllSame(string str) { int zeros = 0, ones = 0; // Traverse through given string and // count numbers of 0's and 1's for (int i = 0; i < str.Length; i++) { char ch = str[i]; if (ch == '0') ++zeros; else ++ones; } // Return true if any of the two counts // is 1 return (zeros == 1 || ones == 1); } // Driver code public static void Main() { Console.WriteLine(canMakeAllSame(\"101\") ? \"Yes\" : \"No\"); }} // This code is contributed by Sam007", "e": 29130, "s": 28334, "text": null }, { "code": "<?php // PHP program to check if a single bit can// be flipped tp make all ones // This function returns true if we can// bits same in given binary string str.function canMakeAllSame($str){ $zeros = 0; $ones = 0; // Traverse through given string and // count numbers of 0's and 1's for($i=0;$i<strlen($str);$i++) { $ch = $str[$i]; if ($ch == '0') ++$zeros ; else ++$ones; } // Return true if any of the two counts // is 1 return ($zeros == 1 || $ones == 1);} // Driver code if (canMakeAllSame(\"101\") ) echo \"Yes\\n\" ; else echo \"No\\n\"; return 0;?>", "e": 29775, "s": 29130, "text": null }, { "code": "<script>// Javascript program to check if a single bit can// be flipped to make all ones // This function returns true if we can // bits same in given binary string str. function canMakeAllSame(str) { let zeros = 0, ones = 0; // Traverse through given string and // count numbers of 0's and 1's for (let i = 0; i < str.length; i++) { let ch = str[i]; if (ch == '0') ++zeros; else ++ones; } // Return true if any of the two counts // is 1 return (zeros == 1 || ones == 1); } // Driver code document.write(canMakeAllSame(\"101\") ? \"Yes\" : \"No\"); // This code is contributed by rag2127</script>", "e": 30530, "s": 29775, "text": null }, { "code": null, "e": 30539, "s": 30530, "text": "Output: " }, { "code": null, "e": 30543, "s": 30539, "text": "Yes" }, { "code": null, "e": 30603, "s": 30543, "text": "Time complexity : O(n) where n is the length of the string." }, { "code": null, "e": 30782, "s": 30603, "text": "Method 2 (Counting 0’s and 1’s) The idea is to compute sum of all bits. If sum is n-1 or 1, then output is true, else false. This solution doesn’t require a comparison in a loop." }, { "code": null, "e": 30827, "s": 30782, "text": "Below is the implementation of above idea. " }, { "code": null, "e": 30831, "s": 30827, "text": "C++" }, { "code": null, "e": 30836, "s": 30831, "text": "Java" }, { "code": null, "e": 30844, "s": 30836, "text": "Python3" }, { "code": null, "e": 30847, "s": 30844, "text": "C#" }, { "code": null, "e": 30851, "s": 30847, "text": "PHP" }, { "code": null, "e": 30862, "s": 30851, "text": "Javascript" }, { "code": "// Check if all bits can be made same by single flip// Idea is to add the integer value all the elements// in the given string.// If the sum is 1 it indicates that there is// only single '1' in the string.// If the sum is 0 it indicates that there is only// single '0' in the string.// It takes O(n) time. #include <bits/stdc++.h>using namespace std; bool isOneFlip(string str){ int sum = 0; int n = str.length(); // Traverse through given string and // count the total sum of numbers for (int i = 0; i < n; i++) sum += str[i] - '0'; // Return true if any of the two counts // is 1 return (sum == n - 1 || sum == 1);} // Main functionint main(){ isOneFlip(\"101111111111\") ? printf(\"Yes\\n\") : printf(\"No\\n\"); return 0;}", "e": 31621, "s": 30862, "text": null }, { "code": "/*Check if all bits can be made same by singleflip. Idea is to add the integer value all theelements in the given string.If the sum is 1 it indicates that there is only single '1' in the string.If the sum is 0 it indicates that there is only single '0' in the string.It takes O(n) time.*/public class GFG { static boolean isOneFlip(String str) { int sum = 0; int n = str.length(); // Traverse through given string and // count the total sum of numbers for (int i = 0; i < n; i++) sum += str.charAt(i) - '0'; // Return true if any of the two counts // is 1 return (sum == n - 1 || sum == 1); } // Main function public static void main(String args[]) { System.out.println(isOneFlip(\"101111111111\") ? \"Yes\" : \"No\"); }}// This code is contributed by Sumit Ghosh", "e": 32482, "s": 31621, "text": null }, { "code": "# Check if all bits can be made same# by single flip Idea is to add the# integer value all the elements in# the given string. If the sum is 1# it indicates that there is only# single '1' in the string. If the# sum is 0 it indicates that there# is only single '0' in the string.# It takes O(n) time. def isOneFlip(str): sum = 0 n = len(str) # Traverse through given string # and count the total sum of # numbers for i in range( 0, n ): sum += int(str[i]) - int('0') # Return true if any of the two # counts is 1 return (sum == n - 1 or sum == 1) # Main function(print(\"Yes\") if isOneFlip(\"101111111111\") else print(\"No\")) # This code is contributed by Smitha", "e": 33200, "s": 32482, "text": null }, { "code": "/*Check if all bits can be made same by single flip. Idea is to add the integer value all the elements in the given string. If the sum is 1 it indicates that there is only single '1' in the string. If the sum is 0 it indicates that there is only single '0' in the string. It takes O(n) time.*/using System; class GFG { static bool isOneFlip(string str) { int sum = 0; int n = str.Length; // Traverse through given string and // count the total sum of numbers for (int i = 0; i < n; i++) sum += str[i] - '0'; // Return true if any of the two counts // is 1 return (sum == n - 1 || sum == 1); } // Driver code public static void Main() { Console.WriteLine(isOneFlip(\"101111111111\") ? \"Yes\" : \"No\"); }} // This code is contributed by Sam007", "e": 34048, "s": 33200, "text": null }, { "code": "<?php// Check if all bits can be made same by// single flip Idea is to add the integer// value all the elements in the given// string. If the sum is 1 it indicates// that there is only single '1' in the// string. If the sum is 0 it indicates// that there is only single '0' in the// string. It takes O(n) time. function isOneFlip($str){ $sum = 0; $n = strlen($str); // Traverse through given string and // count the total sum of numbers for ( $i = 0; $i < $n; $i++) $sum += $str[$i] - '0'; // Return true if any of the two counts // is 1 return ($sum == $n - 1 || $sum == 1);} // Main function if(isOneFlip(\"101111111111\") ) echo \"Yes\\n\"; else echo \"No\\n\"; // This code is contributed by aj_36?>", "e": 34797, "s": 34048, "text": null }, { "code": "<script> /*Check if all bits can be made same by singleflip. Idea is to add the integer value all theelements in the given string.If the sum is 1 it indicates that there is only single '1' in the string.If the sum is 0 it indicates that there is only single '0' in the string.It takes O(n) time.*/function isOneFlip(str){ let sum = 0; let n = str.length; // Traverse through given string and // count the total sum of numbers for(let i = 0; i < n; i++) sum += str[i] - '0'; // Return true if any of the two counts // is 1 return (sum == n - 1 || sum == 1);} // Driver codedocument.write(isOneFlip(\"101111111111\") ? \"Yes\" : \"No\"); // This code is contributed by avanitrachhadiya2155 </script>", "e": 35540, "s": 34797, "text": null }, { "code": null, "e": 35549, "s": 35540, "text": "Output: " }, { "code": null, "e": 35553, "s": 35549, "text": "Yes" }, { "code": null, "e": 35651, "s": 35553, "text": "Time Complexity: O(N)Auxiliary Space: O(1) Thanks to Sourabh Gavhale for suggesting this solution" }, { "code": null, "e": 36073, "s": 35651, "text": "This article is contributed by Subrata Ghosh. 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": 36080, "s": 36073, "text": "Sam007" }, { "code": null, "e": 36101, "s": 36080, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 36107, "s": 36101, "text": "jit_t" }, { "code": null, "e": 36113, "s": 36107, "text": "ukasp" }, { "code": null, "e": 36121, "s": 36113, "text": "rag2127" }, { "code": null, "e": 36142, "s": 36121, "text": "avanitrachhadiya2155" }, { "code": null, "e": 36158, "s": 36142, "text": "pankajsharmagfg" }, { "code": null, "e": 36168, "s": 36158, "text": "rs1686740" }, { "code": null, "e": 36182, "s": 36168, "text": "binary-string" }, { "code": null, "e": 36193, "s": 36182, "text": "Algorithms" }, { "code": null, "e": 36200, "s": 36193, "text": "Arrays" }, { "code": null, "e": 36207, "s": 36200, "text": "Arrays" }, { "code": null, "e": 36218, "s": 36207, "text": "Algorithms" }, { "code": null, "e": 36316, "s": 36218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36325, "s": 36316, "text": "Comments" }, { "code": null, "e": 36338, "s": 36325, "text": "Old Comments" }, { "code": null, "e": 36387, "s": 36338, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 36412, "s": 36387, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 36439, "s": 36412, "text": "Introduction to Algorithms" }, { "code": null, "e": 36469, "s": 36439, "text": "Playfair Cipher with Examples" }, { "code": null, "e": 36497, "s": 36469, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 36512, "s": 36497, "text": "Arrays in Java" }, { "code": null, "e": 36528, "s": 36512, "text": "Arrays in C/C++" }, { "code": null, "e": 36555, "s": 36528, "text": "Program for array rotation" }, { "code": null, "e": 36603, "s": 36555, "text": "Stack Data Structure (Introduction and Program)" } ]
Tryit Editor v3.6 - Show Node.js
var http = require('http'); var url = require('url'); ​ http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); /*Use the url module to turn the querystring into an object:*/ var q = url.parse(req.url, true).query; /*Return the year and month from the query object:*/ var txt = q.year + " " + q.month;
[ { "code": null, "e": 28, "s": 0, "text": "var http = require('http');" }, { "code": null, "e": 54, "s": 28, "text": "var url = require('url');" }, { "code": null, "e": 56, "s": 54, "text": "​" }, { "code": null, "e": 96, "s": 56, "text": "http.createServer(function (req, res) {" }, { "code": null, "e": 149, "s": 96, "text": " res.writeHead(200, {'Content-Type': 'text/html'});" }, { "code": null, "e": 214, "s": 149, "text": " /*Use the url module to turn the querystring into an object:*/" }, { "code": null, "e": 256, "s": 214, "text": " var q = url.parse(req.url, true).query;" }, { "code": null, "e": 311, "s": 256, "text": " /*Return the year and month from the query object:*/" } ]
How to Install Scipy In Python on Linux? - GeeksforGeeks
17 Oct, 2021 In this article, we are going to see how to install Scipy in Python on Linux, SciPy is a python library that is useful in solving many mathematical equations and algorithms, it is a free and open-source Python library built on top of the popular NumPy library. There are generally two easy methods using which we can install SciPy on our Linux machine. One is simply using the inbuilt package manager that comes with the installation of Linux and the second is using the pip, the python package manager. Both the methods take merely a single command to install SciPy. Step 1: To install the SciPy run the following command, this command will install the SciPy and the required dependencies as well: pip3 install numpy scipy matplotlib ipython jupyter pandas sympy nose Installing scipy Step 2: To verify the installation, run the following command: python3 -m pip show scipy Scipy installed Step 1: Install Aptitude package manager using the following command, Aptitude package manager is an interactive package manager for installing packages in the Linux system. sudo apt install aptitude Installation using aptitude Step 2: Install Scipy using the aptitude package manager. sudo aptitude install python3-scipy Installing the scipy using aptitude Note: You can also use the inbuilt package manager apt-get. sudo apt-get install python3-scipy Both the command will result, the successful installation of the scipy. Installing the scipy using apt-get Step 3: To verify the installation, run the following command: Verifying the installation how-to-install linux Picked How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Install Jupyter Notebook on MacOS? How to Add External JAR File to an IntelliJ IDEA Project? How to Create and Setup Spring Boot Project in Eclipse IDE? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Install Jupyter Notebook on MacOS? How to Add External JAR File to an IntelliJ IDEA Project?
[ { "code": null, "e": 24561, "s": 24533, "text": "\n17 Oct, 2021" }, { "code": null, "e": 24822, "s": 24561, "text": "In this article, we are going to see how to install Scipy in Python on Linux, SciPy is a python library that is useful in solving many mathematical equations and algorithms, it is a free and open-source Python library built on top of the popular NumPy library." }, { "code": null, "e": 25129, "s": 24822, "text": "There are generally two easy methods using which we can install SciPy on our Linux machine. One is simply using the inbuilt package manager that comes with the installation of Linux and the second is using the pip, the python package manager. Both the methods take merely a single command to install SciPy." }, { "code": null, "e": 25260, "s": 25129, "text": "Step 1: To install the SciPy run the following command, this command will install the SciPy and the required dependencies as well:" }, { "code": null, "e": 25330, "s": 25260, "text": "pip3 install numpy scipy matplotlib ipython jupyter pandas sympy nose" }, { "code": null, "e": 25347, "s": 25330, "text": "Installing scipy" }, { "code": null, "e": 25410, "s": 25347, "text": "Step 2: To verify the installation, run the following command:" }, { "code": null, "e": 25436, "s": 25410, "text": "python3 -m pip show scipy" }, { "code": null, "e": 25452, "s": 25436, "text": "Scipy installed" }, { "code": null, "e": 25626, "s": 25452, "text": "Step 1: Install Aptitude package manager using the following command, Aptitude package manager is an interactive package manager for installing packages in the Linux system." }, { "code": null, "e": 25652, "s": 25626, "text": "sudo apt install aptitude" }, { "code": null, "e": 25680, "s": 25652, "text": "Installation using aptitude" }, { "code": null, "e": 25738, "s": 25680, "text": "Step 2: Install Scipy using the aptitude package manager." }, { "code": null, "e": 25776, "s": 25738, "text": "sudo aptitude install python3-scipy " }, { "code": null, "e": 25812, "s": 25776, "text": "Installing the scipy using aptitude" }, { "code": null, "e": 25872, "s": 25812, "text": "Note: You can also use the inbuilt package manager apt-get." }, { "code": null, "e": 25907, "s": 25872, "text": "sudo apt-get install python3-scipy" }, { "code": null, "e": 25979, "s": 25907, "text": "Both the command will result, the successful installation of the scipy." }, { "code": null, "e": 26014, "s": 25979, "text": "Installing the scipy using apt-get" }, { "code": null, "e": 26077, "s": 26014, "text": "Step 3: To verify the installation, run the following command:" }, { "code": null, "e": 26104, "s": 26077, "text": "Verifying the installation" }, { "code": null, "e": 26119, "s": 26104, "text": "how-to-install" }, { "code": null, "e": 26125, "s": 26119, "text": "linux" }, { "code": null, "e": 26132, "s": 26125, "text": "Picked" }, { "code": null, "e": 26139, "s": 26132, "text": "How To" }, { "code": null, "e": 26158, "s": 26139, "text": "Installation Guide" }, { "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": 26265, "s": 26256, "text": "Comments" }, { "code": null, "e": 26278, "s": 26265, "text": "Old Comments" }, { "code": null, "e": 26312, "s": 26278, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26361, "s": 26312, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 26403, "s": 26361, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 26461, "s": 26403, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 26521, "s": 26461, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 26554, "s": 26521, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26588, "s": 26554, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26623, "s": 26588, "text": "How to Install Pygame on Windows ?" }, { "code": null, "e": 26665, "s": 26623, "text": "How to Install Jupyter Notebook on MacOS?" } ]
What is batch processing in JDBC?
Grouping related SQL statements into a batch and executing/submitting them at once is known as batch processing. While executing a set of statements one after other the execution switches from the database to program simultaneously. Using batch processing we can reduce this communication overhead and increase the performance of our Java application. For Example, if we have a table named Emp with the following description: +----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | DOB | String | YES | | NULL | | | Location | varchar(255) | YES | | NULL | | +----------+--------------+------+-----+---------+-------+ And if you want to insert data we will generally do it using the statement as: Stmt.execute("INSERT INTO Emp VALUES ('Amit', '30-9-1989', 'Hyderabad')"); Stmt.execute("INSERT INTO Emp VALUES ('Amit', '1-9-1989', 'Vishakhapatnam')"); And using PreparedStatement as: String query = "INSERT INTO Emp(Name, String, Location) VALUES (?, ?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "Amit"); pstmt.setDate(2, "30-9-1989")); pstmt.setString(3, "Hyderabad"); pstmt.execute(); pstmt.setString(1, "Sumith"); pstmt.setDate(2, "1-9-1989"); //Friday, Sept 1, 1989 12:00:00 AM pstmt.setString(3, "Vishakhapatnam"); pstmt.execute(); If you observe carefully in both scenarios, we are executing each insert statement individually. Which implies for each insert statement in the program, when the execute() method invoked, the insert statement is executed in the database and reverts back to the program. This is ok for less number of inserts. But if this happens while inserting huge number of records this may occur communication overhead and the program takes more time to execute. Using Batch Processing you can simply add the statements to the batch using the addBatch() method of the Statement Interface and execute them later using the executeBatch() method as shown below: Stmt.addBatch("INSERT INTO Emp VALUES ('Amit', '30-9-1989', 'Hyderabad')"); Stmt.addBatch("INSERT INTO Emp VALUES ('Amit', '1-9-1989', 'Vishakhapatnam')"); Stmt.executeBatch(); pstmt.setString(1, "Amit"); pstmt.setDate(2, "30-9-1989")); pstmt.setString(3, "Hyderabad"); pstmt.addBatch(); pstmt.setString(1, "Sumith"); pstmt.setDate(2, "1-9-1989"); //Friday, Sept 1, 1989 12:00:00 AM pstmt.setString(3, "Vishakhapatnam"); pstmt.addBatch(); pstmt.executeBatch();
[ { "code": null, "e": 1175, "s": 1062, "text": "Grouping related SQL statements into a batch and executing/submitting them at once is known as batch processing." }, { "code": null, "e": 1295, "s": 1175, "text": "While executing a set of statements one after other the execution switches from the database to program simultaneously." }, { "code": null, "e": 1414, "s": 1295, "text": "Using batch processing we can reduce this communication overhead and increase the performance of our Java application." }, { "code": null, "e": 1488, "s": 1414, "text": "For Example, if we have a table named Emp with the following description:" }, { "code": null, "e": 1901, "s": 1488, "text": "+----------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+----------+--------------+------+-----+---------+-------+\n| Name | varchar(255) | YES | | NULL | |\n| DOB | String | YES | | NULL | |\n| Location | varchar(255) | YES | | NULL | |\n+----------+--------------+------+-----+---------+-------+" }, { "code": null, "e": 1980, "s": 1901, "text": "And if you want to insert data we will generally do it using the statement as:" }, { "code": null, "e": 2134, "s": 1980, "text": "Stmt.execute(\"INSERT INTO Emp VALUES ('Amit', '30-9-1989', 'Hyderabad')\");\nStmt.execute(\"INSERT INTO Emp VALUES ('Amit', '1-9-1989', 'Vishakhapatnam')\");" }, { "code": null, "e": 2166, "s": 2134, "text": "And using PreparedStatement as:" }, { "code": null, "e": 2556, "s": 2166, "text": "String query = \"INSERT INTO Emp(Name, String, Location) VALUES (?, ?, ?)\";\nPreparedStatement pstmt = con.prepareStatement(query);\npstmt.setString(1, \"Amit\");\npstmt.setDate(2, \"30-9-1989\"));\npstmt.setString(3, \"Hyderabad\");\npstmt.execute();\npstmt.setString(1, \"Sumith\");\npstmt.setDate(2, \"1-9-1989\"); //Friday, Sept 1, 1989 12:00:00 AM\npstmt.setString(3, \"Vishakhapatnam\");\npstmt.execute();" }, { "code": null, "e": 2826, "s": 2556, "text": "If you observe carefully in both scenarios, we are executing each insert statement individually. Which implies for each insert statement in the program, when the execute() method invoked, the insert statement is executed in the database and reverts back to the program." }, { "code": null, "e": 3006, "s": 2826, "text": "This is ok for less number of inserts. But if this happens while inserting huge number of records this may occur communication overhead and the program takes more time to execute." }, { "code": null, "e": 3202, "s": 3006, "text": "Using Batch Processing you can simply add the statements to the batch using the addBatch() method of the Statement Interface and execute them later using the executeBatch() method as shown below:" }, { "code": null, "e": 3663, "s": 3202, "text": "Stmt.addBatch(\"INSERT INTO Emp VALUES ('Amit', '30-9-1989', 'Hyderabad')\");\nStmt.addBatch(\"INSERT INTO Emp VALUES ('Amit', '1-9-1989', 'Vishakhapatnam')\");\nStmt.executeBatch();\npstmt.setString(1, \"Amit\");\npstmt.setDate(2, \"30-9-1989\"));\npstmt.setString(3, \"Hyderabad\");\npstmt.addBatch();\npstmt.setString(1, \"Sumith\");\npstmt.setDate(2, \"1-9-1989\"); //Friday, Sept 1, 1989 12:00:00 AM\npstmt.setString(3, \"Vishakhapatnam\");\npstmt.addBatch();\npstmt.executeBatch();" } ]
SWING - CardLayout Class
The class CardLayout arranges each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. Following is the declaration for java.awt.CardLayout class − public class CardLayout extends Object implements LayoutManager2, Serializable CardLayout() Creates a new card layout with the gaps of size zero. CardLayout(int hgap, int vgap) Creates a new card layout with the specified horizontal and vertical gaps. void addLayoutComponent(Component comp, Object constraints) Adds the specified component to this card layout's internal table of names. void addLayoutComponent(String name, Component comp) If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name. void first(Container parent) Flips to the first card of the container. int getHgap() Gets the horizontal gap between the components. float getLayoutAlignmentX(Container parent) Returns the alignment along the x axis. float getLayoutAlignmentY(Container parent) Returns the alignment along the y axis. int getVgap() Gets the vertical gap between the components. void invalidateLayout(Container target) Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. void last(Container parent) Flips to the last card of the container. void layoutContainer(Container parent) Lays out the specified container using this card layout. Dimension maximumLayoutSize(Container target) Returns the maximum dimensions for this layout given the components in the specified target container. Dimension minimumLayoutSize(Container parent) Calculates the minimum size for the specified panel. void next(Container parent) Flips to the next card of the specified container. Dimension preferredLayoutSize(Container parent) Determines the preferred size of the container argument using this card layout. void previous(Container parent) Flips to the previous card of the specified container. void removeLayoutComponent(Component comp) Removes the specified component from the layout. void setHgap(int hgap) Sets the horizontal gap between the components. void setVgap(int vgap) Sets the vertical gap between the components. void show(Container parent, String name) Flips to the component that was added to this layout with the specified name, using addLayoutComponent. String toString() Returns a string representation of the state of this card layout. This class inherits methods from the following class − java.lang.Object Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui > SwingLayoutDemo.java package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingLayoutDemo { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; private JLabel msglabel; public SwingLayoutDemo(){ prepareGUI(); } public static void main(String[] args){ SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo(); swingLayoutDemo.showCardLayoutDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java SWING Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); headerLabel = new JLabel("",JLabel.CENTER ); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showCardLayoutDemo(){ headerLabel.setText("Layout in action: CardLayout"); final JPanel panel = new JPanel(); panel.setBackground(Color.CYAN); panel.setSize(300,300); CardLayout layout = new CardLayout(); layout.setHgap(10); layout.setVgap(10); panel.setLayout(layout); JPanel buttonPanel = new JPanel(new FlowLayout()); buttonPanel.add(new JButton("OK")); buttonPanel.add(new JButton("Cancel")); JPanel textBoxPanel = new JPanel(new FlowLayout()); textBoxPanel.add(new JLabel("Name:")); textBoxPanel.add(new JTextField(20)); panel.add("Button", buttonPanel); panel.add("Text", textBoxPanel); final DefaultComboBoxModel panelName = new DefaultComboBoxModel(); panelName.addElement("Button"); panelName.addElement("Text"); final JComboBox listCombo = new JComboBox(panelName); listCombo.setSelectedIndex(0); JScrollPane listComboScrollPane = new JScrollPane(listCombo); JButton showButton = new JButton("Show"); showButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String data = ""; if (listCombo.getSelectedIndex() != -1) { CardLayout cardLayout = (CardLayout)(panel.getLayout()); cardLayout.show(panel, (String)listCombo.getItemAt(listCombo.getSelectedIndex())); } statusLabel.setText(data); } }); controlPanel.add(listComboScrollPane); controlPanel.add(showButton); controlPanel.add(panel); mainFrame.setVisible(true); } } Compile the program using the command prompt. Go to D:/ > SWING and type the following command. D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java If no error occurs, it means the compilation is successful. Run the program using the following command. D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo Verify the following output. 30 Lectures 3.5 hours Pranjal Srivastava 13 Lectures 1 hours Pranjal Srivastava 25 Lectures 4.5 hours Emenwa Global, Ejike IfeanyiChukwu 14 Lectures 1.5 hours Travis Rose 14 Lectures 1 hours Travis Rose Print Add Notes Bookmark this page
[ { "code": null, "e": 1916, "s": 1763, "text": "The class CardLayout arranges each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards." }, { "code": null, "e": 1977, "s": 1916, "text": "Following is the declaration for java.awt.CardLayout class −" }, { "code": null, "e": 2066, "s": 1977, "text": "public class CardLayout\n extends Object\n implements LayoutManager2, Serializable\n" }, { "code": null, "e": 2079, "s": 2066, "text": "CardLayout()" }, { "code": null, "e": 2133, "s": 2079, "text": "Creates a new card layout with the gaps of size zero." }, { "code": null, "e": 2164, "s": 2133, "text": "CardLayout(int hgap, int vgap)" }, { "code": null, "e": 2239, "s": 2164, "text": "Creates a new card layout with the specified horizontal and vertical gaps." }, { "code": null, "e": 2299, "s": 2239, "text": "void addLayoutComponent(Component comp, Object constraints)" }, { "code": null, "e": 2375, "s": 2299, "text": "Adds the specified component to this card layout's internal table of names." }, { "code": null, "e": 2428, "s": 2375, "text": "void addLayoutComponent(String name, Component comp)" }, { "code": null, "e": 2568, "s": 2428, "text": "If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name." }, { "code": null, "e": 2597, "s": 2568, "text": "void first(Container parent)" }, { "code": null, "e": 2639, "s": 2597, "text": "Flips to the first card of the container." }, { "code": null, "e": 2653, "s": 2639, "text": "int getHgap()" }, { "code": null, "e": 2701, "s": 2653, "text": "Gets the horizontal gap between the components." }, { "code": null, "e": 2745, "s": 2701, "text": "float getLayoutAlignmentX(Container parent)" }, { "code": null, "e": 2785, "s": 2745, "text": "Returns the alignment along the x axis." }, { "code": null, "e": 2829, "s": 2785, "text": "float getLayoutAlignmentY(Container parent)" }, { "code": null, "e": 2869, "s": 2829, "text": "Returns the alignment along the y axis." }, { "code": null, "e": 2883, "s": 2869, "text": "int getVgap()" }, { "code": null, "e": 2929, "s": 2883, "text": "Gets the vertical gap between the components." }, { "code": null, "e": 2969, "s": 2929, "text": "void invalidateLayout(Container target)" }, { "code": null, "e": 3078, "s": 2969, "text": "Invalidates the layout, indicating that if the layout manager has cached information it should be discarded." }, { "code": null, "e": 3106, "s": 3078, "text": "void last(Container parent)" }, { "code": null, "e": 3147, "s": 3106, "text": "Flips to the last card of the container." }, { "code": null, "e": 3186, "s": 3147, "text": "void layoutContainer(Container parent)" }, { "code": null, "e": 3243, "s": 3186, "text": "Lays out the specified container using this card layout." }, { "code": null, "e": 3289, "s": 3243, "text": "Dimension maximumLayoutSize(Container target)" }, { "code": null, "e": 3392, "s": 3289, "text": "Returns the maximum dimensions for this layout given the components in the specified target container." }, { "code": null, "e": 3438, "s": 3392, "text": "Dimension minimumLayoutSize(Container parent)" }, { "code": null, "e": 3491, "s": 3438, "text": "Calculates the minimum size for the specified panel." }, { "code": null, "e": 3519, "s": 3491, "text": "void next(Container parent)" }, { "code": null, "e": 3570, "s": 3519, "text": "Flips to the next card of the specified container." }, { "code": null, "e": 3618, "s": 3570, "text": "Dimension preferredLayoutSize(Container parent)" }, { "code": null, "e": 3698, "s": 3618, "text": "Determines the preferred size of the container argument using this card layout." }, { "code": null, "e": 3730, "s": 3698, "text": "void previous(Container parent)" }, { "code": null, "e": 3785, "s": 3730, "text": "Flips to the previous card of the specified container." }, { "code": null, "e": 3828, "s": 3785, "text": "void removeLayoutComponent(Component comp)" }, { "code": null, "e": 3877, "s": 3828, "text": "Removes the specified component from the layout." }, { "code": null, "e": 3900, "s": 3877, "text": "void setHgap(int hgap)" }, { "code": null, "e": 3948, "s": 3900, "text": "Sets the horizontal gap between the components." }, { "code": null, "e": 3971, "s": 3948, "text": "void setVgap(int vgap)" }, { "code": null, "e": 4017, "s": 3971, "text": "Sets the vertical gap between the components." }, { "code": null, "e": 4058, "s": 4017, "text": "void show(Container parent, String name)" }, { "code": null, "e": 4162, "s": 4058, "text": "Flips to the component that was added to this layout with the specified name, using addLayoutComponent." }, { "code": null, "e": 4180, "s": 4162, "text": "String toString()" }, { "code": null, "e": 4246, "s": 4180, "text": "Returns a string representation of the state of this card layout." }, { "code": null, "e": 4301, "s": 4246, "text": "This class inherits methods from the following class −" }, { "code": null, "e": 4318, "s": 4301, "text": "java.lang.Object" }, { "code": null, "e": 4434, "s": 4318, "text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >" }, { "code": null, "e": 4455, "s": 4434, "text": "SwingLayoutDemo.java" }, { "code": null, "e": 7442, "s": 4455, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class SwingLayoutDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n private JLabel msglabel;\n\n public SwingLayoutDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo(); \n swingLayoutDemo.showCardLayoutDemo(); \n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java SWING Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n \n headerLabel = new JLabel(\"\",JLabel.CENTER );\n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showCardLayoutDemo(){\n headerLabel.setText(\"Layout in action: CardLayout\"); \n\n final JPanel panel = new JPanel();\n panel.setBackground(Color.CYAN);\n panel.setSize(300,300);\n\n CardLayout layout = new CardLayout();\n layout.setHgap(10);\n layout.setVgap(10);\n panel.setLayout(layout); \n \n JPanel buttonPanel = new JPanel(new FlowLayout());\n buttonPanel.add(new JButton(\"OK\"));\n buttonPanel.add(new JButton(\"Cancel\")); \n\n JPanel textBoxPanel = new JPanel(new FlowLayout());\n textBoxPanel.add(new JLabel(\"Name:\"));\n textBoxPanel.add(new JTextField(20));\n\n panel.add(\"Button\", buttonPanel);\n panel.add(\"Text\", textBoxPanel);\n final DefaultComboBoxModel panelName = new DefaultComboBoxModel();\n\n panelName.addElement(\"Button\");\n panelName.addElement(\"Text\");\n final JComboBox listCombo = new JComboBox(panelName); \n \n listCombo.setSelectedIndex(0);\n JScrollPane listComboScrollPane = new JScrollPane(listCombo); \n JButton showButton = new JButton(\"Show\");\n\n showButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) { \n String data = \"\";\n if (listCombo.getSelectedIndex() != -1) { \n CardLayout cardLayout = (CardLayout)(panel.getLayout());\n cardLayout.show(panel, \n (String)listCombo.getItemAt(listCombo.getSelectedIndex())); \n } \n statusLabel.setText(data);\n }\n }); \n controlPanel.add(listComboScrollPane);\n controlPanel.add(showButton);\n controlPanel.add(panel);\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 7538, "s": 7442, "text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command." }, { "code": null, "e": 7598, "s": 7538, "text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingLayoutDemo.java\n" }, { "code": null, "e": 7703, "s": 7598, "text": "If no error occurs, it means the compilation is successful. Run the program using the following command." }, { "code": null, "e": 7757, "s": 7703, "text": "D:\\SWING>java com.tutorialspoint.gui.SwingLayoutDemo\n" }, { "code": null, "e": 7786, "s": 7757, "text": "Verify the following output." }, { "code": null, "e": 7821, "s": 7786, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7841, "s": 7821, "text": " Pranjal Srivastava" }, { "code": null, "e": 7874, "s": 7841, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 7894, "s": 7874, "text": " Pranjal Srivastava" }, { "code": null, "e": 7929, "s": 7894, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7965, "s": 7929, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8000, "s": 7965, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8013, "s": 8000, "text": " Travis Rose" }, { "code": null, "e": 8046, "s": 8013, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8059, "s": 8046, "text": " Travis Rose" }, { "code": null, "e": 8066, "s": 8059, "text": " Print" }, { "code": null, "e": 8077, "s": 8066, "text": " Add Notes" } ]
C# | Create a Stack from a collection - GeeksforGeeks
01 Feb, 2019 Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Creation of stack means the addition of item into the stack. Stack<T>.Push(Object) Method is used to Inserts an object at the top of the Stack. Properties: The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation. If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation. Stack accepts null as a valid value and allows duplicate elements. Syntax: public virtual void Push (object obj); Parameter: obj: The Object of type System.Object which is to push onto the Stack<T>. The value can be null. Below given are some examples to understand the implementation in a better way : Example 1: // C# code to Create a Stack// from a collectionusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of strings Stack<string> myStack1 = new Stack<string>(); // Inserting the elements into the Stack myStack1.Push("GeeksforGeeks"); myStack1.Push("is"); myStack1.Push("the"); myStack1.Push("best"); myStack1.Push("website"); // Displaying the count of elements // contained in the myStack1 Console.Write("Total number of elements in the Stack 1 are : "); Console.WriteLine(myStack1.Count); // Displaying the elements in Stack myStack1 foreach(string str in myStack1) { Console.WriteLine(str); } // Creating a Stack from a collection Stack<string> myStack2 = new Stack<string>(myStack1.ToArray()); // Displaying the count of elements // contained in the myStack2 Console.Write("Total number of elements in the Stack 2 are : "); Console.WriteLine(myStack2.Count); // Displaying the elements in Stack myStack2 foreach(string str in myStack2) { Console.WriteLine(str); } }} Total number of elements in the Stack 1 are : 5 website best the is GeeksforGeeks Total number of elements in the Stack 2 are : 5 GeeksforGeeks is the best website Example 2: // C# code to Create a Stack// from a collectionusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of Integers Stack<int> myStack1 = new Stack<int>(); // Inserting the elements into the Stack myStack1.Push(5); myStack1.Push(10); myStack1.Push(15); myStack1.Push(20); myStack1.Push(25); // Displaying the count of elements // contained in the myStack1 Console.Write("Total number of elements in the Stack 1 are : "); Console.WriteLine(myStack1.Count); // Displaying the elements in Stack myStack1 foreach(int i in myStack1) { Console.WriteLine(i); } // Creating a Stack from a collection Stack<int> myStack2 = new Stack<int>(myStack1.ToArray()); // Displaying the count of elements // contained in the myStack2 Console.Write("Total number of elements in the Stack 2 are : "); Console.WriteLine(myStack2.Count); // Displaying the elements in Stack myStack2 foreach(int i in myStack2) { Console.WriteLine(i); } }} Total number of elements in the Stack 1 are : 5 25 20 15 10 5 Total number of elements in the Stack 2 are : 5 5 10 15 20 25 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.push?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Generic-Namespace CSharp-Generic-Stack CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers Introduction to .NET Framework C# | Constructors Extension Method in C# C# | Class and Object C# | Abstract Classes Common Language Runtime (CLR) in C#
[ { "code": null, "e": 24029, "s": 24001, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24415, "s": 24029, "text": "Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Creation of stack means the addition of item into the stack. Stack<T>.Push(Object) Method is used to Inserts an object at the top of the Stack." }, { "code": null, "e": 24427, "s": 24415, "text": "Properties:" }, { "code": null, "e": 24605, "s": 24427, "text": "The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation." }, { "code": null, "e": 24827, "s": 24605, "text": "If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation." }, { "code": null, "e": 24894, "s": 24827, "text": "Stack accepts null as a valid value and allows duplicate elements." }, { "code": null, "e": 24902, "s": 24894, "text": "Syntax:" }, { "code": null, "e": 24941, "s": 24902, "text": "public virtual void Push (object obj);" }, { "code": null, "e": 24952, "s": 24941, "text": "Parameter:" }, { "code": null, "e": 25049, "s": 24952, "text": "obj: The Object of type System.Object which is to push onto the Stack<T>. The value can be null." }, { "code": null, "e": 25130, "s": 25049, "text": "Below given are some examples to understand the implementation in a better way :" }, { "code": null, "e": 25141, "s": 25130, "text": "Example 1:" }, { "code": "// C# code to Create a Stack// from a collectionusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of strings Stack<string> myStack1 = new Stack<string>(); // Inserting the elements into the Stack myStack1.Push(\"GeeksforGeeks\"); myStack1.Push(\"is\"); myStack1.Push(\"the\"); myStack1.Push(\"best\"); myStack1.Push(\"website\"); // Displaying the count of elements // contained in the myStack1 Console.Write(\"Total number of elements in the Stack 1 are : \"); Console.WriteLine(myStack1.Count); // Displaying the elements in Stack myStack1 foreach(string str in myStack1) { Console.WriteLine(str); } // Creating a Stack from a collection Stack<string> myStack2 = new Stack<string>(myStack1.ToArray()); // Displaying the count of elements // contained in the myStack2 Console.Write(\"Total number of elements in the Stack 2 are : \"); Console.WriteLine(myStack2.Count); // Displaying the elements in Stack myStack2 foreach(string str in myStack2) { Console.WriteLine(str); } }}", "e": 26411, "s": 25141, "text": null }, { "code": null, "e": 26576, "s": 26411, "text": "Total number of elements in the Stack 1 are : 5\nwebsite\nbest\nthe\nis\nGeeksforGeeks\nTotal number of elements in the Stack 2 are : 5\nGeeksforGeeks\nis\nthe\nbest\nwebsite\n" }, { "code": null, "e": 26587, "s": 26576, "text": "Example 2:" }, { "code": "// C# code to Create a Stack// from a collectionusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of Integers Stack<int> myStack1 = new Stack<int>(); // Inserting the elements into the Stack myStack1.Push(5); myStack1.Push(10); myStack1.Push(15); myStack1.Push(20); myStack1.Push(25); // Displaying the count of elements // contained in the myStack1 Console.Write(\"Total number of elements in the Stack 1 are : \"); Console.WriteLine(myStack1.Count); // Displaying the elements in Stack myStack1 foreach(int i in myStack1) { Console.WriteLine(i); } // Creating a Stack from a collection Stack<int> myStack2 = new Stack<int>(myStack1.ToArray()); // Displaying the count of elements // contained in the myStack2 Console.Write(\"Total number of elements in the Stack 2 are : \"); Console.WriteLine(myStack2.Count); // Displaying the elements in Stack myStack2 foreach(int i in myStack2) { Console.WriteLine(i); } }}", "e": 27802, "s": 26587, "text": null }, { "code": null, "e": 27927, "s": 27802, "text": "Total number of elements in the Stack 1 are : 5\n25\n20\n15\n10\n5\nTotal number of elements in the Stack 2 are : 5\n5\n10\n15\n20\n25\n" }, { "code": null, "e": 28036, "s": 27927, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.push?view=netframework-4.7.2" }, { "code": null, "e": 28065, "s": 28036, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 28090, "s": 28065, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 28111, "s": 28090, "text": "CSharp-Generic-Stack" }, { "code": null, "e": 28125, "s": 28111, "text": "CSharp-method" }, { "code": null, "e": 28128, "s": 28125, "text": "C#" }, { "code": null, "e": 28226, "s": 28128, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28235, "s": 28226, "text": "Comments" }, { "code": null, "e": 28248, "s": 28235, "text": "Old Comments" }, { "code": null, "e": 28271, "s": 28248, "text": "C# | Method Overriding" }, { "code": null, "e": 28317, "s": 28271, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28332, "s": 28317, "text": "C# | Delegates" }, { "code": null, "e": 28372, "s": 28332, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28403, "s": 28372, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28421, "s": 28403, "text": "C# | Constructors" }, { "code": null, "e": 28444, "s": 28421, "text": "Extension Method in C#" }, { "code": null, "e": 28466, "s": 28444, "text": "C# | Class and Object" }, { "code": null, "e": 28488, "s": 28466, "text": "C# | Abstract Classes" } ]
How to create minor ticks for a polar plot in matplotlib?
To create minor ticks for a polar plot in matplotlib, we can take the following steps Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Create r (radius) and theta data points using numpy. Create r (radius) and theta data points using numpy. Add a subplot to the current figure. Add a subplot to the current figure. Iterate the points between 0 to 360 with step=10 and plot them to get the ticks. Iterate the points between 0 to 360 with step=10 and plot them to get the ticks. To display the figure, use Show() method. To display the figure, use Show() method. import numpy as np import matplotlib.pyplot as plt # Set the figure size plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True # radius and theta for the polar plot r = np.arange(0, 5, 0.1) theta = 2 * np.pi * r # Add a subplot ax = plt.subplot(111, projection='polar') tick = [ax.get_rmax(), ax.get_rmax() * 0.97] # Iterate the points between 0 to 360 with step=10 for t in np.deg2rad(np.arange(0, 360, 10)): ax.plot([t, t], tick, lw=1, color="red") # Display the plot plt.show() It will produce the following output −
[ { "code": null, "e": 1148, "s": 1062, "text": "To create minor ticks for a polar plot in matplotlib, we can take the following steps" }, { "code": null, "e": 1224, "s": 1148, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1300, "s": 1224, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1353, "s": 1300, "text": "Create r (radius) and theta data points using numpy." }, { "code": null, "e": 1406, "s": 1353, "text": "Create r (radius) and theta data points using numpy." }, { "code": null, "e": 1443, "s": 1406, "text": "Add a subplot to the current figure." }, { "code": null, "e": 1480, "s": 1443, "text": "Add a subplot to the current figure." }, { "code": null, "e": 1561, "s": 1480, "text": "Iterate the points between 0 to 360 with step=10 and plot them to get the ticks." }, { "code": null, "e": 1642, "s": 1561, "text": "Iterate the points between 0 to 360 with step=10 and plot them to get the ticks." }, { "code": null, "e": 1684, "s": 1642, "text": "To display the figure, use Show() method." }, { "code": null, "e": 1726, "s": 1684, "text": "To display the figure, use Show() method." }, { "code": null, "e": 2251, "s": 1726, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\n# Set the figure size\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\n# radius and theta for the polar plot\nr = np.arange(0, 5, 0.1)\ntheta = 2 * np.pi * r\n\n# Add a subplot\nax = plt.subplot(111, projection='polar')\n\ntick = [ax.get_rmax(), ax.get_rmax() * 0.97]\n\n# Iterate the points between 0 to 360 with step=10\nfor t in np.deg2rad(np.arange(0, 360, 10)):\n ax.plot([t, t], tick, lw=1, color=\"red\")\n\n# Display the plot\nplt.show()\n" }, { "code": null, "e": 2290, "s": 2251, "text": "It will produce the following output −" } ]
Remove the child node of a specific element in JavaScript?
To remove the child node of a list javascript has provided removeChild() method. Using this method we can remove any list item using its index position. Let's discuss it in a nutshell. node.removeChild(node); In the following example, there are 3 elements in the provided list but after removing a child there are only two elements in the list and they were displayed in the output. Live Demo <html> <body> <ul id = "list"><li>Tesla</li><li>Spacex</li><li>Solarcity</li></ul> <script> var list = document.getElementById("list"); list.removeChild(list.childNodes[1]); </script> </body> </html> Tesla Solarcity In the following example, there are 3 elements in the provided list but after removing the first child using method removeChild() the other remaining two elements left were displayed as shown in the output. Live Demo <html> <body> <ul id = "list"><li>Tesla</li><li>Spacex</li><li>Solarcity</li></ul> <script> var list = document.getElementById("list"); list.removeChild(list.childNodes[0]); </script> </body> </html> Spacex Solarcity
[ { "code": null, "e": 1247, "s": 1062, "text": "To remove the child node of a list javascript has provided removeChild() method. Using this method we can remove any list item using its index position. Let's discuss it in a nutshell." }, { "code": null, "e": 1271, "s": 1247, "text": "node.removeChild(node);" }, { "code": null, "e": 1447, "s": 1271, "text": "In the following example, there are 3 elements in the provided list but after removing a child there are only two elements in the list and they were displayed in the output. " }, { "code": null, "e": 1457, "s": 1447, "text": "Live Demo" }, { "code": null, "e": 1663, "s": 1457, "text": "<html>\n<body>\n<ul id = \"list\"><li>Tesla</li><li>Spacex</li><li>Solarcity</li></ul>\n<script>\n var list = document.getElementById(\"list\");\n list.removeChild(list.childNodes[1]);\n</script>\n</body>\n</html>" }, { "code": null, "e": 1679, "s": 1663, "text": "Tesla\nSolarcity" }, { "code": null, "e": 1888, "s": 1679, "text": "In the following example, there are 3 elements in the provided list but after removing the first child using method removeChild() the other remaining two elements left were displayed as shown in the output. " }, { "code": null, "e": 1898, "s": 1888, "text": "Live Demo" }, { "code": null, "e": 2104, "s": 1898, "text": "<html>\n<body>\n<ul id = \"list\"><li>Tesla</li><li>Spacex</li><li>Solarcity</li></ul>\n<script>\n var list = document.getElementById(\"list\");\n list.removeChild(list.childNodes[0]);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2121, "s": 2104, "text": "Spacex\nSolarcity" } ]
Remove and add new HTML Tags with JavaScript?
To remove and add new HTML tags, use the concept of hide() and show(). Let’s say the following are our buttons − <button type="submit" id="hide">Click Me To hide above content </button> <button type="submit" id="show">Click Me To show above content </button> To remove and add tags on button clicks, use hie() and show() − $(document).ready(function(){ $("#hide").click(function(){ $("h1").hide(); }); $("#show").click(function(){ $("h1").show(); }); }); 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"> <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> <h1>Test JavaScript</h1> <button type="submit" id="hide">Click Me To hide above content </button> <button type="submit" id="show">Click Me To show above content </button> <script> $(document).ready(function(){ $("#hide").click(function(){ $("h1").hide(); }); $("#show").click(function(){ $("h1").show(); }); }); </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 − Case 1 When you click on the button “Click Me To hide above content”, you will get the following output. Case 2 When you click on the button “Click Me To show above content”, you will get the following output.
[ { "code": null, "e": 1133, "s": 1062, "text": "To remove and add new HTML tags, use the concept of hide() and show()." }, { "code": null, "e": 1175, "s": 1133, "text": "Let’s say the following are our buttons −" }, { "code": null, "e": 1321, "s": 1175, "text": "<button type=\"submit\" id=\"hide\">Click Me To hide above content </button>\n<button type=\"submit\" id=\"show\">Click Me To show above content </button>" }, { "code": null, "e": 1385, "s": 1321, "text": "To remove and add tags on button clicks, use hie() and show() −" }, { "code": null, "e": 1541, "s": 1385, "text": "$(document).ready(function(){\n $(\"#hide\").click(function(){\n $(\"h1\").hide();\n });\n $(\"#show\").click(function(){\n $(\"h1\").show();\n });\n});" }, { "code": null, "e": 1552, "s": 1541, "text": " Live Demo" }, { "code": null, "e": 2331, "s": 1552, "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\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\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<h1>Test JavaScript</h1>\n<button type=\"submit\" id=\"hide\">Click Me To hide above content\n</button>\n<button type=\"submit\" id=\"show\">Click Me To show above content\n</button>\n<script>\n $(document).ready(function(){\n $(\"#hide\").click(function(){\n $(\"h1\").hide();\n });\n $(\"#show\").click(function(){\n $(\"h1\").show();\n });\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2493, "s": 2331, "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": 2534, "s": 2493, "text": "This will produce the following output −" }, { "code": null, "e": 2541, "s": 2534, "text": "Case 1" }, { "code": null, "e": 2639, "s": 2541, "text": "When you click on the button “Click Me To hide above content”, you will get the following output." }, { "code": null, "e": 2646, "s": 2639, "text": "Case 2" }, { "code": null, "e": 2744, "s": 2646, "text": "When you click on the button “Click Me To show above content”, you will get the following\noutput." } ]
C# | Join() Method | Set - 1 - GeeksforGeeks
05 Nov, 2019 In C#, Join() is a string method. This method is used to concatenates the members of a collection or the elements of the specified array, using the specified separator between each member or element. This method can be overloaded by passing different parameters to it. There are total 5 methods in the overload list of the Join() method in which 3 are discussed in this article and remaining 2 will be discussed in C# | Join() Method | Set – 2. String.Join(String, Obj [ ]) String.Join(String, string [ ]) String.Join(String, string [ ], int pos1, int pos2) String.Join(String, IEnumerable<String>) String.Join<T>(String, IEnumerable<T>) This method is used to concatenate the elements of an object array with the help of a separator between each element of the object array. Syntax: public static string Join(string separator, params obj[] array) Parameters: This method takes two parameters, One of them is the separator of the type System.Sting which is used to define a separator according to the user’s choice. Another parameter is an array of type System.Object[] which contains the elements to be concatenated. Return Type: The return type of this method is System.String. Exception: This method can give ArgumentNullException if the array is null. Example: In the below code, first an array of objects is created and then it is passed to the join method along with the separator to be used, here ‘, ‘ comma separator is used and after method’s return, the string is taken as the output. // C# program to demonstrate the// Join(String, Obj [ ]) methodusing System;namespace ConsoleApplication1 { class Geeks { // Main Method static void Main(string[] args) { // Creating an object array // Here, It is consist of four // elements only object[] array = {"Hello", "Geeks", 12345, 786}; // Using Join method // Here separator is ', '( comma ) string s1 = string.Join(", ", array); // Finally after joining process gets over // Getting the output of value of string s1 Console.WriteLine("Value of string s1 is " + s1); }}} Output: Value of string s1 is Hello, Geeks, 12345, 786 This method is used to concatenate the elements of a String array with the help of a user-specified separator between each element of the string array. Syntax: public static string Join(string separator, params string[ ] array) Parameters: This method takes two parameters, One of them is the separator of the type System.Sting which is used to define a separator according to the user’s choice. Another parameter is an array of type System.String[] which contains the elements to be concatenated. Return Type: The return type of this method is System.String. Exception: This method can give ArgumentNullException if the array is null. Example:In below code, first an array of strings is created and is passed to the join method along with the separator to be used, here ‘/’ slash separator is used and after method’s return, the string is print as the output. // C# program to demonstrate the// Join(String, String [])using System;namespace ConsoleApplication2 { class Geeks { // Main Method static void Main(string[] args) { // Creating a string array // Here It contains five // elements only string[] array = {"hello", " World ", "Geeks", " are ", " here " }; // Using Join method // Here separator used is '/'( slash ) string s1 = string.Join("/", array); // Finally after join method // Getting the output of value of string s1 Console.WriteLine("Value of string s1 is " + s1); }}} Output: Value of string s1 is hello/ World /Geeks/ are / here This method is used to concatenate the elements of a String array between the specified positions with the help of a user-defined separator between each element of the array. Syntax: public static string Join(string separator, params string[] array, int pos1, int pos2) Parameters: This method takes four parameters, first one is the separator of the type System.Sting which is used to define a separator according to the user’s choice. Second parameter is an array of type System.String[] which contains the elements to be concatenated. Third parameter is pos1 of type System.Int32 which is the first element in array to be used and important point to remember about this parameter is that it used zero-based index. Fourth parameter is pos2 of type System.Int32 which is used to specify the number of elements of array to be used and it always starts from 1 i.e it counts the pos1’value as its first element. Return Type: The return type of this method is System.String. Also it can return of type String.Empty if value of pos2 is zero. Exceptions: This method can give ArgumentNullException if the array is null. ArgumentOutOfRangeException can be given if the pos1 or pos2 is less than zero or pos1 + pos2 is greater than the number of elements in array and also this method can give OutOfMemoryException. Example: In below code, an array of strings is created and suppose that user wants to join the strings from position index 2 and want to cover five elements. // C# program to demonstrate the// Join(String, string [ ], int // pos1, int pos2) methodusing System;namespace ConsoleApplication3 { class Geeks { // Main Method static void Main(string[] args) { // Creating a string array string[] array = {"lazy", "dog", "jumps", "Over", "the", "Lazy", "fox" }; // Using Join method // Here separator used is '-'( hiphen ) // from index 2 and covers upto 5 // elements from index 2 string s1 = string.Join("-", array, 2, 5); // Finally after joining process gets over // Getting the output of value of string s1 Console.WriteLine("Value of string is " + s1); }}} Output: Value of string is jumps-Over-the-Lazy-fox References: https://msdn.microsoft.com/en-us/library/tk0xe5h0(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/57a79xd0(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/tk0xe5h0(v=vs.110).aspx Akanksha_Rai CSharp-method CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers Introduction to .NET Framework C# | Constructors Extension Method in C# C# | Class and Object C# | Abstract Classes Common Language Runtime (CLR) in C#
[ { "code": null, "e": 24051, "s": 24023, "text": "\n05 Nov, 2019" }, { "code": null, "e": 24496, "s": 24051, "text": "In C#, Join() is a string method. This method is used to concatenates the members of a collection or the elements of the specified array, using the specified separator between each member or element. This method can be overloaded by passing different parameters to it. There are total 5 methods in the overload list of the Join() method in which 3 are discussed in this article and remaining 2 will be discussed in C# | Join() Method | Set – 2." }, { "code": null, "e": 24525, "s": 24496, "text": "String.Join(String, Obj [ ])" }, { "code": null, "e": 24557, "s": 24525, "text": "String.Join(String, string [ ])" }, { "code": null, "e": 24609, "s": 24557, "text": "String.Join(String, string [ ], int pos1, int pos2)" }, { "code": null, "e": 24650, "s": 24609, "text": "String.Join(String, IEnumerable<String>)" }, { "code": null, "e": 24689, "s": 24650, "text": "String.Join<T>(String, IEnumerable<T>)" }, { "code": null, "e": 24827, "s": 24689, "text": "This method is used to concatenate the elements of an object array with the help of a separator between each element of the object array." }, { "code": null, "e": 24835, "s": 24827, "text": "Syntax:" }, { "code": null, "e": 24900, "s": 24835, "text": "public static string Join(string separator, params obj[] array)\n" }, { "code": null, "e": 25170, "s": 24900, "text": "Parameters: This method takes two parameters, One of them is the separator of the type System.Sting which is used to define a separator according to the user’s choice. Another parameter is an array of type System.Object[] which contains the elements to be concatenated." }, { "code": null, "e": 25232, "s": 25170, "text": "Return Type: The return type of this method is System.String." }, { "code": null, "e": 25308, "s": 25232, "text": "Exception: This method can give ArgumentNullException if the array is null." }, { "code": null, "e": 25547, "s": 25308, "text": "Example: In the below code, first an array of objects is created and then it is passed to the join method along with the separator to be used, here ‘, ‘ comma separator is used and after method’s return, the string is taken as the output." }, { "code": "// C# program to demonstrate the// Join(String, Obj [ ]) methodusing System;namespace ConsoleApplication1 { class Geeks { // Main Method static void Main(string[] args) { // Creating an object array // Here, It is consist of four // elements only object[] array = {\"Hello\", \"Geeks\", 12345, 786}; // Using Join method // Here separator is ', '( comma ) string s1 = string.Join(\", \", array); // Finally after joining process gets over // Getting the output of value of string s1 Console.WriteLine(\"Value of string s1 is \" + s1); }}}", "e": 26175, "s": 25547, "text": null }, { "code": null, "e": 26183, "s": 26175, "text": "Output:" }, { "code": null, "e": 26231, "s": 26183, "text": "Value of string s1 is Hello, Geeks, 12345, 786" }, { "code": null, "e": 26383, "s": 26231, "text": "This method is used to concatenate the elements of a String array with the help of a user-specified separator between each element of the string array." }, { "code": null, "e": 26391, "s": 26383, "text": "Syntax:" }, { "code": null, "e": 26460, "s": 26391, "text": "public static string Join(string separator, params string[ ] array)\n" }, { "code": null, "e": 26730, "s": 26460, "text": "Parameters: This method takes two parameters, One of them is the separator of the type System.Sting which is used to define a separator according to the user’s choice. Another parameter is an array of type System.String[] which contains the elements to be concatenated." }, { "code": null, "e": 26792, "s": 26730, "text": "Return Type: The return type of this method is System.String." }, { "code": null, "e": 26868, "s": 26792, "text": "Exception: This method can give ArgumentNullException if the array is null." }, { "code": null, "e": 27093, "s": 26868, "text": "Example:In below code, first an array of strings is created and is passed to the join method along with the separator to be used, here ‘/’ slash separator is used and after method’s return, the string is print as the output." }, { "code": "// C# program to demonstrate the// Join(String, String [])using System;namespace ConsoleApplication2 { class Geeks { // Main Method static void Main(string[] args) { // Creating a string array // Here It contains five // elements only string[] array = {\"hello\", \" World \", \"Geeks\", \" are \", \" here \" }; // Using Join method // Here separator used is '/'( slash ) string s1 = string.Join(\"/\", array); // Finally after join method // Getting the output of value of string s1 Console.WriteLine(\"Value of string s1 is \" + s1); }}}", "e": 27734, "s": 27093, "text": null }, { "code": null, "e": 27742, "s": 27734, "text": "Output:" }, { "code": null, "e": 27799, "s": 27742, "text": "Value of string s1 is hello/ World /Geeks/ are / here " }, { "code": null, "e": 27974, "s": 27799, "text": "This method is used to concatenate the elements of a String array between the specified positions with the help of a user-defined separator between each element of the array." }, { "code": null, "e": 27982, "s": 27974, "text": "Syntax:" }, { "code": null, "e": 28070, "s": 27982, "text": "public static string Join(string separator, params string[] array, int pos1, int pos2)\n" }, { "code": null, "e": 28710, "s": 28070, "text": "Parameters: This method takes four parameters, first one is the separator of the type System.Sting which is used to define a separator according to the user’s choice. Second parameter is an array of type System.String[] which contains the elements to be concatenated. Third parameter is pos1 of type System.Int32 which is the first element in array to be used and important point to remember about this parameter is that it used zero-based index. Fourth parameter is pos2 of type System.Int32 which is used to specify the number of elements of array to be used and it always starts from 1 i.e it counts the pos1’value as its first element." }, { "code": null, "e": 28838, "s": 28710, "text": "Return Type: The return type of this method is System.String. Also it can return of type String.Empty if value of pos2 is zero." }, { "code": null, "e": 29109, "s": 28838, "text": "Exceptions: This method can give ArgumentNullException if the array is null. ArgumentOutOfRangeException can be given if the pos1 or pos2 is less than zero or pos1 + pos2 is greater than the number of elements in array and also this method can give OutOfMemoryException." }, { "code": null, "e": 29267, "s": 29109, "text": "Example: In below code, an array of strings is created and suppose that user wants to join the strings from position index 2 and want to cover five elements." }, { "code": "// C# program to demonstrate the// Join(String, string [ ], int // pos1, int pos2) methodusing System;namespace ConsoleApplication3 { class Geeks { // Main Method static void Main(string[] args) { // Creating a string array string[] array = {\"lazy\", \"dog\", \"jumps\", \"Over\", \"the\", \"Lazy\", \"fox\" }; // Using Join method // Here separator used is '-'( hiphen ) // from index 2 and covers upto 5 // elements from index 2 string s1 = string.Join(\"-\", array, 2, 5); // Finally after joining process gets over // Getting the output of value of string s1 Console.WriteLine(\"Value of string is \" + s1); }}}", "e": 30005, "s": 29267, "text": null }, { "code": null, "e": 30013, "s": 30005, "text": "Output:" }, { "code": null, "e": 30056, "s": 30013, "text": "Value of string is jumps-Over-the-Lazy-fox" }, { "code": null, "e": 30068, "s": 30056, "text": "References:" }, { "code": null, "e": 30133, "s": 30068, "text": "https://msdn.microsoft.com/en-us/library/tk0xe5h0(v=vs.110).aspx" }, { "code": null, "e": 30198, "s": 30133, "text": "https://msdn.microsoft.com/en-us/library/57a79xd0(v=vs.110).aspx" }, { "code": null, "e": 30263, "s": 30198, "text": "https://msdn.microsoft.com/en-us/library/tk0xe5h0(v=vs.110).aspx" }, { "code": null, "e": 30276, "s": 30263, "text": "Akanksha_Rai" }, { "code": null, "e": 30290, "s": 30276, "text": "CSharp-method" }, { "code": null, "e": 30304, "s": 30290, "text": "CSharp-string" }, { "code": null, "e": 30307, "s": 30304, "text": "C#" }, { "code": null, "e": 30405, "s": 30307, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30414, "s": 30405, "text": "Comments" }, { "code": null, "e": 30427, "s": 30414, "text": "Old Comments" }, { "code": null, "e": 30450, "s": 30427, "text": "C# | Method Overriding" }, { "code": null, "e": 30496, "s": 30450, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 30511, "s": 30496, "text": "C# | Delegates" }, { "code": null, "e": 30551, "s": 30511, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 30582, "s": 30551, "text": "Introduction to .NET Framework" }, { "code": null, "e": 30600, "s": 30582, "text": "C# | Constructors" }, { "code": null, "e": 30623, "s": 30600, "text": "Extension Method in C#" }, { "code": null, "e": 30645, "s": 30623, "text": "C# | Class and Object" }, { "code": null, "e": 30667, "s": 30645, "text": "C# | Abstract Classes" } ]
Sum of length | Practice | GeeksforGeeks
Given an array. Calculate the sum of lengths of contiguous subarrays having all distinct elements. Example 1: Input: N=3 arr[] = { 1,2,3 } Output: 10 Explanation: {1, 2, 3} is a subarray of length 3 with distinct elements. Total length of length three = 3. {1, 2}, {2, 3} are 2 subarray of length 2 with distinct elements. Total length of lengths two = 2 + 2 = 4 {1}, {2}, {3} are 3 subarrays of length 1 with distinct element. Total lengths of length one = 1 + 1 + 1 = 3 Sum of lengths = 3 + 4 + 3 = 10 Example 2: Input: N=1 arr[] = { 1 } Output: 1 Explanation: {1} is the only subarray with distinct elements of length 1. Your Task: You don't need to read input or print anything. Your task is to complete the function sumoflength() that takes array arr and integer N as input parameters and returns the sum of lengths of contiguous subarrays having all distinct elements. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 ≤ N ≤ 106 +1 sejalxz4 months ago Here's my solution using sliding window.TC : O(N) SC : O(N) class Solution{ public: int sumoflength(int arr[], int size) { int left=0, sum = 0, n =0; unordered_map<int,int>mem; for(int right = 0; right < size ; right++){ int currentVal = arr[right]; if(mem.find(currentVal) != mem.end()){ int index = mem[currentVal]; while(left <= right && left <= index){ int discard = arr[left]; mem[discard]--; if(mem[discard]==0) mem.erase(discard); left++; } mem[currentVal] = right; } else{ mem[currentVal]=right; } n = right - left + 1; sum += ((n*(n+1))/2); } return sum; } }; 0 imranwahid4 months ago Easy C++ solution using sliding window technique The basic idea is to grow the window until we are not getting a visited character and while growing consider every element as end point of a subarray and add the lengths of the subarray ending at that element. +1 negilokesh3477 months ago why have u m guys marked this as a easy level problem 0 Shivam Bhardwaj2 years ago Shivam Bhardwaj Easy c++ solutionthanks me laterhttps://ide.geeksforgeeks.o... 0 JAHANVI SINGH2 years ago JAHANVI SINGH https://ide.geeksforgeeks.o... Java solution 0 SHUBHAM TANDAN2 years ago SHUBHAM TANDAN for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) counter = 0 for i in range(n): h = {} for j in range(i,n): if arr[j] not in h: h[arr[j]] = 1 counter += len(h) else: break print(counter) 0 Ritik Sunita Jain2 years ago Ritik Sunita Jain https://uploads.disquscdn.c... O(n). 0.01 solution fastest with pre computation 0 Kamal Meena2 years ago Kamal Meena Python solution Using set Ex.Time: 0.02 sechttps://ide.geeksforgeeks.o... 0 Nikhil Pachkor2 years ago Nikhil Pachkor Can anyone suggest how to improve time complexity of the following code:for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) count=0 for i in range(n+1): for j in range(i+1,n+1,1): p=a[i:j] if len(set(p))==len(p): count+=len(p) print(count) 0 ultrainstinct2 years ago ultrainstinct Easy python solution: https://ide.geeksforgeeks.o... 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": 339, "s": 238, "text": "Given an array. Calculate the sum of lengths of contiguous subarrays having all distinct elements.\n " }, { "code": null, "e": 350, "s": 339, "text": "Example 1:" }, { "code": null, "e": 749, "s": 350, "text": "Input:\nN=3\narr[] = { 1,2,3 }\nOutput: 10\nExplanation: \n{1, 2, 3} is a subarray of length 3 with \ndistinct elements. Total length of length\nthree = 3. {1, 2}, {2, 3} are 2 subarray \nof length 2 with distinct elements. Total \nlength of lengths two = 2 + 2 = 4\n{1}, {2}, {3} are 3 subarrays of length 1\nwith distinct element. Total lengths of \nlength one = 1 + 1 + 1 = 3\nSum of lengths = 3 + 4 + 3 = 10" }, { "code": null, "e": 760, "s": 749, "text": "Example 2:" }, { "code": null, "e": 874, "s": 760, "text": "Input:\nN=1\narr[] = { 1 }\nOutput: 1\nExplanation: \n{1} is the only subarray with distinct \nelements of length 1. \n" }, { "code": null, "e": 1126, "s": 874, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function sumoflength() that takes array arr and integer N as input parameters and returns the sum of lengths of contiguous subarrays having all distinct elements." }, { "code": null, "e": 1190, "s": 1126, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 1217, "s": 1192, "text": "Constraints:\n1 ≤ N ≤ 106" }, { "code": null, "e": 1220, "s": 1217, "text": "+1" }, { "code": null, "e": 1240, "s": 1220, "text": "sejalxz4 months ago" }, { "code": null, "e": 1290, "s": 1240, "text": "Here's my solution using sliding window.TC : O(N)" }, { "code": null, "e": 1300, "s": 1290, "text": "SC : O(N)" }, { "code": null, "e": 2182, "s": 1302, "text": "class Solution{\n public:\n int sumoflength(int arr[], int size)\n {\n int left=0, sum = 0, n =0;\n unordered_map<int,int>mem;\n \n for(int right = 0; right < size ; right++){\n int currentVal = arr[right];\n \n if(mem.find(currentVal) != mem.end()){\n int index = mem[currentVal];\n while(left <= right && left <= index){\n int discard = arr[left];\n mem[discard]--;\n \n if(mem[discard]==0)\n mem.erase(discard);\n \n left++;\n }\n mem[currentVal] = right;\n }\n else{\n mem[currentVal]=right;\n }\n n = right - left + 1;\n sum += ((n*(n+1))/2);\n }\n \n return sum;\n }\n}; " }, { "code": null, "e": 2184, "s": 2182, "text": "0" }, { "code": null, "e": 2207, "s": 2184, "text": "imranwahid4 months ago" }, { "code": null, "e": 2256, "s": 2207, "text": "Easy C++ solution using sliding window technique" }, { "code": null, "e": 2468, "s": 2258, "text": "The basic idea is to grow the window until we are not getting a visited character and while growing consider every element as end point of a subarray and add the lengths of the subarray ending at that element." }, { "code": null, "e": 2471, "s": 2468, "text": "+1" }, { "code": null, "e": 2497, "s": 2471, "text": "negilokesh3477 months ago" }, { "code": null, "e": 2551, "s": 2497, "text": "why have u m guys marked this as a easy level problem" }, { "code": null, "e": 2553, "s": 2551, "text": "0" }, { "code": null, "e": 2580, "s": 2553, "text": "Shivam Bhardwaj2 years ago" }, { "code": null, "e": 2596, "s": 2580, "text": "Shivam Bhardwaj" }, { "code": null, "e": 2659, "s": 2596, "text": "Easy c++ solutionthanks me laterhttps://ide.geeksforgeeks.o..." }, { "code": null, "e": 2661, "s": 2659, "text": "0" }, { "code": null, "e": 2686, "s": 2661, "text": "JAHANVI SINGH2 years ago" }, { "code": null, "e": 2700, "s": 2686, "text": "JAHANVI SINGH" }, { "code": null, "e": 2745, "s": 2700, "text": "https://ide.geeksforgeeks.o... Java solution" }, { "code": null, "e": 2747, "s": 2745, "text": "0" }, { "code": null, "e": 2773, "s": 2747, "text": "SHUBHAM TANDAN2 years ago" }, { "code": null, "e": 2788, "s": 2773, "text": "SHUBHAM TANDAN" }, { "code": null, "e": 2879, "s": 2788, "text": "for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split()))" }, { "code": null, "e": 3090, "s": 2879, "text": " counter = 0 for i in range(n): h = {} for j in range(i,n): if arr[j] not in h: h[arr[j]] = 1 counter += len(h) else: break" }, { "code": null, "e": 3109, "s": 3090, "text": " print(counter)" }, { "code": null, "e": 3111, "s": 3109, "text": "0" }, { "code": null, "e": 3140, "s": 3111, "text": "Ritik Sunita Jain2 years ago" }, { "code": null, "e": 3158, "s": 3140, "text": "Ritik Sunita Jain" }, { "code": null, "e": 3189, "s": 3158, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 3239, "s": 3189, "text": "O(n). 0.01 solution fastest with pre computation" }, { "code": null, "e": 3241, "s": 3239, "text": "0" }, { "code": null, "e": 3264, "s": 3241, "text": "Kamal Meena2 years ago" }, { "code": null, "e": 3276, "s": 3264, "text": "Kamal Meena" }, { "code": null, "e": 3350, "s": 3276, "text": "Python solution Using set Ex.Time: 0.02 sechttps://ide.geeksforgeeks.o..." }, { "code": null, "e": 3352, "s": 3350, "text": "0" }, { "code": null, "e": 3378, "s": 3352, "text": "Nikhil Pachkor2 years ago" }, { "code": null, "e": 3393, "s": 3378, "text": "Nikhil Pachkor" }, { "code": null, "e": 3718, "s": 3393, "text": "Can anyone suggest how to improve time complexity of the following code:for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) count=0 for i in range(n+1): for j in range(i+1,n+1,1): p=a[i:j] if len(set(p))==len(p): count+=len(p) print(count)" }, { "code": null, "e": 3720, "s": 3718, "text": "0" }, { "code": null, "e": 3745, "s": 3720, "text": "ultrainstinct2 years ago" }, { "code": null, "e": 3759, "s": 3745, "text": "ultrainstinct" }, { "code": null, "e": 3781, "s": 3759, "text": "Easy python solution:" }, { "code": null, "e": 3812, "s": 3781, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 3958, "s": 3812, "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": 3994, "s": 3958, "text": " Login to access your submissions. " }, { "code": null, "e": 4004, "s": 3994, "text": "\nProblem\n" }, { "code": null, "e": 4014, "s": 4004, "text": "\nContest\n" }, { "code": null, "e": 4077, "s": 4014, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4225, "s": 4077, "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": 4433, "s": 4225, "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": 4539, "s": 4433, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Speech Emotion Recognition with Convolutional Neural Network | by Reza Chu | Towards Data Science
Recognizing human emotion has always been a fascinating task for data scientists. Lately, I am working on an experimental Speech Emotion Recognition (SER) project to explore its potential. I selected the most starred SER repository from GitHub to be the backbone of my project. Before we walk through the project, it is good to know the major bottleneck of Speech Emotion Recognition. Emotions are subjective, people would interpret it differently. It is hard to define the notion of emotions. Annotating an audio recording is challenging. Should we label a single word, sentence or a whole conversation? How many emotions should we define to recognize? Collecting data is complex. There are lots of audio data can be achieved from films or news. However, both of them are biased since news reporting has to be neutral and actors’ emotions are imitated. It is hard to look for neutral audio recording without any bias. Labeling data require high human and time cost. Unlike drawing a bounding box on an image, it requires trained personnel to listen to the whole audio recording, analysis it and give an annotation. The annotation result has to be evaluated by multiple individuals due to its subjectivity. Using Convolutional Neural Network to recognize emotion from the audio recording. And the repository owner does not provide any paper reference. These are two datasets originally made use in the repository RAVDESS and SAVEE, and I only adopted RAVDESS in my model. In the RAVDESS, there are two types of data: speech and song. Data Set: The Ryerson Audio-Visual Database of Emotional Speech and Song (RAVDESS) 12 Actors & 12 Actresses recorded speech and song version respectively. Actor no.18 does not have song version data. Emotion Disgust, Neutral and Surprised are not included in the song version data. Here is the emotion class distribution bar chart. When we do Speech Recognition tasks, MFCCs is the state-of-the-art feature since it was invented in the 1980s. This shape determines what sound comes out. If we can determine the shape accurately, this should give us an accurate representation of the phoneme being produced. The shape of the vocal tract manifests itself in the envelope of the short time power spectrum, and the job of MFCCs is to accurately represent this envelope. — Noted from: MFCC tutorial We would use MFCCs to be our input feature. If you want a thorough understanding of MFCCs, here is a great tutorial for you. Loading audio data and converting it to MFCCs format can be easily done by the Python package librosa. The author developed the CNN model with Keras and constructed with 7 layers — 6 Conv1D layers followed by a Dense layer. model = Sequential()model.add(Conv1D(256, 5,padding='same', input_shape=(216,1))) #1model.add(Activation('relu'))model.add(Conv1D(128, 5,padding='same')) #2model.add(Activation('relu'))model.add(Dropout(0.1))model.add(MaxPooling1D(pool_size=(8)))model.add(Conv1D(128, 5,padding='same')) #3model.add(Activation('relu'))#model.add(Conv1D(128, 5,padding='same')) #4#model.add(Activation('relu'))#model.add(Conv1D(128, 5,padding='same')) #5#model.add(Activation('relu'))#model.add(Dropout(0.2))model.add(Conv1D(128, 5,padding='same')) #6model.add(Activation('relu'))model.add(Flatten())model.add(Dense(10)) #7model.add(Activation('softmax'))opt = keras.optimizers.rmsprop(lr=0.00001, decay=1e-6) The author commented layer #4 and #5 in the latest notebook (18 Sep 2018 Update) and the model weight file does not fit the network provided, thus, I cannot load the weight provide and replicate its result 72% Testing Accuracy. The model only simply trained with batch_size=16 and 700 epochs without any learning rate schedule, etc. # Compile Modelmodel.compile(loss='categorical_crossentropy', optimizer=opt,metrics=['accuracy'])# Fit Modelcnnhistory=model.fit(x_traincnn, y_train, batch_size=16, epochs=700, validation_data=(x_testcnn, y_test)) Its loss function is categorical_crossentropy and the evaluation metric is accuracy. In the RADVESS dataset, each actor has to perform 8 emotions by saying and singing two sentences and two times for each. As a result, each actor would induce 4 samples for each emotion except neutral, disgust and surprised since there is no singing data for these emotions. Each audio wave is around 4 second, the first and last second are most likely silenced. The standard sentences are: 1. Kids are talking by the door.2. Dogs are sitting by the door. Observation: After I selected 1 actor and 1 actress’s dataset and listened to all of them. I found out male and female are expressing their emotions in a different way. Here are some findings: Male’s Angry is simply increased in volume.​ Male’s Happy and Sad significant features were laughing and crying tone in the silenced period in the audio. Female’s Happy, Angry and Sad are increased in volume.​ Female’s Disgust would add vomiting sound inside. Replicating Result: The author excluded the class neutral, disgust and surprised to do a 10 class recognition for the RAVDESS dataset. I tried to replicate his result with the model provided, I can achieve a result of However, I found out there is a data leakage problem where the validation set used in the training phase is identical to the test set. So, I re-do the data splitting part by isolating two actors and two actresses data into the test set which make sure it is unseen in the training phase. Actor no. 1–20 are used for Train / Valid sets with 8:2 splitting ratio. Actor no. 21–24 are isolated for testing usage. Train Set Shape: (1248, 216, 1) Valid Set Shape: (312, 216, 1) Test Set Shape: (320, 216, 1) — (Isolated) I re-trained the model with the new data-splitting setting and here is the result: From the train valid loss graph, we can see the model cannot even converge well with 10 target classes. Thus, I decided to reduce the complexity of my model by recognizing male emotions only. I isolated the two actors to be the test set, and the rest would be the train/valid set with 8:2 Stratified Shuffle Split which ensures there is no class imbalance in the dataset. Afterward, I trained both male and female data separately to explore the benchmark. Male Dataset Train Set = 640 samples from actor 1- 10. Valid Set = 160 samples from actor 1- 10. Test Set = 160 samples from actor 11- 12. Male Baseline Female Dataset Train Set = 608 samples from actress 1- 10. Valid Set = 152 samples from actress 1- 10. Test Set = 160 samples from actress 11- 12. Female Baseline As you can see, the confusion matrix of the male and female model is different. - Male: Angryand Happy are the dominant predicted classes in the male model but they are unlikely to mix up.​ - Female: Sad and Happy are the dominant predicted classes in the female model and Angry and Happy are very likely to mix up. Referring to the observation form the EDA section, I suspect the reason for female Angry and Happy are very likely to mix up is because their expression method is simply increasing the volume of the speech. On top of it, I wonder what if I further simplify the model by reducing the target class to Positive, Neutral and Negative or even Positive and Negative only. So, I grouped the emotions into 2 class and 3 class. 2 Class: Positive: happy, calm. Negative: angry, fearful, sad. 3 Class: Positive: happy. Neutral: calm, neutral. Negative: angry, fearful, sad. (Added neutral to the 3 class to explore the result.) Before I do the training experiment, I tune the model architecture with the male data by doing 5 class recognition. # Set the target class numbertarget_class = 5# Model model = Sequential()model.add(Conv1D(256, 8, padding='same',input_shape=(X_train.shape[1],1))) #1model.add(Activation('relu'))model.add(Conv1D(256, 8, padding='same')) #2model.add(BatchNormalization())model.add(Activation('relu'))model.add(Dropout(0.25))model.add(MaxPooling1D(pool_size=(8)))model.add(Conv1D(128, 8, padding='same')) #3model.add(Activation('relu')) model.add(Conv1D(128, 8, padding='same')) #4model.add(Activation('relu'))model.add(Conv1D(128, 8, padding='same')) #5model.add(Activation('relu'))model.add(Conv1D(128, 8, padding='same')) #6model.add(BatchNormalization())model.add(Activation('relu'))model.add(Dropout(0.25))model.add(MaxPooling1D(pool_size=(8)))model.add(Conv1D(64, 8, padding='same')) #7model.add(Activation('relu'))model.add(Conv1D(64, 8, padding='same')) #8model.add(Activation('relu'))model.add(Flatten())model.add(Dense(target_class)) #9model.add(Activation('softmax'))opt = keras.optimizers.SGD(lr=0.0001, momentum=0.0, decay=0.0, nesterov=False) I added 2 Conv1D layers, 1 MaxPooling1D layer and 2 BarchNormalization layers, moreover, I changed the dropout value to 0.25. Lastly, I changed the optimizer to SGD with 0.0001 learning rate. lr_reduce = ReduceLROnPlateau(monitor=’val_loss’, factor=0.9, patience=20, min_lr=0.000001)mcp_save = ModelCheckpoint(‘model/baseline_2class_np.h5’, save_best_only=True, monitor=’val_loss’, mode=’min’)cnnhistory=model.fit(x_traincnn, y_train, batch_size=16, epochs=700, validation_data=(x_testcnn, y_test), callbacks=[mcp_save, lr_reduce]) For the model training, I adopted Reduce Learning On Plateau and save the best model with the min val_loss only. And here are the model performance of different target class setups. Male 5 Class Female 5 Class Male 2 Class Male 3 Class After I tuned the model architecture, optimizer and learning rate schedule, I found out the model still cannot converge in the training period. I assumed it is the data size problem since we have 800 samples for train valid set only. Thus, I decided to explore the audio augmentation methods. Let’s take a look at some augmentation method with code. I simply augmented all of the datasets once to double the train / valid set size. Dynamic Value Change def dyn_change(data): """ Random Value Change. """ dyn_change = np.random.uniform(low=1.5,high=3) return (data * dyn_change) Pitch Tuning def pitch(data, sample_rate): """ Pitch Tuning. """ bins_per_octave = 12 pitch_pm = 2 pitch_change = pitch_pm * 2*(np.random.uniform()) data = librosa.effects.pitch_shift(data.astype('float64'), sample_rate, n_steps=pitch_change, bins_per_octave=bins_per_octave) Shifting def shift(data): """ Random Shifting. """ s_range = int(np.random.uniform(low=-5, high = 5)*500) return np.roll(data, s_range) White Noise Adding def noise(data): """ Adding White Noise. """ # you can take any distribution from https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.random.html noise_amp = 0.005*np.random.uniform()*np.amax(data) data = data.astype('float64') + noise_amp * np.random.normal(size=data.shape[0]) return data We can see that the augmentation can jack up the Validation Accuracy a lot, 70+% in general. Especially that adding white noise can achieve 87.19% Validation Accuracy, however, the Testing Accuracy and Testing F1-score dropped more than 5% respectively. Then, I wonder if I mixing different augmentation methods would bring a good result. Noise Adding + Shifting Noise Adding + ShiftingFor all sample Noise Adding + Shifting For positive sample only since the 2 class set is imbalance (skewed toward negative). Pitch Tuning + Noise AddingFor all sample Pitch Tuning + Noise AddingFor positive sample only In the end, I only have time to experiment with the male data set. I re-split the data with stratified shuffle split to make sure there is no data imbalance nor data leakage problem. I tuned the model by experimenting the male dataset since I want to simplified the model at the beginning. I also tested the by with different target label setups and augmentation method. I found out Noise Adding and Shifting for the imbalanced data could help in achieving a better result. Emotions are subjective and it is hard to notate them. We should define the emotions that suitable for our own project objective. Do not always trust the content from GitHub even it has lots of stars. Be aware of the data splitting. Exploratory Data Analysis always grant us good insight, and you have to be patient when you work on audio data! Deciding the input for your model: a sentence, a recording or an utterance? Lack of data is a crucial factor to achieve success in SER, however, it is complex and very expensive to build a good speech emotion dataset. Simplified your model when you lack data. I only selected the first 3 seconds to be the input data since it would reduce the dimension, the original notebook used 2.5 sec only. I would like to use the full length of the audio to do the experiment. Preprocess the data like cropping silence voice, normalize the length by zero padding, etc. Experiment the Recurrent Neural Network approach on this topic. GitHub: rezachu/emotion_recognition_cnn Linkedin: Kai Cheong, Reza Chu Remarks: Some papers related to this topic will be noted in the GitHub soon.
[ { "code": null, "e": 450, "s": 172, "text": "Recognizing human emotion has always been a fascinating task for data scientists. Lately, I am working on an experimental Speech Emotion Recognition (SER) project to explore its potential. I selected the most starred SER repository from GitHub to be the backbone of my project." }, { "code": null, "e": 557, "s": 450, "text": "Before we walk through the project, it is good to know the major bottleneck of Speech Emotion Recognition." }, { "code": null, "e": 666, "s": 557, "text": "Emotions are subjective, people would interpret it differently. It is hard to define the notion of emotions." }, { "code": null, "e": 826, "s": 666, "text": "Annotating an audio recording is challenging. Should we label a single word, sentence or a whole conversation? How many emotions should we define to recognize?" }, { "code": null, "e": 1091, "s": 826, "text": "Collecting data is complex. There are lots of audio data can be achieved from films or news. However, both of them are biased since news reporting has to be neutral and actors’ emotions are imitated. It is hard to look for neutral audio recording without any bias." }, { "code": null, "e": 1379, "s": 1091, "text": "Labeling data require high human and time cost. Unlike drawing a bounding box on an image, it requires trained personnel to listen to the whole audio recording, analysis it and give an annotation. The annotation result has to be evaluated by multiple individuals due to its subjectivity." }, { "code": null, "e": 1524, "s": 1379, "text": "Using Convolutional Neural Network to recognize emotion from the audio recording. And the repository owner does not provide any paper reference." }, { "code": null, "e": 1706, "s": 1524, "text": "These are two datasets originally made use in the repository RAVDESS and SAVEE, and I only adopted RAVDESS in my model. In the RAVDESS, there are two types of data: speech and song." }, { "code": null, "e": 1789, "s": 1706, "text": "Data Set: The Ryerson Audio-Visual Database of Emotional Speech and Song (RAVDESS)" }, { "code": null, "e": 1861, "s": 1789, "text": "12 Actors & 12 Actresses recorded speech and song version respectively." }, { "code": null, "e": 1906, "s": 1861, "text": "Actor no.18 does not have song version data." }, { "code": null, "e": 1988, "s": 1906, "text": "Emotion Disgust, Neutral and Surprised are not included in the song version data." }, { "code": null, "e": 2038, "s": 1988, "text": "Here is the emotion class distribution bar chart." }, { "code": null, "e": 2149, "s": 2038, "text": "When we do Speech Recognition tasks, MFCCs is the state-of-the-art feature since it was invented in the 1980s." }, { "code": null, "e": 2500, "s": 2149, "text": "This shape determines what sound comes out. If we can determine the shape accurately, this should give us an accurate representation of the phoneme being produced. The shape of the vocal tract manifests itself in the envelope of the short time power spectrum, and the job of MFCCs is to accurately represent this envelope. — Noted from: MFCC tutorial" }, { "code": null, "e": 2728, "s": 2500, "text": "We would use MFCCs to be our input feature. If you want a thorough understanding of MFCCs, here is a great tutorial for you. Loading audio data and converting it to MFCCs format can be easily done by the Python package librosa." }, { "code": null, "e": 2849, "s": 2728, "text": "The author developed the CNN model with Keras and constructed with 7 layers — 6 Conv1D layers followed by a Dense layer." }, { "code": null, "e": 3541, "s": 2849, "text": "model = Sequential()model.add(Conv1D(256, 5,padding='same', input_shape=(216,1))) #1model.add(Activation('relu'))model.add(Conv1D(128, 5,padding='same')) #2model.add(Activation('relu'))model.add(Dropout(0.1))model.add(MaxPooling1D(pool_size=(8)))model.add(Conv1D(128, 5,padding='same')) #3model.add(Activation('relu'))#model.add(Conv1D(128, 5,padding='same')) #4#model.add(Activation('relu'))#model.add(Conv1D(128, 5,padding='same')) #5#model.add(Activation('relu'))#model.add(Dropout(0.2))model.add(Conv1D(128, 5,padding='same')) #6model.add(Activation('relu'))model.add(Flatten())model.add(Dense(10)) #7model.add(Activation('softmax'))opt = keras.optimizers.rmsprop(lr=0.00001, decay=1e-6)" }, { "code": null, "e": 3769, "s": 3541, "text": "The author commented layer #4 and #5 in the latest notebook (18 Sep 2018 Update) and the model weight file does not fit the network provided, thus, I cannot load the weight provide and replicate its result 72% Testing Accuracy." }, { "code": null, "e": 3874, "s": 3769, "text": "The model only simply trained with batch_size=16 and 700 epochs without any learning rate schedule, etc." }, { "code": null, "e": 4088, "s": 3874, "text": "# Compile Modelmodel.compile(loss='categorical_crossentropy', optimizer=opt,metrics=['accuracy'])# Fit Modelcnnhistory=model.fit(x_traincnn, y_train, batch_size=16, epochs=700, validation_data=(x_testcnn, y_test))" }, { "code": null, "e": 4173, "s": 4088, "text": "Its loss function is categorical_crossentropy and the evaluation metric is accuracy." }, { "code": null, "e": 4535, "s": 4173, "text": "In the RADVESS dataset, each actor has to perform 8 emotions by saying and singing two sentences and two times for each. As a result, each actor would induce 4 samples for each emotion except neutral, disgust and surprised since there is no singing data for these emotions. Each audio wave is around 4 second, the first and last second are most likely silenced." }, { "code": null, "e": 4563, "s": 4535, "text": "The standard sentences are:" }, { "code": null, "e": 4628, "s": 4563, "text": "1. Kids are talking by the door.2. Dogs are sitting by the door." }, { "code": null, "e": 4641, "s": 4628, "text": "Observation:" }, { "code": null, "e": 4821, "s": 4641, "text": "After I selected 1 actor and 1 actress’s dataset and listened to all of them. I found out male and female are expressing their emotions in a different way. Here are some findings:" }, { "code": null, "e": 4866, "s": 4821, "text": "Male’s Angry is simply increased in volume.​" }, { "code": null, "e": 4975, "s": 4866, "text": "Male’s Happy and Sad significant features were laughing and crying tone in the silenced period in the audio." }, { "code": null, "e": 5031, "s": 4975, "text": "Female’s Happy, Angry and Sad are increased in volume.​" }, { "code": null, "e": 5081, "s": 5031, "text": "Female’s Disgust would add vomiting sound inside." }, { "code": null, "e": 5101, "s": 5081, "text": "Replicating Result:" }, { "code": null, "e": 5216, "s": 5101, "text": "The author excluded the class neutral, disgust and surprised to do a 10 class recognition for the RAVDESS dataset." }, { "code": null, "e": 5299, "s": 5216, "text": "I tried to replicate his result with the model provided, I can achieve a result of" }, { "code": null, "e": 5587, "s": 5299, "text": "However, I found out there is a data leakage problem where the validation set used in the training phase is identical to the test set. So, I re-do the data splitting part by isolating two actors and two actresses data into the test set which make sure it is unseen in the training phase." }, { "code": null, "e": 5660, "s": 5587, "text": "Actor no. 1–20 are used for Train / Valid sets with 8:2 splitting ratio." }, { "code": null, "e": 5708, "s": 5660, "text": "Actor no. 21–24 are isolated for testing usage." }, { "code": null, "e": 5740, "s": 5708, "text": "Train Set Shape: (1248, 216, 1)" }, { "code": null, "e": 5771, "s": 5740, "text": "Valid Set Shape: (312, 216, 1)" }, { "code": null, "e": 5814, "s": 5771, "text": "Test Set Shape: (320, 216, 1) — (Isolated)" }, { "code": null, "e": 5897, "s": 5814, "text": "I re-trained the model with the new data-splitting setting and here is the result:" }, { "code": null, "e": 6353, "s": 5897, "text": "From the train valid loss graph, we can see the model cannot even converge well with 10 target classes. Thus, I decided to reduce the complexity of my model by recognizing male emotions only. I isolated the two actors to be the test set, and the rest would be the train/valid set with 8:2 Stratified Shuffle Split which ensures there is no class imbalance in the dataset. Afterward, I trained both male and female data separately to explore the benchmark." }, { "code": null, "e": 6366, "s": 6353, "text": "Male Dataset" }, { "code": null, "e": 6408, "s": 6366, "text": "Train Set = 640 samples from actor 1- 10." }, { "code": null, "e": 6450, "s": 6408, "text": "Valid Set = 160 samples from actor 1- 10." }, { "code": null, "e": 6492, "s": 6450, "text": "Test Set = 160 samples from actor 11- 12." }, { "code": null, "e": 6506, "s": 6492, "text": "Male Baseline" }, { "code": null, "e": 6521, "s": 6506, "text": "Female Dataset" }, { "code": null, "e": 6565, "s": 6521, "text": "Train Set = 608 samples from actress 1- 10." }, { "code": null, "e": 6609, "s": 6565, "text": "Valid Set = 152 samples from actress 1- 10." }, { "code": null, "e": 6653, "s": 6609, "text": "Test Set = 160 samples from actress 11- 12." }, { "code": null, "e": 6669, "s": 6653, "text": "Female Baseline" }, { "code": null, "e": 6749, "s": 6669, "text": "As you can see, the confusion matrix of the male and female model is different." }, { "code": null, "e": 6859, "s": 6749, "text": "- Male: Angryand Happy are the dominant predicted classes in the male model but they are unlikely to mix up.​" }, { "code": null, "e": 6985, "s": 6859, "text": "- Female: Sad and Happy are the dominant predicted classes in the female model and Angry and Happy are very likely to mix up." }, { "code": null, "e": 7192, "s": 6985, "text": "Referring to the observation form the EDA section, I suspect the reason for female Angry and Happy are very likely to mix up is because their expression method is simply increasing the volume of the speech." }, { "code": null, "e": 7404, "s": 7192, "text": "On top of it, I wonder what if I further simplify the model by reducing the target class to Positive, Neutral and Negative or even Positive and Negative only. So, I grouped the emotions into 2 class and 3 class." }, { "code": null, "e": 7413, "s": 7404, "text": "2 Class:" }, { "code": null, "e": 7436, "s": 7413, "text": "Positive: happy, calm." }, { "code": null, "e": 7467, "s": 7436, "text": "Negative: angry, fearful, sad." }, { "code": null, "e": 7476, "s": 7467, "text": "3 Class:" }, { "code": null, "e": 7493, "s": 7476, "text": "Positive: happy." }, { "code": null, "e": 7517, "s": 7493, "text": "Neutral: calm, neutral." }, { "code": null, "e": 7548, "s": 7517, "text": "Negative: angry, fearful, sad." }, { "code": null, "e": 7602, "s": 7548, "text": "(Added neutral to the 3 class to explore the result.)" }, { "code": null, "e": 7718, "s": 7602, "text": "Before I do the training experiment, I tune the model architecture with the male data by doing 5 class recognition." }, { "code": null, "e": 8757, "s": 7718, "text": "# Set the target class numbertarget_class = 5# Model model = Sequential()model.add(Conv1D(256, 8, padding='same',input_shape=(X_train.shape[1],1))) #1model.add(Activation('relu'))model.add(Conv1D(256, 8, padding='same')) #2model.add(BatchNormalization())model.add(Activation('relu'))model.add(Dropout(0.25))model.add(MaxPooling1D(pool_size=(8)))model.add(Conv1D(128, 8, padding='same')) #3model.add(Activation('relu')) model.add(Conv1D(128, 8, padding='same')) #4model.add(Activation('relu'))model.add(Conv1D(128, 8, padding='same')) #5model.add(Activation('relu'))model.add(Conv1D(128, 8, padding='same')) #6model.add(BatchNormalization())model.add(Activation('relu'))model.add(Dropout(0.25))model.add(MaxPooling1D(pool_size=(8)))model.add(Conv1D(64, 8, padding='same')) #7model.add(Activation('relu'))model.add(Conv1D(64, 8, padding='same')) #8model.add(Activation('relu'))model.add(Flatten())model.add(Dense(target_class)) #9model.add(Activation('softmax'))opt = keras.optimizers.SGD(lr=0.0001, momentum=0.0, decay=0.0, nesterov=False)" }, { "code": null, "e": 8949, "s": 8757, "text": "I added 2 Conv1D layers, 1 MaxPooling1D layer and 2 BarchNormalization layers, moreover, I changed the dropout value to 0.25. Lastly, I changed the optimizer to SGD with 0.0001 learning rate." }, { "code": null, "e": 9289, "s": 8949, "text": "lr_reduce = ReduceLROnPlateau(monitor=’val_loss’, factor=0.9, patience=20, min_lr=0.000001)mcp_save = ModelCheckpoint(‘model/baseline_2class_np.h5’, save_best_only=True, monitor=’val_loss’, mode=’min’)cnnhistory=model.fit(x_traincnn, y_train, batch_size=16, epochs=700, validation_data=(x_testcnn, y_test), callbacks=[mcp_save, lr_reduce])" }, { "code": null, "e": 9471, "s": 9289, "text": "For the model training, I adopted Reduce Learning On Plateau and save the best model with the min val_loss only. And here are the model performance of different target class setups." }, { "code": null, "e": 9484, "s": 9471, "text": "Male 5 Class" }, { "code": null, "e": 9499, "s": 9484, "text": "Female 5 Class" }, { "code": null, "e": 9512, "s": 9499, "text": "Male 2 Class" }, { "code": null, "e": 9525, "s": 9512, "text": "Male 3 Class" }, { "code": null, "e": 9957, "s": 9525, "text": "After I tuned the model architecture, optimizer and learning rate schedule, I found out the model still cannot converge in the training period. I assumed it is the data size problem since we have 800 samples for train valid set only. Thus, I decided to explore the audio augmentation methods. Let’s take a look at some augmentation method with code. I simply augmented all of the datasets once to double the train / valid set size." }, { "code": null, "e": 9978, "s": 9957, "text": "Dynamic Value Change" }, { "code": null, "e": 10118, "s": 9978, "text": "def dyn_change(data): \"\"\" Random Value Change. \"\"\" dyn_change = np.random.uniform(low=1.5,high=3) return (data * dyn_change)" }, { "code": null, "e": 10131, "s": 10118, "text": "Pitch Tuning" }, { "code": null, "e": 10495, "s": 10131, "text": "def pitch(data, sample_rate): \"\"\" Pitch Tuning. \"\"\" bins_per_octave = 12 pitch_pm = 2 pitch_change = pitch_pm * 2*(np.random.uniform()) data = librosa.effects.pitch_shift(data.astype('float64'), sample_rate, n_steps=pitch_change, bins_per_octave=bins_per_octave)" }, { "code": null, "e": 10504, "s": 10495, "text": "Shifting" }, { "code": null, "e": 10646, "s": 10504, "text": "def shift(data): \"\"\" Random Shifting. \"\"\" s_range = int(np.random.uniform(low=-5, high = 5)*500) return np.roll(data, s_range)" }, { "code": null, "e": 10665, "s": 10646, "text": "White Noise Adding" }, { "code": null, "e": 10984, "s": 10665, "text": "def noise(data): \"\"\" Adding White Noise. \"\"\" # you can take any distribution from https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.random.html noise_amp = 0.005*np.random.uniform()*np.amax(data) data = data.astype('float64') + noise_amp * np.random.normal(size=data.shape[0]) return data" }, { "code": null, "e": 11323, "s": 10984, "text": "We can see that the augmentation can jack up the Validation Accuracy a lot, 70+% in general. Especially that adding white noise can achieve 87.19% Validation Accuracy, however, the Testing Accuracy and Testing F1-score dropped more than 5% respectively. Then, I wonder if I mixing different augmentation methods would bring a good result." }, { "code": null, "e": 11347, "s": 11323, "text": "Noise Adding + Shifting" }, { "code": null, "e": 11385, "s": 11347, "text": "Noise Adding + ShiftingFor all sample" }, { "code": null, "e": 11495, "s": 11385, "text": "Noise Adding + Shifting For positive sample only since the 2 class set is imbalance (skewed toward negative)." }, { "code": null, "e": 11537, "s": 11495, "text": "Pitch Tuning + Noise AddingFor all sample" }, { "code": null, "e": 11589, "s": 11537, "text": "Pitch Tuning + Noise AddingFor positive sample only" }, { "code": null, "e": 12063, "s": 11589, "text": "In the end, I only have time to experiment with the male data set. I re-split the data with stratified shuffle split to make sure there is no data imbalance nor data leakage problem. I tuned the model by experimenting the male dataset since I want to simplified the model at the beginning. I also tested the by with different target label setups and augmentation method. I found out Noise Adding and Shifting for the imbalanced data could help in achieving a better result." }, { "code": null, "e": 12118, "s": 12063, "text": "Emotions are subjective and it is hard to notate them." }, { "code": null, "e": 12193, "s": 12118, "text": "We should define the emotions that suitable for our own project objective." }, { "code": null, "e": 12264, "s": 12193, "text": "Do not always trust the content from GitHub even it has lots of stars." }, { "code": null, "e": 12296, "s": 12264, "text": "Be aware of the data splitting." }, { "code": null, "e": 12408, "s": 12296, "text": "Exploratory Data Analysis always grant us good insight, and you have to be patient when you work on audio data!" }, { "code": null, "e": 12484, "s": 12408, "text": "Deciding the input for your model: a sentence, a recording or an utterance?" }, { "code": null, "e": 12626, "s": 12484, "text": "Lack of data is a crucial factor to achieve success in SER, however, it is complex and very expensive to build a good speech emotion dataset." }, { "code": null, "e": 12668, "s": 12626, "text": "Simplified your model when you lack data." }, { "code": null, "e": 12874, "s": 12668, "text": "I only selected the first 3 seconds to be the input data since it would reduce the dimension, the original notebook used 2.5 sec only. I would like to use the full length of the audio to do the experiment." }, { "code": null, "e": 12966, "s": 12874, "text": "Preprocess the data like cropping silence voice, normalize the length by zero padding, etc." }, { "code": null, "e": 13030, "s": 12966, "text": "Experiment the Recurrent Neural Network approach on this topic." }, { "code": null, "e": 13070, "s": 13030, "text": "GitHub: rezachu/emotion_recognition_cnn" }, { "code": null, "e": 13101, "s": 13070, "text": "Linkedin: Kai Cheong, Reza Chu" } ]
C++ Program to Implement Caesar Cypher
It is a mono-alphabetic cipher wherein each letter of the plaintext is substituted by another letter to form the ciphertext. It is a simplest form of substitution cipher scheme. This cryptosystem is generally referred to as the Shift Cipher. The concept is to replace each alphabet by another alphabet which is ‘shifted’ by some fixed number between 0 and 25. For this type of scheme, both sender and receiver agree on a ‘secret shift number’ for shifting the alphabet. This number which is between 0 and 25 becomes the key of encryption. The name ‘Caesar Cipher’ is occasionally used to describe the Shift Cipher when the ‘shift of three’ is used. In order to encrypt a plaintext letter, the sender positions the sliding ruler underneath the first set of plaintext letters and slides it to LEFT by the number of positions of the secret shift. In order to encrypt a plaintext letter, the sender positions the sliding ruler underneath the first set of plaintext letters and slides it to LEFT by the number of positions of the secret shift. The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler underneath. The result of this process is depicted in the following illustration for an agreed shift of three positions. In this case, the plaintext ‘tutorial’ is encrypted to the ciphertext ‘wxwruldo’. Here is the ciphertext alphabet for a Shift of 3 − The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler underneath. The result of this process is depicted in the following illustration for an agreed shift of three positions. In this case, the plaintext ‘tutorial’ is encrypted to the ciphertext ‘wxwruldo’. Here is the ciphertext alphabet for a Shift of 3 − On receiving the ciphertext, the receiver who also knows the secret shift, positions his sliding ruler underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift number, 3 in this case. On receiving the ciphertext, the receiver who also knows the secret shift, positions his sliding ruler underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift number, 3 in this case. He then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath. Hence the ciphertext ‘wxwruldo’ is decrypted to ‘tutorial’. To decrypt a message encoded with a Shift of 3, generate the plaintext alphabet using a shift of ‘-3’ as shown below − He then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath. Hence the ciphertext ‘wxwruldo’ is decrypted to ‘tutorial’. To decrypt a message encoded with a Shift of 3, generate the plaintext alphabet using a shift of ‘-3’ as shown below − Here is the implementation of above process in C++. Take the message and key as input − Input: tutorial. Output: wxwruldo Input: wxwruldo Output: tutorial Begin For i = 0 to msg[i] != '\0' ch = msg[i] //encrypt for lowercase letter If (ch >= 'a' and ch <= 'z') ch = ch + key if (ch > 'z') ch = ch - 'z' + 'a' - 1 done msg[i] = ch //encrypt for uppercase letter else if (ch >= 'A' and ch <= 'Z') ch = ch + key if (ch > 'Z') ch = ch - 'Z' + 'A' - 1 done msg[i] = ch done done Print Encrypted message End Begin For i = 0 to msg[i] != '\0' ch = msg[i] //decrypt for lowercase letter if(ch >= 'a' and ch <= 'z') ch = ch - key if (ch < 'a') ch = ch +'z' - 'a' + 1 done msg[i] = ch //decrypt for uppercase letter else if (ch >= 'A' and ch <= 'Z') ch = ch + key if (ch < 'A') ch = ch + 'Z' - 'A' + 1 done msg[i] = ch done done Print decrypted message End #include<iostream> #include<string.h> using namespace std; int main() { cout<<"Enter the message:\n"; char msg[100]; cin.getline(msg,100); //take the message as input int i, j, length,choice,key; cout << "Enter key: "; cin >> key; //take the key as input length = strlen(msg); cout<<"Enter your choice \n1. Encryption \n2. Decryption \n"; cin>>choice; if (choice==1) //for encryption{ char ch; for(int i = 0; msg[i] != '\0'; ++i) { ch = msg[i]; //encrypt for lowercase letter If (ch >= 'a' && ch <= 'z'){ ch = ch + key; if (ch > 'z') { ch = ch - 'z' + 'a' - 1; } msg[i] = ch; } //encrypt for uppercase letter else if (ch >= 'A' && ch <= 'Z'){ ch = ch + key; if (ch > 'Z'){ ch = ch - 'Z' + 'A' - 1; } msg[i] = ch; } } printf("Encrypted message: %s", msg); } else if (choice == 2) { //for decryption char ch; for(int i = 0; msg[i] != '\0'; ++i) { ch = msg[i]; //decrypt for lowercase letter if(ch >= 'a' && ch <= 'z') { ch = ch - key; if(ch < 'a'){ ch = ch + 'z' - 'a' + 1; } msg[i] = ch; } //decrypt for uppercase letter else if(ch >= 'A' && ch <= 'Z') { ch = ch - key; if(ch < 'A') { ch = ch + 'Z' - 'A' + 1; } msg[i] = ch; } } cout << "Decrypted message: " << msg; } } For encryption: Enter the message: tutorial Enter key: 3 Enter your choice 1. Encryption 2. Decryption 1 Encrypted message: wxwruldo For decryption: Enter the message: wxwruldo Enter key: 3 Enter your choice 1. Encryption 2. Decryption 2 Decrypted message: tutorial
[ { "code": null, "e": 1240, "s": 1062, "text": "It is a mono-alphabetic cipher wherein each letter of the plaintext is substituted by another letter to form the ciphertext. It is a simplest form of substitution cipher scheme." }, { "code": null, "e": 1422, "s": 1240, "text": "This cryptosystem is generally referred to as the Shift Cipher. The concept is to replace each alphabet by another alphabet which is ‘shifted’ by some fixed number between 0 and 25." }, { "code": null, "e": 1601, "s": 1422, "text": "For this type of scheme, both sender and receiver agree on a ‘secret shift number’ for shifting the alphabet. This number which is between 0 and 25 becomes the key of encryption." }, { "code": null, "e": 1711, "s": 1601, "text": "The name ‘Caesar Cipher’ is occasionally used to describe the Shift Cipher when the ‘shift of three’ is used." }, { "code": null, "e": 1906, "s": 1711, "text": "In order to encrypt a plaintext letter, the sender positions the sliding ruler underneath the first set of plaintext letters and slides it to LEFT by the number of positions of the secret shift." }, { "code": null, "e": 2101, "s": 1906, "text": "In order to encrypt a plaintext letter, the sender positions the sliding ruler underneath the first set of plaintext letters and slides it to LEFT by the number of positions of the secret shift." }, { "code": null, "e": 2440, "s": 2101, "text": "The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler underneath. The result of this process is depicted in the following illustration for an agreed shift of three positions. In this case, the plaintext ‘tutorial’ is encrypted to the ciphertext ‘wxwruldo’. Here is the ciphertext alphabet for a Shift of 3 −" }, { "code": null, "e": 2779, "s": 2440, "text": "The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler underneath. The result of this process is depicted in the following illustration for an agreed shift of three positions. In this case, the plaintext ‘tutorial’ is encrypted to the ciphertext ‘wxwruldo’. Here is the ciphertext alphabet for a Shift of 3 −" }, { "code": null, "e": 2984, "s": 2779, "text": "On receiving the ciphertext, the receiver who also knows the secret shift, positions his sliding ruler underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift number, 3 in this case." }, { "code": null, "e": 3189, "s": 2984, "text": "On receiving the ciphertext, the receiver who also knows the secret shift, positions his sliding ruler underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift number, 3 in this case." }, { "code": null, "e": 3464, "s": 3189, "text": "He then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath. Hence the ciphertext ‘wxwruldo’ is decrypted to ‘tutorial’. To decrypt a message encoded with a Shift of 3, generate the plaintext alphabet using a shift of ‘-3’ as shown below −" }, { "code": null, "e": 3739, "s": 3464, "text": "He then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath. Hence the ciphertext ‘wxwruldo’ is decrypted to ‘tutorial’. To decrypt a message encoded with a Shift of 3, generate the plaintext alphabet using a shift of ‘-3’ as shown below −" }, { "code": null, "e": 3791, "s": 3739, "text": "Here is the implementation of above process in C++." }, { "code": null, "e": 3827, "s": 3791, "text": "Take the message and key as input −" }, { "code": null, "e": 3844, "s": 3827, "text": "Input: tutorial." }, { "code": null, "e": 3861, "s": 3844, "text": "Output: wxwruldo" }, { "code": null, "e": 3877, "s": 3861, "text": "Input: wxwruldo" }, { "code": null, "e": 3894, "s": 3877, "text": "Output: tutorial" }, { "code": null, "e": 4376, "s": 3894, "text": "Begin\n For i = 0 to msg[i] != '\\0'\n ch = msg[i]\n //encrypt for lowercase letter\n If (ch >= 'a' and ch <= 'z')\n ch = ch + key\n if (ch > 'z')\n ch = ch - 'z' + 'a' - 1\n done\n msg[i] = ch\n //encrypt for uppercase letter\n else if (ch >= 'A' and ch <= 'Z')\n ch = ch + key\n if (ch > 'Z')\n ch = ch - 'Z' + 'A' - 1\n done\n msg[i] = ch\n done\n done\n Print Encrypted message\nEnd" }, { "code": null, "e": 4850, "s": 4376, "text": "Begin\n For i = 0 to msg[i] != '\\0'\n ch = msg[i]\n //decrypt for lowercase letter\n if(ch >= 'a' and ch <= 'z')\n ch = ch - key\n if (ch < 'a')\n ch = ch +'z' - 'a' + 1\n done\n msg[i] = ch\n //decrypt for uppercase letter\n else if (ch >= 'A' and ch <= 'Z')\n ch = ch + key\n if (ch < 'A')\n ch = ch + 'Z' - 'A' + 1\n done\n msg[i] = ch\n done\n done\n Print decrypted message\nEnd" }, { "code": null, "e": 6487, "s": 4850, "text": "#include<iostream>\n#include<string.h>\nusing namespace std;\nint main() {\n cout<<\"Enter the message:\\n\";\n char msg[100];\n cin.getline(msg,100); //take the message as input\n int i, j, length,choice,key;\n cout << \"Enter key: \";\n cin >> key; //take the key as input\n length = strlen(msg);\n cout<<\"Enter your choice \\n1. Encryption \\n2. Decryption \\n\";\n cin>>choice;\n if (choice==1) //for encryption{\n char ch;\n for(int i = 0; msg[i] != '\\0'; ++i) {\n ch = msg[i];\n //encrypt for lowercase letter\n If (ch >= 'a' && ch <= 'z'){\n ch = ch + key;\n if (ch > 'z') {\n ch = ch - 'z' + 'a' - 1;\n } \n msg[i] = ch;\n }\n //encrypt for uppercase letter\n else if (ch >= 'A' && ch <= 'Z'){\n ch = ch + key;\n if (ch > 'Z'){\n ch = ch - 'Z' + 'A' - 1;\n }\n msg[i] = ch;\n }\n }\n printf(\"Encrypted message: %s\", msg);\n }\n else if (choice == 2) { //for decryption\n char ch;\n for(int i = 0; msg[i] != '\\0'; ++i) {\n ch = msg[i];\n //decrypt for lowercase letter\n if(ch >= 'a' && ch <= 'z') {\n ch = ch - key;\n if(ch < 'a'){\n ch = ch + 'z' - 'a' + 1;\n }\n msg[i] = ch;\n }\n //decrypt for uppercase letter\n else if(ch >= 'A' && ch <= 'Z') {\n ch = ch - key;\n if(ch < 'A') {\n ch = ch + 'Z' - 'A' + 1;\n }\n msg[i] = ch;\n }\n }\n cout << \"Decrypted message: \" << msg;\n }\n}" }, { "code": null, "e": 6754, "s": 6487, "text": "For encryption:\nEnter the message:\ntutorial\nEnter key: 3\nEnter your choice\n1. Encryption\n2. Decryption\n1\nEncrypted message: wxwruldo\n\nFor decryption:\nEnter the message:\nwxwruldo\nEnter key: 3\nEnter your choice\n1. Encryption\n2. Decryption\n2\nDecrypted message: tutorial" } ]
Executing main() in C/C++ - behind the scene - GeeksforGeeks
19 Aug, 2020 How to write a C program to print “Hello world” without main() function?At first, it seems impractical to execute a program without a main() function because the main() function is the entry point of any program. Let us first understand what happens under the hood while executing a C program in Linux system, how main() is called and how to execute a program without main(). Following setup is considered for the demonstration. Ubuntu 16.4 LTS operating system GCC 5.4.0 compiler objdump utility From C/C++ programming perspective, the program entry point is main() function. From the perspective of program execution, however, it is not. Prior to the point when the execution flow reaches to the main(), calls to few other functions are made, which setup arguments, prepare environment variables for program execution etc. The executable file created after compiling a C source code is a Executable and Linkable Format (ELF) file.Every ELF file have a ELF header where there is a e_entry field which contains the program memory address from which the execution of executable will start. This memory address point to the _start() function.After loading the program, loader looks for the e_entry field from the ELF file header. Executable and Linkable Format (ELF) is a common standard file format used in UNIX system for executable files, object code, shared libraries, and core dumps. Let’s see this using an example. I’m creating a example.c file to demonstrate this. int main(){ return(0);} Now compiling this using following commands gcc -o example example.c Now an example executable is created, let us examine this using objdump utility objdump -f example This outputs following critical information of executable on my machine. Have a look at start address below, this is the address pointing to _start() function. example: file format elf64-x86-64 architecture: i386:x86-64, flags 0x00000112: EXEC_P, HAS_SYMS, D_PAGED start address 0x00000000004003e0 We can cross check this address by deassembling the executable, the output is long so I’m just pasting the output which shows where this address 0x00000000004003e0 is pointing objdump --disassemble example Output : 00000000004003e0 <_start>: 4003e0: 31 ed xor %ebp,%ebp 4003e2: 49 89 d1 mov %rdx,%r9 4003e5: 5e pop %rsi 4003e6: 48 89 e2 mov %rsp,%rdx 4003e9: 48 83 e4 f0 and $0xfffffffffffffff0,%rsp 4003ed: 50 push %rax 4003ee: 54 push %rsp 4003ef: 49 c7 c0 60 05 40 00 mov $0x400560,%r8 4003f6: 48 c7 c1 f0 04 40 00 mov $0x4004f0,%rcx 4003fd: 48 c7 c7 d6 04 40 00 mov $0x4004d6,%rdi 400404: e8 b7 ff ff ff callq 4003c0 400409: f4 hlt 40040a: 66 0f 1f 44 00 00 nopw 0x0(%rax,%rax,1) As we can clearly see this is pointing to the _start() function. The _start() function prepare the input arguments for another function _libc_start_main() which will be called next. This is prototype of _libc_start_main() function. Here we can see the arguments which were prepared by _start() function. int __libc_start_main(int (*main) (int, char * *, char * *), /* address of main function*/int argc, /* number of command line args*/char ** ubp_av, /* command line arg array*/void (*init) (void), /* address of init function*/void (*fini) (void), /* address of fini function*/void (*rtld_fini) (void), /* address of dynamic linker fini function */void (* stack_end) /* end of the stack address*/); The role of _libc_start_main() function is following – Preparing environment variables for program execution Calls _init() function which performs initialization before the main() function start. Register _fini() and _rtld_fini() functions to perform cleanup after program terminatesAfter all the prerequisite actions has been completed, _libc_start_main() calls the main() function.Writing program without main()Now we know how the call to the main() is made.To make it clear, main() is nothing but a agreed term for startup code. We can have any name for startup code it doesn’t necessarily have to be “main”. As _start() function by default calls main(), we have to change it if we want to execute our custom startup code. We can override the _start() function to make it call our custom startup code not main(). Let’s have an example, save it as nomain.c –#include<stdio.h>#include<stdlib.h>void _start(){ int x = my_fun(); //calling custom main function exit(x);} int my_fun() // our custom main function{ printf("Hello world!\n"); return 0;}Now we have to force compiler to not use it’s own implementation of _start().In GCC we can do this using -nostartfilesgcc -nostartfiles -o nomain nomain.c Execute the executable nomain./nomain Output:Hello world! Referenceshttp://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.htmlAdvanced C/C++ Compiling by Milan StevanovicThis article is contributed by Atul Kumar. 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.My Personal Notes arrow_drop_upSave Now we know how the call to the main() is made.To make it clear, main() is nothing but a agreed term for startup code. We can have any name for startup code it doesn’t necessarily have to be “main”. As _start() function by default calls main(), we have to change it if we want to execute our custom startup code. We can override the _start() function to make it call our custom startup code not main(). Let’s have an example, save it as nomain.c – #include<stdio.h>#include<stdlib.h>void _start(){ int x = my_fun(); //calling custom main function exit(x);} int my_fun() // our custom main function{ printf("Hello world!\n"); return 0;} Now we have to force compiler to not use it’s own implementation of _start().In GCC we can do this using -nostartfiles gcc -nostartfiles -o nomain nomain.c Execute the executable nomain ./nomain Output: Hello world! References http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html Advanced C/C++ Compiling by Milan Stevanovic This article is contributed by Atul Kumar. 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. nikhilnagrale2 system-programming C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ Arrow operator -> in C/C++ with Examples 'this' pointer in C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 24232, "s": 24204, "text": "\n19 Aug, 2020" }, { "code": null, "e": 24445, "s": 24232, "text": "How to write a C program to print “Hello world” without main() function?At first, it seems impractical to execute a program without a main() function because the main() function is the entry point of any program." }, { "code": null, "e": 24608, "s": 24445, "text": "Let us first understand what happens under the hood while executing a C program in Linux system, how main() is called and how to execute a program without main()." }, { "code": null, "e": 24661, "s": 24608, "text": "Following setup is considered for the demonstration." }, { "code": null, "e": 24694, "s": 24661, "text": "Ubuntu 16.4 LTS operating system" }, { "code": null, "e": 24713, "s": 24694, "text": "GCC 5.4.0 compiler" }, { "code": null, "e": 24729, "s": 24713, "text": "objdump utility" }, { "code": null, "e": 25057, "s": 24729, "text": "From C/C++ programming perspective, the program entry point is main() function. From the perspective of program execution, however, it is not. Prior to the point when the execution flow reaches to the main(), calls to few other functions are made, which setup arguments, prepare environment variables for program execution etc." }, { "code": null, "e": 25619, "s": 25057, "text": "The executable file created after compiling a C source code is a Executable and Linkable Format (ELF) file.Every ELF file have a ELF header where there is a e_entry field which contains the program memory address from which the execution of executable will start. This memory address point to the _start() function.After loading the program, loader looks for the e_entry field from the ELF file header. Executable and Linkable Format (ELF) is a common standard file format used in UNIX system for executable files, object code, shared libraries, and core dumps." }, { "code": null, "e": 25703, "s": 25619, "text": "Let’s see this using an example. I’m creating a example.c file to demonstrate this." }, { "code": "int main(){ return(0);}", "e": 25729, "s": 25703, "text": null }, { "code": null, "e": 25773, "s": 25729, "text": "Now compiling this using following commands" }, { "code": null, "e": 25799, "s": 25773, "text": "gcc -o example example.c\n" }, { "code": null, "e": 25879, "s": 25799, "text": "Now an example executable is created, let us examine this using objdump utility" }, { "code": null, "e": 25899, "s": 25879, "text": "objdump -f example\n" }, { "code": null, "e": 26059, "s": 25899, "text": "This outputs following critical information of executable on my machine. Have a look at start address below, this is the address pointing to _start() function." }, { "code": null, "e": 26202, "s": 26059, "text": "example: file format elf64-x86-64\narchitecture: i386:x86-64, flags 0x00000112:\nEXEC_P, HAS_SYMS, D_PAGED\nstart address 0x00000000004003e0\n" }, { "code": null, "e": 26378, "s": 26202, "text": "We can cross check this address by deassembling the executable, the output is long so I’m just pasting the output which shows where this address 0x00000000004003e0 is pointing" }, { "code": null, "e": 26410, "s": 26378, "text": "objdump --disassemble example\n" }, { "code": null, "e": 26419, "s": 26410, "text": "Output :" }, { "code": null, "e": 27171, "s": 26419, "text": "00000000004003e0 <_start>:\n 4003e0: 31 ed xor %ebp,%ebp\n 4003e2: 49 89 d1 mov %rdx,%r9\n 4003e5: 5e pop %rsi\n 4003e6: 48 89 e2 mov %rsp,%rdx\n 4003e9: 48 83 e4 f0 and $0xfffffffffffffff0,%rsp\n 4003ed: 50 push %rax\n 4003ee: 54 push %rsp\n 4003ef: 49 c7 c0 60 05 40 00 mov $0x400560,%r8\n 4003f6: 48 c7 c1 f0 04 40 00 mov $0x4004f0,%rcx\n 4003fd: 48 c7 c7 d6 04 40 00 mov $0x4004d6,%rdi\n 400404: e8 b7 ff ff ff callq 4003c0 \n 400409: f4 hlt \n 40040a: 66 0f 1f 44 00 00 nopw 0x0(%rax,%rax,1)\n" }, { "code": null, "e": 27236, "s": 27171, "text": "As we can clearly see this is pointing to the _start() function." }, { "code": null, "e": 27475, "s": 27236, "text": "The _start() function prepare the input arguments for another function _libc_start_main() which will be called next. This is prototype of _libc_start_main() function. Here we can see the arguments which were prepared by _start() function." }, { "code": "int __libc_start_main(int (*main) (int, char * *, char * *), /* address of main function*/int argc, /* number of command line args*/char ** ubp_av, /* command line arg array*/void (*init) (void), /* address of init function*/void (*fini) (void), /* address of fini function*/void (*rtld_fini) (void), /* address of dynamic linker fini function */void (* stack_end) /* end of the stack address*/);", "e": 27872, "s": 27475, "text": null }, { "code": null, "e": 27927, "s": 27872, "text": "The role of _libc_start_main() function is following –" }, { "code": null, "e": 27981, "s": 27927, "text": "Preparing environment variables for program execution" }, { "code": null, "e": 28068, "s": 27981, "text": "Calls _init() function which performs initialization before the main() function start." }, { "code": null, "e": 29726, "s": 28068, "text": "Register _fini() and _rtld_fini() functions to perform cleanup after program terminatesAfter all the prerequisite actions has been completed, _libc_start_main() calls the main() function.Writing program without main()Now we know how the call to the main() is made.To make it clear, main() is nothing but a agreed term for startup code. We can have any name for startup code it doesn’t necessarily have to be “main”. As _start() function by default calls main(), we have to change it if we want to execute our custom startup code. We can override the _start() function to make it call our custom startup code not main(). Let’s have an example, save it as nomain.c –#include<stdio.h>#include<stdlib.h>void _start(){ int x = my_fun(); //calling custom main function exit(x);} int my_fun() // our custom main function{ printf(\"Hello world!\\n\"); return 0;}Now we have to force compiler to not use it’s own implementation of _start().In GCC we can do this using -nostartfilesgcc -nostartfiles -o nomain nomain.c\nExecute the executable nomain./nomain\nOutput:Hello world!\nReferenceshttp://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.htmlAdvanced C/C++ Compiling by Milan StevanovicThis article is contributed by Atul Kumar. 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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 30174, "s": 29726, "text": "Now we know how the call to the main() is made.To make it clear, main() is nothing but a agreed term for startup code. We can have any name for startup code it doesn’t necessarily have to be “main”. As _start() function by default calls main(), we have to change it if we want to execute our custom startup code. We can override the _start() function to make it call our custom startup code not main(). Let’s have an example, save it as nomain.c –" }, { "code": "#include<stdio.h>#include<stdlib.h>void _start(){ int x = my_fun(); //calling custom main function exit(x);} int my_fun() // our custom main function{ printf(\"Hello world!\\n\"); return 0;}", "e": 30375, "s": 30174, "text": null }, { "code": null, "e": 30494, "s": 30375, "text": "Now we have to force compiler to not use it’s own implementation of _start().In GCC we can do this using -nostartfiles" }, { "code": null, "e": 30532, "s": 30494, "text": "gcc -nostartfiles -o nomain nomain.c\n" }, { "code": null, "e": 30562, "s": 30532, "text": "Execute the executable nomain" }, { "code": null, "e": 30572, "s": 30562, "text": "./nomain\n" }, { "code": null, "e": 30580, "s": 30572, "text": "Output:" }, { "code": null, "e": 30594, "s": 30580, "text": "Hello world!\n" }, { "code": null, "e": 30605, "s": 30594, "text": "References" }, { "code": null, "e": 30676, "s": 30605, "text": "http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html" }, { "code": null, "e": 30721, "s": 30676, "text": "Advanced C/C++ Compiling by Milan Stevanovic" }, { "code": null, "e": 31019, "s": 30721, "text": "This article is contributed by Atul Kumar. 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": 31144, "s": 31019, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31159, "s": 31144, "text": "nikhilnagrale2" }, { "code": null, "e": 31178, "s": 31159, "text": "system-programming" }, { "code": null, "e": 31189, "s": 31178, "text": "C Language" }, { "code": null, "e": 31193, "s": 31189, "text": "C++" }, { "code": null, "e": 31197, "s": 31193, "text": "CPP" }, { "code": null, "e": 31295, "s": 31197, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31333, "s": 31295, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 31353, "s": 31333, "text": "Multithreading in C" }, { "code": null, "e": 31379, "s": 31353, "text": "Exception Handling in C++" }, { "code": null, "e": 31420, "s": 31379, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31442, "s": 31420, "text": "'this' pointer in C++" }, { "code": null, "e": 31460, "s": 31442, "text": "Vector in C++ STL" }, { "code": null, "e": 31506, "s": 31460, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 31525, "s": 31506, "text": "Inheritance in C++" }, { "code": null, "e": 31568, "s": 31525, "text": "Map in C++ Standard Template Library (STL)" } ]
Scala Collections - List
Scala Lists are quite similar to arrays which means, all the elements of a list have the same type but there are two important differences. First, lists are immutable, which means elements of a list cannot be changed by assignment. Second, lists represent a linked list whereas arrays are flat. The type of a list that has elements of type T is written as List[T]. Try the following example, here are few lists defined for various data types. // List of Strings val fruit: List[String] = List("apples", "oranges", "pears") // List of Integers val nums: List[Int] = List(1, 2, 3, 4) // Empty List. val empty: List[Nothing] = List() // Two dimensional list val dim: List[List[Int]] = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) ) All lists can be defined using two fundamental building blocks, a tail Nil and ::, which is pronounced cons. Nil also represents the empty list. All the above lists can be defined as follows. // List of Strings val fruit = "apples" :: ("oranges" :: ("pears" :: Nil)) // List of Integers val nums = 1 :: (2 :: (3 :: (4 :: Nil))) // Empty List. val empty = Nil // Two dimensional list val dim = (1 :: (0 :: (0 :: Nil))) :: (0 :: (1 :: (0 :: Nil))) :: (0 :: (0 :: (1 :: Nil))) :: Nil All operations on lists can be expressed in terms of the following three methods. head This method returns the first element of a list. tail This method returns a list consisting of all elements except the first. isEmpty This method returns true if the list is empty otherwise false. The following example shows how to use the above methods. object Demo { def main(args: Array[String]) { val fruit = "apples" :: ("oranges" :: ("pears" :: Nil)) val nums = Nil println( "Head of fruit : " + fruit.head ) println( "Tail of fruit : " + fruit.tail ) println( "Check if fruit is empty : " + fruit.isEmpty ) println( "Check if nums is empty : " + nums.isEmpty ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo Head of fruit : apples Tail of fruit : List(oranges, pears) Check if fruit is empty : false Check if nums is empty : true You can use either ::: operator or List.:::() method or List.concat() method to add two or more lists. Please find the following example given below − object Demo { def main(args: Array[String]) { val fruit1 = "apples" :: ("oranges" :: ("pears" :: Nil)) val fruit2 = "mangoes" :: ("banana" :: Nil) // use two or more lists with ::: operator var fruit = fruit1 ::: fruit2 println( "fruit1 ::: fruit2 : " + fruit ) // use two lists with Set.:::() method fruit = fruit1.:::(fruit2) println( "fruit1.:::(fruit2) : " + fruit ) // pass two or more lists as arguments fruit = List.concat(fruit1, fruit2) println( "List.concat(fruit1, fruit2) : " + fruit ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo fruit1 ::: fruit2 : List(apples, oranges, pears, mangoes, banana) fruit1.:::(fruit2) : List(mangoes, banana, apples, oranges, pears) List.concat(fruit1, fruit2) : List(apples, oranges, pears, mangoes, banana) You can use List.fill() method creates a list consisting of zero or more copies of the same element. Try the following example program. object Demo { def main(args: Array[String]) { val fruit = List.fill(3)("apples") // Repeats apples three times. println( "fruit : " + fruit ) val num = List.fill(10)(2) // Repeats 2, 10 times. println( "num : " + num ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo fruit : List(apples, apples, apples) num : List(2, 2, 2, 2, 2, 2, 2, 2, 2, 2) You can use a function along with List.tabulate() method to apply on all the elements of the list before tabulating the list. Its arguments are just like those of List.fill: the first argument list gives the dimensions of the list to create, and the second describes the elements of the list. The only difference is that instead of the elements being fixed, they are computed from a function. Try the following example program. object Demo { def main(args: Array[String]) { // Creates 5 elements using the given function. val squares = List.tabulate(6)(n => n * n) println( "squares : " + squares ) val mul = List.tabulate( 4,5 )( _ * _ ) println( "mul : " + mul ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo squares : List(0, 1, 4, 9, 16, 25) mul : List(List(0, 0, 0, 0, 0), List(0, 1, 2, 3, 4), List(0, 2, 4, 6, 8), List(0, 3, 6, 9, 12)) You can use List.reverse method to reverse all elements of the list. The Following example shows the usage. object Demo { def main(args: Array[String]) { val fruit = "apples" :: ("oranges" :: ("pears" :: Nil)) println( "Before reverse fruit : " + fruit ) println( "After reverse fruit : " + fruit.reverse ) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo Before reverse fruit : List(apples, oranges, pears) After reverse fruit : List(pears, oranges, apples) 82 Lectures 7 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 76 Lectures 5.5 hours Bigdata Engineer 69 Lectures 7.5 hours Bigdata Engineer 46 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 3177, "s": 2882, "text": "Scala Lists are quite similar to arrays which means, all the elements of a list have the same type but there are two important differences. First, lists are immutable, which means elements of a list cannot be changed by assignment. Second, lists represent a linked list whereas arrays are flat." }, { "code": null, "e": 3247, "s": 3177, "text": "The type of a list that has elements of type T is written as List[T]." }, { "code": null, "e": 3325, "s": 3247, "text": "Try the following example, here are few lists defined for various data types." }, { "code": null, "e": 3625, "s": 3325, "text": "// List of Strings\nval fruit: List[String] = List(\"apples\", \"oranges\", \"pears\")\n// List of Integers\nval nums: List[Int] = List(1, 2, 3, 4)\n// Empty List.\nval empty: List[Nothing] = List()\n// Two dimensional list\nval dim: List[List[Int]] = List(\n List(1, 0, 0),\n List(0, 1, 0),\n List(0, 0, 1)\n)" }, { "code": null, "e": 3817, "s": 3625, "text": "All lists can be defined using two fundamental building blocks, a tail Nil and ::, which is pronounced cons. Nil also represents the empty list. All the above lists can be defined as follows." }, { "code": null, "e": 4112, "s": 3817, "text": "// List of Strings\nval fruit = \"apples\" :: (\"oranges\" :: (\"pears\" :: Nil))\n// List of Integers\nval nums = 1 :: (2 :: (3 :: (4 :: Nil)))\n// Empty List.\nval empty = Nil\n// Two dimensional list\nval dim = (1 :: (0 :: (0 :: Nil))) ::\n (0 :: (1 :: (0 :: Nil))) ::\n (0 :: (0 :: (1 :: Nil))) :: Nil" }, { "code": null, "e": 4194, "s": 4112, "text": "All operations on lists can be expressed in terms of the following three methods." }, { "code": null, "e": 4199, "s": 4194, "text": "head" }, { "code": null, "e": 4248, "s": 4199, "text": "This method returns the first element of a list." }, { "code": null, "e": 4253, "s": 4248, "text": "tail" }, { "code": null, "e": 4325, "s": 4253, "text": "This method returns a list consisting of all elements except the first." }, { "code": null, "e": 4333, "s": 4325, "text": "isEmpty" }, { "code": null, "e": 4396, "s": 4333, "text": "This method returns true if the list is empty otherwise false." }, { "code": null, "e": 4454, "s": 4396, "text": "The following example shows how to use the above methods." }, { "code": null, "e": 4813, "s": 4454, "text": "object Demo {\n def main(args: Array[String]) {\n val fruit = \"apples\" :: (\"oranges\" :: (\"pears\" :: Nil))\n val nums = Nil\n println( \"Head of fruit : \" + fruit.head )\n println( \"Tail of fruit : \" + fruit.tail )\n println( \"Check if fruit is empty : \" + fruit.isEmpty )\n println( \"Check if nums is empty : \" + nums.isEmpty )\n }\n}" }, { "code": null, "e": 4920, "s": 4813, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 4954, "s": 4920, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 5077, "s": 4954, "text": "Head of fruit : apples\nTail of fruit : List(oranges, pears)\nCheck if fruit is empty : false\nCheck if nums is empty : true\n" }, { "code": null, "e": 5229, "s": 5077, "text": "You can use either ::: operator or List.:::() method or List.concat() method to add two or more lists. Please find the following example given below −" }, { "code": null, "e": 5804, "s": 5229, "text": "object Demo {\n def main(args: Array[String]) {\n val fruit1 = \"apples\" :: (\"oranges\" :: (\"pears\" :: Nil))\n val fruit2 = \"mangoes\" :: (\"banana\" :: Nil)\n // use two or more lists with ::: operator\n var fruit = fruit1 ::: fruit2\n println( \"fruit1 ::: fruit2 : \" + fruit )\n // use two lists with Set.:::() method\n fruit = fruit1.:::(fruit2)\n println( \"fruit1.:::(fruit2) : \" + fruit )\n // pass two or more lists as arguments\n fruit = List.concat(fruit1, fruit2)\n println( \"List.concat(fruit1, fruit2) : \" + fruit )\n }\n}" }, { "code": null, "e": 5911, "s": 5804, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 5945, "s": 5911, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 6155, "s": 5945, "text": "fruit1 ::: fruit2 : List(apples, oranges, pears, mangoes, banana)\nfruit1.:::(fruit2) : List(mangoes, banana, apples, oranges, pears)\nList.concat(fruit1, fruit2) : List(apples, oranges, pears, mangoes, banana)\n" }, { "code": null, "e": 6291, "s": 6155, "text": "You can use List.fill() method creates a list consisting of zero or more copies of the same element. Try the following example program." }, { "code": null, "e": 6554, "s": 6291, "text": "object Demo {\n def main(args: Array[String]) {\n val fruit = List.fill(3)(\"apples\") // Repeats apples three times.\n println( \"fruit : \" + fruit )\n val num = List.fill(10)(2) // Repeats 2, 10 times.\n println( \"num : \" + num )\n }\n}" }, { "code": null, "e": 6661, "s": 6554, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 6695, "s": 6661, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 6774, "s": 6695, "text": "fruit : List(apples, apples, apples)\nnum : List(2, 2, 2, 2, 2, 2, 2, 2, 2, 2)\n" }, { "code": null, "e": 7167, "s": 6774, "text": "You can use a function along with List.tabulate() method to apply on all the elements of the list before tabulating the list. Its arguments are just like those of List.fill: the first argument list gives the dimensions of the list to create, and the second describes the elements of the list. The only difference is that instead of the elements being fixed, they are computed from a function." }, { "code": null, "e": 7202, "s": 7167, "text": "Try the following example program." }, { "code": null, "e": 7487, "s": 7202, "text": "object Demo {\n def main(args: Array[String]) {\n // Creates 5 elements using the given function.\n val squares = List.tabulate(6)(n => n * n)\n println( \"squares : \" + squares )\n val mul = List.tabulate( 4,5 )( _ * _ ) \n println( \"mul : \" + mul )\n }\n}" }, { "code": null, "e": 7594, "s": 7487, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 7628, "s": 7594, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 7764, "s": 7628, "text": "squares : List(0, 1, 4, 9, 16, 25)\nmul : List(List(0, 0, 0, 0, 0), List(0, 1, 2, 3, 4), \n List(0, 2, 4, 6, 8), List(0, 3, 6, 9, 12))\n" }, { "code": null, "e": 7872, "s": 7764, "text": "You can use List.reverse method to reverse all elements of the list. The Following example shows the usage." }, { "code": null, "e": 8099, "s": 7872, "text": "object Demo {\n def main(args: Array[String]) {\n val fruit = \"apples\" :: (\"oranges\" :: (\"pears\" :: Nil))\n println( \"Before reverse fruit : \" + fruit )\n println( \"After reverse fruit : \" + fruit.reverse )\n }\n}" }, { "code": null, "e": 8206, "s": 8099, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 8240, "s": 8206, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 8344, "s": 8240, "text": "Before reverse fruit : List(apples, oranges, pears)\nAfter reverse fruit : List(pears, oranges, apples)\n" }, { "code": null, "e": 8377, "s": 8344, "text": "\n 82 Lectures \n 7 hours \n" }, { "code": null, "e": 8396, "s": 8377, "text": " Arnab Chakraborty" }, { "code": null, "e": 8431, "s": 8396, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8452, "s": 8431, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 8487, "s": 8452, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8505, "s": 8487, "text": " Bigdata Engineer" }, { "code": null, "e": 8540, "s": 8505, "text": "\n 76 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8558, "s": 8540, "text": " Bigdata Engineer" }, { "code": null, "e": 8593, "s": 8558, "text": "\n 69 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8611, "s": 8593, "text": " Bigdata Engineer" }, { "code": null, "e": 8646, "s": 8611, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8669, "s": 8646, "text": " Stone River ELearning" }, { "code": null, "e": 8676, "s": 8669, "text": " Print" }, { "code": null, "e": 8687, "s": 8676, "text": " Add Notes" } ]
wxPython - Destroy button widget using Destroy() function - GeeksforGeeks
26 Jun, 2020 In this article we will learn that, how can we destroy a button widget from a window using Destroy() function in wx.Button class of wxPython. Destroy() function is used to simply destroy a window or widget safely.Destroy() returns True if the window has either been successfully deleted, or it has been added to the list of windows pending real deletion. Syntax: wx.StaticText.Destroy(self) Parameters: Destroy() function takes no arguments. Return Type: bool Returns: True if the window has either been successfully deleted, or it has been added to the list of windows pending real deletion. Code Example: import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) # create parent panel self.pnl = wx.Panel(self) # create a button at point (20, 50) self.btn1 = wx.Button(self.pnl, id = 1, label ="Remove Text", pos =(20, 50)) # create button to destroy self.btn0 = wx.Button(self.pnl, id = 1, label ="Click button to remove", pos =(20, 20)) # bind Onclick() function with button self.btn1.Bind(wx.EVT_BUTTON, self.Onclick) self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def Onclick(self, e): # destroy btn0 button self.btn0.Destroy() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main() Output Window:before Destroy() after Destroy() Python wxPython-Button Python-gui Python-wxPython 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 Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23901, "s": 23873, "text": "\n26 Jun, 2020" }, { "code": null, "e": 24256, "s": 23901, "text": "In this article we will learn that, how can we destroy a button widget from a window using Destroy() function in wx.Button class of wxPython. Destroy() function is used to simply destroy a window or widget safely.Destroy() returns True if the window has either been successfully deleted, or it has been added to the list of windows pending real deletion." }, { "code": null, "e": 24292, "s": 24256, "text": "Syntax: wx.StaticText.Destroy(self)" }, { "code": null, "e": 24343, "s": 24292, "text": "Parameters: Destroy() function takes no arguments." }, { "code": null, "e": 24361, "s": 24343, "text": "Return Type: bool" }, { "code": null, "e": 24494, "s": 24361, "text": "Returns: True if the window has either been successfully deleted, or it has been added to the list of windows pending real deletion." }, { "code": null, "e": 24508, "s": 24494, "text": "Code Example:" }, { "code": "import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) # create parent panel self.pnl = wx.Panel(self) # create a button at point (20, 50) self.btn1 = wx.Button(self.pnl, id = 1, label =\"Remove Text\", pos =(20, 50)) # create button to destroy self.btn0 = wx.Button(self.pnl, id = 1, label =\"Click button to remove\", pos =(20, 20)) # bind Onclick() function with button self.btn1.Bind(wx.EVT_BUTTON, self.Onclick) self.SetSize((350, 250)) self.SetTitle('wx.Button') self.Centre() def Onclick(self, e): # destroy btn0 button self.btn0.Destroy() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 25465, "s": 24508, "text": null }, { "code": null, "e": 25496, "s": 25465, "text": "Output Window:before Destroy()" }, { "code": null, "e": 25512, "s": 25496, "text": "after Destroy()" }, { "code": null, "e": 25535, "s": 25512, "text": "Python wxPython-Button" }, { "code": null, "e": 25546, "s": 25535, "text": "Python-gui" }, { "code": null, "e": 25562, "s": 25546, "text": "Python-wxPython" }, { "code": null, "e": 25569, "s": 25562, "text": "Python" }, { "code": null, "e": 25667, "s": 25569, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25676, "s": 25667, "text": "Comments" }, { "code": null, "e": 25689, "s": 25676, "text": "Old Comments" }, { "code": null, "e": 25725, "s": 25689, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25748, "s": 25725, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25787, "s": 25748, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25820, "s": 25787, "text": "Python | Convert set into a list" }, { "code": null, "e": 25869, "s": 25820, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 25910, "s": 25869, "text": "Python - Call function from another file" }, { "code": null, "e": 25926, "s": 25910, "text": "loops in python" }, { "code": null, "e": 25977, "s": 25926, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 26009, "s": 25977, "text": "Python Dictionary keys() method" } ]
Insert Euro and Dollar symbol to a column in MySQL?
For this, use CASE statement with UPDATE command. Let us first create a table − mysql> create table DemoTable1874 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Amount varchar(100) ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1874(Amount) values('3450'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1874(Amount) values('190'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1874(Amount) values('7600'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1874(Amount) values('4500'); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1874; This will produce the following output − +----+--------+ | Id | Amount | +----+--------+ | 1 | 3450 | | 2 | 190 | | 3 | 7600 | | 4 | 4500 | +----+--------+ 4 rows in set (0.00 sec) Here is the query to insert Euro and Dollar symbol to a column in MySQL − mysql> UPDATE DemoTable1874 SET Amount= CASE WHEN Id = 1 THEN Concat('$','',Amount) WHEN Id = 3 THEN Concat('€','',Amount) else Amount END ; Query OK, 2 rows affected (0.00 sec) Rows matched: 4 Changed: 2 Warnings: 0 Let us check the table records once again − mysql> select * from DemoTable1874; This will produce the following output − +----+---------+ | Id | Amount | +----+---------+ | 1 | $3450 | | 2 | 190 | | 3 | €7600 | | 4 | 4500 | +----+---------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1142, "s": 1062, "text": "For this, use CASE statement with UPDATE command. Let us first create a table −" }, { "code": null, "e": 1294, "s": 1142, "text": "mysql> create table DemoTable1874\n (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n Amount varchar(100)\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1350, "s": 1294, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1721, "s": 1350, "text": "mysql> insert into DemoTable1874(Amount) values('3450');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1874(Amount) values('190');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1874(Amount) values('7600');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1874(Amount) values('4500');\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1781, "s": 1721, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1817, "s": 1781, "text": "mysql> select * from DemoTable1874;" }, { "code": null, "e": 1858, "s": 1817, "text": "This will produce the following output −" }, { "code": null, "e": 2011, "s": 1858, "text": "+----+--------+\n| Id | Amount |\n+----+--------+\n| 1 | 3450 |\n| 2 | 190 |\n| 3 | 7600 |\n| 4 | 4500 |\n+----+--------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2085, "s": 2011, "text": "Here is the query to insert Euro and Dollar symbol to a column in MySQL −" }, { "code": null, "e": 2336, "s": 2085, "text": "mysql> UPDATE DemoTable1874 SET Amount=\n CASE\n WHEN Id = 1 THEN Concat('$','',Amount)\n WHEN Id = 3 THEN Concat('€','',Amount)\n else\n Amount\n END\n ;\nQuery OK, 2 rows affected (0.00 sec)\nRows matched: 4 Changed: 2 Warnings: 0" }, { "code": null, "e": 2380, "s": 2336, "text": "Let us check the table records once again −" }, { "code": null, "e": 2416, "s": 2380, "text": "mysql> select * from DemoTable1874;" }, { "code": null, "e": 2457, "s": 2416, "text": "This will produce the following output −" }, { "code": null, "e": 2618, "s": 2457, "text": "+----+---------+\n| Id | Amount |\n+----+---------+\n| 1 | $3450 |\n| 2 | 190 |\n| 3 | €7600 |\n| 4 | 4500 |\n+----+---------+\n4 rows in set (0.00 sec)" } ]
Drupal - Quick Guide
Drupal is a free and open source Content Management System (CMS) that allows organizing, managing and publishing your content. It is built on PHP based environments. This is carried out under GNU i.e. General Public License, which means everyone has the freedom of downloading and sharing it with others. Drupal is used on million sites such as WhiteHouse.gov, World Economic Forum, Stanford University, Examiner.com and many more. The Content Management System (CMS) is a software which stores all the data of your content (such as text, photos, music, documents, etc.) and is made available on your website. A CMS helps in editing, publishing and modifying the content of the website. The standard release of Drupal known as Drupal core was developed by Dries Buytaerti in January 2001. It is considered as a leading CMS in variety of industries. If you are developing a website with content management system, Drupal CMS is very flexible than any other CMS. Drupal is very powerful and can be used for building large, complex sites. It is PHP based template and allows non-technical users to add and edit the content without any HTML or Web design knowledge. Using Drupal CMS, it is easy to interact with other sites or technologies as Drupal can handle complex forms and workflows. It is available with more than 16000 modules which can be addressed with Drupal core and add-on modules. Drupal makes it easy to create and manage your site. Drupal makes it easy to create and manage your site. Drupal translates anything in the system with built-in user interfaces. Drupal translates anything in the system with built-in user interfaces. Drupal connects your website to other sites and services using feeds, search engine connection capabilities, etc. Drupal connects your website to other sites and services using feeds, search engine connection capabilities, etc. Drupal is an open source software hence requires no licensing costs. Drupal is an open source software hence requires no licensing costs. Drupal designs highly flexible and creative website with effective display quality thus increasing the visitors to the site. Drupal designs highly flexible and creative website with effective display quality thus increasing the visitors to the site. Drupal can publish your content on social media such as Twitter, Facebook and other social mediums. Drupal can publish your content on social media such as Twitter, Facebook and other social mediums. Drupal provides more number of customizable themes, including several base themes which are used to design your own themes for developing web applications. Drupal provides more number of customizable themes, including several base themes which are used to design your own themes for developing web applications. Drupal manages content on informational sites, social media sites, member sites, intranets and web applications. Drupal manages content on informational sites, social media sites, member sites, intranets and web applications. Drupal is a flexible CMS that allows handling content types including video, text, blog, menu handling, real-time statistics, etc. Drupal is a flexible CMS that allows handling content types including video, text, blog, menu handling, real-time statistics, etc. Drupal provides a number of templates for developing web applications. There is no need to start from scratch if you are building simple or complicated web applications. Drupal provides a number of templates for developing web applications. There is no need to start from scratch if you are building simple or complicated web applications. Drupal is easy to manage or create blog or website. It helps to organize, structure, find and reuse content. Drupal is easy to manage or create blog or website. It helps to organize, structure, find and reuse content. Drupal provides some interesting themes and templates which gives your website an attractive look. Drupal provides some interesting themes and templates which gives your website an attractive look. Drupal has over 7000 plug-ins to boost your website. Since Drupal is an open source, you can create your own plug-ins. Drupal has over 7000 plug-ins to boost your website. Since Drupal is an open source, you can create your own plug-ins. Drupal is not a user-friendly interface. It requires advanced knowledge and few basic things about the platform to install and modify. Drupal is not a user-friendly interface. It requires advanced knowledge and few basic things about the platform to install and modify. Drupal is a new content management system. It is not compatible with other software. Drupal is a new content management system. It is not compatible with other software. Performance is low compared to other CMS. The website which is built using Drupal will generate big server loads and will never open with a slow internet connection. Performance is low compared to other CMS. The website which is built using Drupal will generate big server loads and will never open with a slow internet connection. This chapter provides step-by-step procedure for Drupal installation. Before installing Drupal, the following system requirements are necessary. Database − MySQL 5.1 + Database − MySQL 5.1 + Web Server − WAMP (Windows) LAMP (Linux) XAMP (Multi-platform) MAMP (Macintosh) Nginx Microsoft IIS Web Server − WAMP (Windows) WAMP (Windows) LAMP (Linux) LAMP (Linux) XAMP (Multi-platform) XAMP (Multi-platform) MAMP (Macintosh) MAMP (Macintosh) Nginx Nginx Microsoft IIS Microsoft IIS Operating System − Cross-platform Operating System − Cross-platform Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera SSL (Secure Socket Layer) − A valid security certificate is required for HTTPS SSL (Secure Socket Layer) − A valid security certificate is required for HTTPS PHP Compatibility − PHP 5.2+ PHP Compatibility − PHP 5.2+ Step 1 − Download the Drupal and copy to your web server from this link − https://www.drupal.org/project/drupal Step 2 − Select the latest version of zip file which you want to download as shown in the following screen. The Recommended releases are the latest stable releases of either version. It's very easy to setup Drupal on your system. The following steps describe how to setup Drupal locally on your system. Step 1 − Download the zip file and extract it to your local computer. Rename the folder from its current name to any name of your choice to refer to your site. Step 2 − Drupal requires MySQL database. Create a new empty database with user/password for Drupal to use. (For e.g., user as "root" and password as "root" or else you can set as per your choice). Step 3 − Open your browser and navigate to your Drupal file path, you will see the first Drupal installer screen as shown in the following image. In our case the path is localhost/< Your_drupal_folder >. Select the Standard option and click Save and continue. Step 4 − Select the default language for Drupal website. After selecting the language, click Save and continue. Step 5 − Go to Database configuration page. You need to enter the type of database you will be using, and other details as follows. Database Type − Select the database type. By default, it will be MySQL. Database Type − Select the database type. By default, it will be MySQL. Database name − Enter the database name for Drupal. Database name − Enter the database name for Drupal. Database username − Enter the user name of your MySQL database. Database username − Enter the user name of your MySQL database. Database password − Enter the password which you had set for MySQL Database. Database password − Enter the password which you had set for MySQL Database. When you click the ADVANCED OPTIONS, you will see the following screen − You can fill the advanced options for the database − Database Host − Enter the host name where your database is located. Database Host − Enter the host name where your database is located. Database port − Enter the database port. Database port − Enter the database port. Table Prefix − It is used to add prefix in the database tables, which helps to run multiple sites on the same database. Table Prefix − It is used to add prefix in the database tables, which helps to run multiple sites on the same database. After filling all the information, click the Save and continue button. Step 6 − The installation process starts on your machine. Step 7 − The Configure site page appears on the screen − It contains the following fields − Site name − The name that you want to give to your site. Site name − The name that you want to give to your site. Site e-mail address − The e-mail address to which automated e-mails will be sent. Site e-mail address − The e-mail address to which automated e-mails will be sent. Username, Email-address and Password − These are all administrative details used for the maintenance account. Username, Email-address and Password − These are all administrative details used for the maintenance account. You need to enter all these fields and click Save and continue. Step 8 − The following page indicating that your Drupal installation is successful will appear on your screen. Step 9 − Click the Visit your new site link as shown in this image. Step 10 − Finally, the newly installed Drupal homepage appears on your screen as seen in the preceding image. Drupal is a platform for web content management which is a powerful tool for building simple and complex sites. In this chapter, we are going to discuss the architectural style of Drupal for implementing user interfaces. The following diagram shows the architecture of Drupal − The architecture of Drupal contains the following layers &miuns; Users Users Administrator Administrator Drupal Drupal PHP PHP Web Server Web Server Database Database Users − These are the users on the Drupal community. The user sends a request to a server using Drupal CMS and web browsers, search engines, etc. acts like clients. Administrator − Administrator can provide access permission to authorized users and will be able to block unauthorized access. Administrative account will be having all privileges for managing content and administering the site. Drupal − Drupal is a free and open source Content Management System (CMS) that allows organizing, managing and publishing your content and is built on PHP based environments. Drupal CMS is very flexible and powerful and can be used for building large, complex sites. It is very easy to interact with other sites and technologies using Drupal CMS. Further, you will be able to handle complex forms and workflows. PHP − Drupal uses PHP in order to work with an application which is created by a user. It takes the help of web server to fetch data from the database. PHP memory requirements depend on the modules which are used in your site. Drupal 6 requires at least 16MB, Drupal 7 requires 32MB and Drupal 8 requires 64MB. Web Server − Web server is a server where the user interacts and processes requests via HTTP (Hyper Text Transfer Protocol) and serves files that form web pages to web users. The communication between the user and the server takes place using HTTP. You can use different types of web servers such as Apache, IIS, Nginx, Lighttpd, etc. Database − Database stores the user information, content and other required data of the site. It is used to store the administrative information to manage the Drupal site. Drupal uses the database to extract the data and enables to store, modify and update the database. In this chapter, we will study how to Create Menus in Drupal. Menus are very important to easily navigate in your website. Menus offer a set of links that helps you navigate. The Drupal menu allows you to add, remove and rename the menus and menu items. Following are the simple steps to create menus in Drupal. Step 1 − Click Structure → Menus as shown in the following screen. Step 2 − Click on Add menu option to add menu. Step 3 − Fill in the required details as shown in the following screen. Title − It displays title in the Administrator Menu bar. Title − It displays title in the Administrator Menu bar. Description − Enter a brief description about the menu. The description field will display only in the admin dashboard under the menu list, but it does not display any information to site visitors. Description − Enter a brief description about the menu. The description field will display only in the admin dashboard under the menu list, but it does not display any information to site visitors. After filling all the information about the menu, click on Save button to save your created menu bar. Step 4 − Once you save the menu bar, the following screen will get displayed. Here you have to define the path link to your created menu page. Click Add link as shown in the following screen. Step 5 − The created Menu 1 page gets displayed as shown in the following screen. It contains below fields − Menu link title− Specify the name of the menu item. Menu link title− Specify the name of the menu item. Path − Specify the URL path of the page which you want to display. Path − Specify the URL path of the page which you want to display. Description − Description about the menu link. Description − Description about the menu link. Enabled − It enables the item to display on menu. Enabled − It enables the item to display on menu. Show as expanded − If it consists of sub menus, then it will be displayed under the parent menu item. Show as expanded − If it consists of sub menus, then it will be displayed under the parent menu item. Parent Link − It sets the main structure of menu. Parent Link − It sets the main structure of menu. Weight − Sets the order of menu items. Weight − Sets the order of menu items. After filling all the information about the menu link, click the Save button, this will save your Menu link. Step 6− Now the following screen pops up. Step 7 − Click Structure → Menus to get the following screen. Here, you will see the created Menu 1 name in the list of Menus. In this chapter, we will study about Drupal Blocks & Regions. Blocks are container objects that are used to organize your content of your website. It can be displayed in the regions on your page. Following are the simple steps for creating Drupal Blocks. Step 1 − Click Structure in Drupal as shown in the following screen. Step 2 − Then, click Blocks. Step 3 − Blocks page gets displayed. Click Add block. Step 4 − A block page will gets displayed to create a new custom block as shown in the following screen. The following fields appear on the Blocks page. Block Settings Block Settings Block title − Enter the title for your block. Block title − Enter the title for your block. Block description − Enter the description about block. Block description − Enter the description about block. Block body − Enter the content of the block. Block body − Enter the content of the block. Text format − Select the format for your text i.e. Filtered HTML, Full HTML, and Plain text. Text format − Select the format for your text i.e. Filtered HTML, Full HTML, and Plain text. Region Settings Region Settings Bartik (default theme) − Select the region to display block in the theme. Bartik (default theme) − Select the region to display block in the theme. Seven (administration theme) − Select the region to display block in the administration theme. Seven (administration theme) − Select the region to display block in the administration theme. Visibility Setting Visibility Setting Page − Allows displaying blocks on all or specific pages. Page − Allows displaying blocks on all or specific pages. Content Types − Allows to display the blocks in specific content, i.e. Article or Basic Page. Content Types − Allows to display the blocks in specific content, i.e. Article or Basic Page. Roles − Allows displaying the blocks for specific types of users, i.e. anonymous user, authenticated user, or administrator user. Roles − Allows displaying the blocks for specific types of users, i.e. anonymous user, authenticated user, or administrator user. Users − Allows each user to customize the visibility of block in their settings. Users − Allows each user to customize the visibility of block in their settings. Now, click the Save block after filling all the fields. Step 5 − You can view the created block as shown in the following screen. In this chapter, let us study about Themes and Layouts. Drupal will install Bartik theme as default theme during installation. You can select paid or free themes from Drupal official site. In general, layout is an arrangement of text and graphics. It is a good thought to choose a theme, keeping in mind what different layouts to use on your site. Step 1 − Go to Drupal official site and click Get Started. Step 2 − Click on All Themes as shown in the following screen. Step 3 − You will get a list of themes. Select theme of your choice (let us select Adaptive theme as it consists Layout & General Settings, which will be covered later in this chapter) and click Version as shown in the following screen. Step 4 − Next, right click Download file and copy the link address as shown in the following screen. Step 5 − You can also download the theme directly by clicking on archive file and the module will be downloaded locally on your computer as shown in the following screen. Step 6 − Go to Appearance and click Install new theme as shown in the following screen. Step 7 − You can paste the link address you copied in step (4) and click the install button as shown in the following screen. Step 8 − You can also upload the theme archive, instead of copying the link address, if you have downloaded it and click Install as shown in the following screen. Step 9 − The following screen appears, wait until installation completes. Step 10 − Next, click Enable newly added themes as shown in the following screen. Step 11 − By default the themes are disabled. To enable them, click Enable and set default as shown in the following screen. Step 12 − Click on Settings as shown in the following screen to set the appearance for your site. Step 13 − The Layout & General Settings option pops up on the screen, in this Adaptive theme consists of Standard layout, Tablet Layout, Smalltouch layout and Panels & Gpanels. These options control the display settings for the current AT Admin theme that is already in use. When your site displays the theme, these settings will be used. Now, let us discuss these layouts one by one. Step 14 − In Standard layout you can choose layout for desktops, laptops and other large screen devices. Choose sidebar positions − You can choose sidebar position by clicking on radio button. Choose sidebar positions − You can choose sidebar position by clicking on radio button. Set the width of each sidebar − You can set width of first sidebar and second sidebar and unit in % or px or em. Set the width of each sidebar − You can set width of first sidebar and second sidebar and unit in % or px or em. Set the page width − You can set width of the page. Set the page width − You can set width of the page. Set a max width −You can check or uncheck to set maximum width. Set a max width −You can check or uncheck to set maximum width. Media query for this layout − Media query defines different style rules for different media devices and by default for this layout will be 1025px. Media query for this layout − Media query defines different style rules for different media devices and by default for this layout will be 1025px. Step 15 − Next, click Tablet Layout as shown in the following screen. Tablet devices will have two orientations Landscape and Portrait. You can configure a different layout for each orientation. Under Landscape tablet and Portrait tablet you can choose sidebar position, width of each sidebar and page width. Media query for Landscape tablet will be min-width:769px and max-width:1024px. For Portrait tablet it will be min-width:581px and max-width:768px Step 16 − Now, click Smalltouch Layout as shown in the following screen. Smalltouch layout will also have two orientations Landscape and Portrait. You can configure a different layout for each orientation. In Landscape Smalltouch you can choose sidebar position and set width. The Portrait Smalltouch always displays in one column with sidebars stacked horizontally below the main content. Media query for Landscape Smalltouch will be min-width:321px and max-width:580px and for Portrait Smalltouch it will be max-width:320px. Step 17 − Next, click Panels & Gpanels as shown in the following screen. Adaptive theme supports responsive Panels and Gpanel layouts. To use this capability, you can use the Panels module, Display Suite (with Panels) or Adaptive themes native Gpanels layouts. You can select options for each device range and layout their type. Let us see one by one. Under Standard layout you can select the layouts you want to use when the site is being viewed in standard layout. By clicking on TWO, THREE, FOUR, FIVE, SIX or INSET, you can select the columns arrangement as shown in the following screen. Under Standard layout you can select the layouts you want to use when the site is being viewed in standard layout. By clicking on TWO, THREE, FOUR, FIVE, SIX or INSET, you can select the columns arrangement as shown in the following screen. Follow the same step for TABLET LANDSCAPE, TABLET PORTRAIT and SMALLTOUCH LANDSCAPE layouts. Follow the same step for TABLET LANDSCAPE, TABLET PORTRAIT and SMALLTOUCH LANDSCAPE layouts. Step 18 − Once done with all your configurations, click Save configurations as shown in the following screen. In this chapter, let us study how to create Front Page in Drupal. If you have good content on your website and expect your visitor to see that particular content first, then that article must be on the front page. Drupal provides solution for this. Following are the simple steps used for creating Drupal Front Page. Step 1 − Click Content as shown in the following screen. Step 2 − A list of articles and pages pop up on screen. Click edit link as shown in the following screen. Step 3 − Then, click Publishing option and check mark all the boxes as shown in the following screen. Following are the functions of the checkboxes on the page − Published − Publish your page or article by marking the check box Published − Publish your page or article by marking the check box Promoted to front page− Promote your page or article, to the front page of your website. Promoted to front page− Promote your page or article, to the front page of your website. Sticky at top of lists− Fixes your page at top of lists on your site. Sticky at top of lists− Fixes your page at top of lists on your site. Click the Save button to save the changes. Step 4− You will see your page on the front page of your website similar to the following screen. In this chapter, we will study about how to create Static Pages in Drupal. Let's add some static pages named About Us and Services. The main purpuse for using a static pages is speed and steadiness. Static websites are more faster than a dynamic site. Following are the simple steps to create static page. Step 1 − Click Content --> Add content link. Step 2 − Click on Basic pages. Step 3 − Create basic page will get displayed as shown in the following screen. Following are the details of the fields present in the above screen. Title − It specifies the title of the static page. Title − It specifies the title of the static page. Body − It displays the body content of the page. Body − It displays the body content of the page. URL path settings − You can specify alternative URL by which content can be accessed. URL path settings − You can specify alternative URL by which content can be accessed. Note − Don't add slash at the end or beginning of the URL alias or else it will not work. You can see about-us URL path has been added under URL alias heading. The process is same for both About Us and Services static pages, only the content will be changed as per the demand. You can click Publishing options and check the box of published option to publish your page. Step 4 − Click on About Us tab, you will see the created about us page as shown in the following screen. Step 5 − Click the Services tab, you will see the created services page as shown in the following screen. In this chapter, we will study how to Create Blogs in Drupal. Blog entries can be made public or private, for the site members, depending on which roles have access to view content. Following are the simple steps used for creating Drupal Blogs. Step 1 − Click on the Modules as shown in the following screen. Step 2 − Next, Check the box of Blog to install it. Enable the Blog module and click Save configuration as shown in the following screen. Step 3 − Now, click Content as shown in the following screen. Step 4 − Click on Add content. Step 5 − Click on Blog entry. Step 6 − You can add the content to blog as shown in the following screen and click Save. Following are the details about the fields present in the preceding screen. Title − It displays the title of the blog. Title − It displays the title of the blog. Body − It displays the content of the body. Body − It displays the content of the body. Publishing options − It allows you to publish your blog content on Front Page or you can stick at top of lists as per the demand. Publishing options − It allows you to publish your blog content on Front Page or you can stick at top of lists as per the demand. Step 7 − Once you are done, you will see your post on home page. In this chapter, we will study about creating articles in Drupal. Creating articles help your visitors know about the company and your website in detail. Following are the steps used to create articles in Drupal. Step 1 − Click Add content in Drupal. Step 2 − You will get the pop-up window as shown in the following screen. Select Article. Step 3 − You will get the following screen. Below are the fields present in Create Article page. Title − It specifies the title for new article. Title − It specifies the title for new article. Tags − Describes the content of your article. Tags contain those related words which are included into your articles. Tags − Describes the content of your article. Tags contain those related words which are included into your articles. Body − Enter the description. Body − Enter the description. Text format − It specifies the Text format such as Filtered HTML, Full HTML and Plain text. Text format − It specifies the Text format such as Filtered HTML, Full HTML and Plain text. Image − Upload images by choosing a particular file. Image − Upload images by choosing a particular file. When you click choose file, a pop-up window appears, you can select an image from your local file, once you choose a file, click Upload. The image gets uploaded. Menu settings − By clicking on Provide a menu link checkbox it shows all the related details of Menu such as Menu link title, Description, Parent item, and Weight. Menu settings − By clicking on Provide a menu link checkbox it shows all the related details of Menu such as Menu link title, Description, Parent item, and Weight. Revision information − Provides revised information if any changes are made in the article. Revision information − Provides revised information if any changes are made in the article. URL path settings − Add URL alias to access the content of article to the users. URL path settings − Add URL alias to access the content of article to the users. Comment settings − By selecting open or close, it allows others to write comment for the article. Comment settings − By selecting open or close, it allows others to write comment for the article. Authoring information − Specifies the authored name and the date when article has been authored. Authoring information − Specifies the authored name and the date when article has been authored. Publishing options − Allows options for articles to be Published, Promoted to front page and Sticky at top of lists for the users. Publishing options − Allows options for articles to be Published, Promoted to front page and Sticky at top of lists for the users. After filling all the details about the article, click the Save button. In this chapter, we will study about how to Create Pages in Drupal. It is very easy to create pages in Drupal. Following are the simple steps used to create pages in Drupal. Step 1 − Click Content in the top menu. Step 2− Click on Add content as shown in the following screen. Step 3− Click the Basic page option. Step 4− Create Basic page will get displayed where you need to fill all the required details as shown in the following screen. Following are the details of the fields present on Create Basic page. Title − It specifies the title for new page. Title − It specifies the title for new page. Body − It specifies the description of the page. Body − It specifies the description of the page. Text format − It specifies the Text format for your page such as Filtered HTML, Full HTML, and Plain text. Text format − It specifies the Text format for your page such as Filtered HTML, Full HTML, and Plain text. Menu settings − By clicking on checkbox Provide a menu link, it shows the details of Menu such as Menu link title, Description, Parent item, and Weight. Menu settings − By clicking on checkbox Provide a menu link, it shows the details of Menu such as Menu link title, Description, Parent item, and Weight. Revision information − It specifies to provide revise information, if any changes are made in the pages. Revision information − It specifies to provide revise information, if any changes are made in the pages. URL path settings − It specifies to add URL alias to access the content of pages to the users. URL path settings − It specifies to add URL alias to access the content of pages to the users. Comment settings − By selecting open or close, it allows displaying a comment box for the page. Comment settings − By selecting open or close, it allows displaying a comment box for the page. Authoring information − It specifies the authored name and the date when page has been authored. Authoring information − It specifies the authored name and the date when page has been authored. Publishing options − It specifies that the page should be Published, Promoted to front page and Sticky at top of lists for the users. Publishing options − It specifies that the page should be Published, Promoted to front page and Sticky at top of lists for the users. Once you complete adding the content to the page. Click the Save button to create the page. Before saving the details, you can also preview the filled page using the Preview button. In this chapter, let us study about Creating content. In Drupal, content type defines the style in which contents are collected and displayed. When you install Drupal, by default two content types will be fixed and they are Articles and Basic page. When you enable other core and contributed modules by visiting Modules you can also use other content types. Following are the simple steps used for creating content. Step 1 − Click Content as shown in the following screen. Step 2 − Click on Add content as shown in the following screen. Step 3 − You can choose any of the content type. We shall take Basic page as we have already studied about Articles and Blog entry. Click Basic page as shown below in the following screen. Step 4 − Next, you will see the screen as shown in the following screen. You can add content to the page and click the Save button to save the content. Following are the details about the fields present in the preceding screen. Title − It specifies the title of the page. Title − It specifies the title of the page. Body − Write the content of your page. Body − Write the content of your page. Menu setting − It allows you to provide a menu link. Menu setting − It allows you to provide a menu link. Revision Information It provides an explanation of the changes you are making. Revision Information It provides an explanation of the changes you are making. URL path settings − It allows you to optionally define an alternative URL, by which your content can be accessed. URL path settings − It allows you to optionally define an alternative URL, by which your content can be accessed. Comment Setting − It allows users to send their comments depending upon the permission you set that is Open or closed. Comment Setting − It allows users to send their comments depending upon the permission you set that is Open or closed. Authorizing information − It specifies the author information. Authorizing information − It specifies the author information. Publishing options − It permits you to promote your content to the front page and stick your content on top of the list on the front page. Publishing options − It permits you to promote your content to the front page and stick your content on top of the list on the front page. Step 5 − Finally, you can see your page will be created and displayed similar to the following screen. In this chapter, let us study how to Modify content in Drupal. You can modify any of the previously used content type's content such as Articles, Basic page and Blog entry. Following are the simple steps used for modifying content. Step 1 − Click the tab Content as shown in the following screen. Step 2 − You will see the same screen as the following. Step 3 − If you have lot of content you can use Filter to search the content that you want to modify. You can modify About us (About us page was created in the chapter Drupal - Create Content). You can select the status of the content as shown in the following screen. Select published for About us status. Following are the details of the fields present in the preceding screen. Published − It displays all the published items. Published − It displays all the published items. Promoted − It displays the promoted items on your website. Promoted − It displays the promoted items on your website. Not promoted − It displays the items that not promoted on your website. Not promoted − It displays the items that not promoted on your website. Sticky − It displays the sticky items on your website. Sticky − It displays the sticky items on your website. Not sticky − It displays the non-sticky items on your website. Not sticky − It displays the non-sticky items on your website. You can select type of the content like Articles, Basic page or Blog entry. Select Basic page as About us type is Basic page, and click filter as shown in the following screen. Step 4 − Now you can see the filtered content as shown in the following screen. To edit the content, click the edit link. Step 5 − You can modify your content and click Save. Step 6 − You will see the following screen with updated content. In this chapter, let us study about Deleting content. You can delete any of the previously written content such as Articles, Basic page and Blog entry. Following are the simple steps used to delete content. Step 1 − Click the Content. Step 2 − You can delete About us (About us page was created in the chapter Drupal - Create Content), and click the delete tab as shown in the following screen. Step 3 − Next, you will see the following screen. You need to confirm deletion of the content. Click the Delete button if you want to delete or Cancel button if you want to cancel the process. Step 4 − Immediately, you will see a confirmation message as your page has been deleted, as shown in the following screen. In this chapter, let us study how to Publish content. Every content is either published or unpublished. Published content is open for visitors to view while unpublished content cannot be viewed. We can make use of this feature to hide the content from public view without deleting it. Following are the simple steps to enable or disable publishing options for content. Step 1 − Click on the Content tab as shown in the following screen. Step 2 − You can select any of the content. Let us choose About us (About us page was created in the chapter Drupal - Create Content), and click edit as shown in the following screen. Step 3 − Next, click Publishing options as shown in the following screen. Step 4 − Check the box of Published option and click Save as shown in the following screen. Following are the details of the fields present in the preceding screen. Published − It specifies to publish your page. Published − It specifies to publish your page. Promoted to front page − It displays your page on front page of your website. Promoted to front page − It displays your page on front page of your website. Sticky at top of lists − It displays your article or page, etc. at the top of the lists. Sticky at top of lists − It displays your article or page, etc. at the top of the lists. Step 5 − You can see the status of the content will be changed. In this chapter, we will study about Menu Management in Drupal. Menu Management is the important part to navigate through Drupal admin page. Following is the screen for Drupal Menu Management. It displays the list of articles or pages which are created. It is the first screen that will get displayed when you log into administration area. This feature can help you in creating, managing and finding new pages. The table gets displayed with the detail of the articles, i.e. status, title, updated, author and operation (Edit and delete). Structure includes the blocks, manage content types, add new menu links to the site and manage administrative tagging of content. Block − Blocks are a container objects used to organize your content on your website. It can be displayed in the region on your page. Block − Blocks are a container objects used to organize your content on your website. It can be displayed in the region on your page. Content types − Content type defines the way the contents are collected and displayed. Content types − Content type defines the way the contents are collected and displayed. Menus − Menus are used to set the URL links for your site. Menus − Menus are used to set the URL links for your site. Taxonomy − Taxonomy can be thought of classifying website content which display specific content based on taxonomy terms. Taxonomy − Taxonomy can be thought of classifying website content which display specific content based on taxonomy terms. A list of themes are displayed. You can install the theme, update the existing theme or switch the themes. You can create a new user account or mange the existing user. You can enable or disable the modules present in it or can install a new module. This is an important part in the Drupal backend. Any changes done in this configuration, will affect the entire website. You can do the user account setting, site information setting or any other general site setting. Following are the details of the fields present in the preceding screen. People − Manages the user settings and IP address setting. People − Manages the user settings and IP address setting. System − Manages the basic site information, advanced actions and site maintenance task. System − Manages the basic site information, advanced actions and site maintenance task. Content Authoring − Manages the content input by the users including HTML tags. Content Authoring − Manages the content input by the users including HTML tags. User Interface − Sets the shortcut for menu on the admin account page. User Interface − Sets the shortcut for menu on the admin account page. Media − Manages the media settings in Drupal sites. Media − Manages the media settings in Drupal sites. Development − Manages the errors and page caching for users. Development − Manages the errors and page caching for users. Search and Meta Data − Set the alternative URL for specific page and the search engine maintains an index of words found in site content. Search and Meta Data − Set the alternative URL for specific page and the search engine maintains an index of words found in site content. Web Services − Displays the RSS feed from your site. Web Services − Displays the RSS feed from your site. Regional and Language − Sets the website time zone and displays the date and time. Regional and Language − Sets the website time zone and displays the date and time. It displays the information of available updates, recent log messages, and site security. Following are the details of the fields present in the preceding screen. Status report − Creates your Drupal site status report. Status report − Creates your Drupal site status report. Available updates − Gives status update for you available installed modules and themes. Available updates − Gives status update for you available installed modules and themes. Recent log messages − Displays messages which are recently logged. Recent log messages − Displays messages which are recently logged. Field List − Displays the list of fields configured on your site. Field List − Displays the list of fields configured on your site. Top 'access denied' errors − Displays access denied error message when user tries to access the unauthorized page. Top 'access denied' errors − Displays access denied error message when user tries to access the unauthorized page. Top 'Page not found' errors − Displays an error message as Page not found when there is no specified URL present in the Drupal site. Top 'Page not found' errors − Displays an error message as Page not found when there is no specified URL present in the Drupal site. Top search phrases − Displays the most searched phrases on your Drupal site. Top search phrases − Displays the most searched phrases on your Drupal site. It displays the help screen, where documentation pages of online modules are listed. Taxonomy can be thought of classifying website content which display specific content based on taxonomy terms. Drupal taxonomy is made up of − Term − It is used to manage or describe the content. Term − It is used to manage or describe the content. Vocabulary − It is set of terms. Vocabulary − It is set of terms. Following are the steps to work with Drupal Taxonomy − Step 1 − Go to Structure and click the Taxonomy option. Step 2 − You can create a new vocabulary for Drupal taxonomy by clicking on Add vocabulary link. Step 3 − You will get a screen with Name field for adding name for your vocabulary which is mandatory and Description field is used for adding description for the vocabulary. Click the Save button. Step 4 − Click add terms to add new terms to the created vocabulary as shown in the following screen. Step 5 − The screen shows some fields as seen in the following screen. Following are the details of the fields present in the preceding screen. Name− It specifies name of the term. Name− It specifies name of the term. Description− It is used for adding description for the term. Description− It is used for adding description for the term. Text format− It provides different types of formats by using dropdown menu. Text format− It provides different types of formats by using dropdown menu. URL alias− It optionally specifies an alternative URL by which this term can be accessed. URL alias− It optionally specifies an alternative URL by which this term can be accessed. Relations Relations Parent Terms − In this field, you can set a term as the parent term. Parent Terms − In this field, you can set a term as the parent term. Weight − Specifies weight for each term which will then display in ascending order by weight. Weight − Specifies weight for each term which will then display in ascending order by weight. After filling all the fields, click the Save button. In this chapter, we will study about Comments in Drupal. You can enable or disable the comments on your website. You can control, who can comment on your website's content and who can manage those comments. Following are the simple steps to configure comments in Drupal. Step 1 − Go to Structure and click Content types as shown in the following screen. Step 2 − Click on Edit link that you would like to change the comment setting. Step 3 − Click Comment settings category as shown in the following screen. Step 4 − Select open from the drop-down menu under Default comment setting for new content. This will allow comments on your website. Click the Save Content type button to save your configuration settings. User Management manages the information of the user, which allows creating or deleting the user, changing passwords, time and roles. Following are the simple steps to manage the users in Drupal. Step 1 − Click People --> Permissions Tab. In Permission tab, you can view two more tabs i.e. Permissions and Roles as shown in the preceding screen. Permission This section is related to posting content permission. It contains the following types of permission − Permission This section is related to posting content permission. It contains the following types of permission − Block − Sets permission to view, create, enable and disable the blocks. Block − Sets permission to view, create, enable and disable the blocks. Comment − Sets permission to users to view, edit, post comment or skip comment approval. Comment − Sets permission to users to view, edit, post comment or skip comment approval. Contextual links − Sets permission to use contextual link to perform action related to elements on a page. Contextual links − Sets permission to use contextual link to perform action related to elements on a page. Dashboard − Sets permission to allow users to view and make changes in the dashboard. Dashboard − Sets permission to allow users to view and make changes in the dashboard. Filter − Permission to filter the amount of roles and permission on the site. Filter − Permission to filter the amount of roles and permission on the site. Image − Permission to create or modify the styles of images. Image − Permission to create or modify the styles of images. Menu − Allows permission to access menu items and create menu through the admin interface. Menu − Allows permission to access menu items and create menu through the admin interface. Node − Allows to manage the view, edit and delete permissions for content type. Node − Allows to manage the view, edit and delete permissions for content type. Overlay − Sets permission to display administrative page as a layer over the current page. Overlay − Sets permission to display administrative page as a layer over the current page. Path − Sets permission to access path to all pages of Drupal site. Path − Sets permission to access path to all pages of Drupal site. Search − Sets permission to use normal and advanced search. Search − Sets permission to use normal and advanced search. Shortcut − Allows permission to set the shortcut toolbar on top of the page. Shortcut − Allows permission to set the shortcut toolbar on top of the page. System − Permission is granted to administer site configuration, view the themes, site reports, etc. System − Permission is granted to administer site configuration, view the themes, site reports, etc. Taxonomy − Permission to set the vocabularies and terms, and also to edit and delete terms in tags. Taxonomy − Permission to set the vocabularies and terms, and also to edit and delete terms in tags. Toolbar − Allows permission to access the administration toolbar. Toolbar − Allows permission to access the administration toolbar. User − Sets permission to individual users without assigning any special role to provide an interface. User − Sets permission to individual users without assigning any special role to provide an interface. Roles It allows to set permissions for group of users by defining there roles. Here you can create the roles and edit permissions for each user. Roles It allows to set permissions for group of users by defining there roles. Here you can create the roles and edit permissions for each user. Anonymous user − Allows user to access your website without asking them for the username or password. Anonymous user − Allows user to access your website without asking them for the username or password. Authenticated user − Allows only those users to access your website, who are authenticated to use it. Authenticated user − Allows only those users to access your website, who are authenticated to use it. Administrator − User who is responsible to manage the complete website and allow users to create or view by his permission. Administrator − User who is responsible to manage the complete website and allow users to create or view by his permission. In this chapter, we will learn how to optimize Drupal to improve its performance and speed. There are few steps through which we can improve the performance of the website. Following are some of the ways to optimize the website. Enable Cache blocks and Cache pages for Anonymous Users. Page caching lets your contents store in different database cache tables. Page cache is stored in the HTML content. It optimizes the page load time for anonymous users. Step 1 − Click Configuration from the menu bar. Step 2 − In Development section click Performance. Step 3 − Enable Cache blocks and Cache pages for Anonymous Users by checking both the boxes. Then, click Save Configuration. If you have many CSS files, it can lower your websites speed. Compress them by enabling Aggregate and Compress CSS files. Enable this setting from AdministrationConfiguration→Development→Performance section. Drupal decreases the number and size of your CSS files. Java files can also affect the performance and speed of your website. To compress this enable the Aggregate JavaScript files from the Administration→Configuration→Development→Performance in the bandwidth optimization section. This decreases the number of requests that a shared hosting handles. Use CDN (Content Delivery Network) that hosts your media files and static files. CDN acts as an external cache for your files and will store them in high performance servers so that it is optimized. Do not have many images which consume more space as this leads to slow website. Always resize your images and have few that are related to your website. Optimizing themes is a very important aspect. Media files like high quality images, videos, audios and flash can affect your website and slow down the speed resulting in low performance. Try reducing the size and number of media files or maybe you can avoid using flash. In this chapter, we will study about Site Backup in Drupal. It helps in backing up the files and the database file. Backup Files in Drupal Backup Database in Drupal To get the backup files of Drupal, you need to install FileZilla Client on your system. Following are the simple steps for file backup in Drupal − Step 1 − Open the FileZilla Client as shown in the following screen. Step 2 − Enter the Host, Username, Password and Port as you have used to login to your cPanel. After filling all the fields, click Quickconnect button. Step 3 − You will get all files and folder of your Drupal site on the right side as shown in the following screen. Step 4 − Select all the files and folders and right click the mouse, click the Download option. After downloading the Drupal files from cPanel, it will get saved on your system. Following are the simple steps for database backup in Drupal − Step 1 − Type the path http://localhost/phpmyadmin in browser. You will get the following screen. Step 2 − Click the database name drupal, which you have created for Drupal. Step 3 − After clicking on database drupal, it will open the following page, click Export tab. Step 4 − Next, you will find two methods to export the database i.e. Quick and Custom. Select any one of the methods and click the Go button. After exporting the database file, it will get saved on your system. In this chapter, we will study how to upgrade the Drupal site. Upgrade is a process of enhancing the old version to the latest version. Here we will upgrade the Drupal to the latest version. Below are simple steps to upgrade the site in Drupal. Step 1 − Backup your Drupal files. You can study about this in detail in the chapter Drupal - Site Backup. Step 2 − If there is any upgradation to be done on Drupal site, then a message gets displayed on your site as shown in the following screen. Step 3 − Click on the highlighted word available updates in the message. Step 4 − You can now view the Available Updates page, where it shows exactly what upgradation is to be done on the site. Here, it shows you the recommended version to update your site. Click Release notes. Step 5 − It will take you to Drupal official site page where you can see the latest version tar.gz files available in Drupal. While writing this tutorial, the latest version was drupal - 7.39.tar.gz. Click drupal - 7.39.tar.gz. The tar.gz files get downloaded on your system. Step 6 − Extract the downloaded file, copy all the files and folder except the Sites folder available inside the latest downloaded folder. Later, paste these files into your existing Drupal folder. Step 7 − Go to Reports --> Available updates or else you can refresh the page; here you will view a message as shown in the following screen. Step 8 − Click on Reports --> Status report. You can now see that your site is upgraded to latest version and it will show the status Up to date for Drupal core update status as shown in the preceding screen. In this chapter, we will learn about Announcements in Drupal. If you want to make any announcements on your website then you can do it through this feature. Declaration given to a visitor or user with the help of your website is announcements. It can be some important news, report, etc. It can be useful if you want to declare something important through your site that can be helpful for your visitors. Following are the steps to create Announcements in Drupal. Step 1 − First click Structure. Step 2 − Click on Content Types. Step 3 − Then you must click Add Content type. Step 4 − When you click Add content, the following page will get displayed on screen. Step 5 − Enter the content that you want to announce in the Name section. After adding name, click Save content type. Your new content gets displayed as shown in the following screen. Step 6 − If you want to make changes you must click the Edit section, you will get the following page. Step 7 − You can make the required changes, such as adding description and then click Save Content type. If you want to delete, then click Delete Content type. You can manage the fields by clicking on Manage Fields and manage display by clicking on Manage Display. In this chapter, we will study about Drupal URL Alias. URL or Uniform Resource Locater Aliases is a page address on your web page, it changes the existing system path to new path alias. Following are the simple steps to create URL Aliases in Drupal. Step 1 − Click Configuration as shown in the following screen. Step 2 − Click on URL aliases. Step 3 − Then, click Add alias. Step 4 − The Url aliases page will get displayed as shown in the following screen. Following are the details about the fields present in URL aliases page. Language − Specifies the language to be used in URL aliases. Language − Specifies the language to be used in URL aliases. Existing system path − Existing system path of an Article/Page in Drupal site. Existing system path − Existing system path of an Article/Page in Drupal site. Path alias − New path alias that replaces with the existing system path of an Article/Page. Path alias − New path alias that replaces with the existing system path of an Article/Page. Click the Save button. Step 5 − You can view your created URL aliases in the list as shown in the following screen. Step 6 − When you go back to Drupal Admin panel and hover over Article, it will display the newly added Path alias at the left bottom of the screen as shown in the following screen. Drupal allows to search for specific content on your site. You can search for both users and words on the site. We will see how to set up site search in Drupal as specified in the following steps − Step 1 − Go to Configuration and click the Search settings link under SEARCH AND METADATA section. Step 2 − The search engine maintains an index of words found on your site's content. You can adjust the indexing behavior as shown in the following screen. The Indexing Status section indexes the content of nodes on the site. When you click the Re-index site button, the previous content remains until cron runs and sets the number of items to index per cron run by, using the drop-down menu under the Indexing Throttle section. Step 3 − Next it provides settings related to the indexing which will cause the site index to be rebuilt. It updates systematically to reflect the new settings. You can set minimum word length to index, i.e., the number of characters a word has to be indexed as shown in the following screen. Step 4 − You can choose which search modules are active from the available modules as defined in the following screen. You can search for both users and words (node) by checking the required modules and set the default search module as shown in the preceding screen. Step 5 − The last section is Content Ranking which comes with Factor and Influence columns. Influence is a numeric multiplier used in ordering search results. If you set higher number for a corresponding factor, it will have more influence on search results; zero means the factor is ignored. After you are done with settings, click the Save configuration button. Step 6 − Now go to home page, search the content that matches for the keywords in your content in the search bar. In this chapter, we will study about Drupal error handling for managing error messages on Drupal site. Error Handling is a process of detection and finding the resolutions for the errors. It can be programming application errors or communicable errors. The following steps describe how to manage error messages in Drupa − Step 1 − Go to Configuration and click Logging and errors. Step 2 − The Logging and errors page will get displayed as shown in the following screen. Following are the details of the fields as seen in the preceding screen − Error messages to display − It specifies error messages to be displayed on the Drupal site. Error messages to display − It specifies error messages to be displayed on the Drupal site. None − This option doesn't display any error message. None − This option doesn't display any error message. Errors and warnings − This option displays only messages related to errors and warnings. Errors and warnings − This option displays only messages related to errors and warnings. All messages − This option specifies all types of error messages such as errors, warnings, etc. to be displayed on the site. All messages − This option specifies all types of error messages such as errors, warnings, etc. to be displayed on the site. Database log messages to keep − It indicates the maximum number of messages to be kept in the database log. Database log messages to keep − It indicates the maximum number of messages to be kept in the database log. Drupal uses _drupal_exception_handler ($exception) function to handle the errors on the site. These errors will not be enclosed in a try/catch block. The script won't execute the function when an exception handler exits. The code for _drupal_exception_handler is as follows − function _drupal_exception_handler($exception) { require_once DRUPAL_ROOT . '/includes/errors.inc'; try { // display the error message in the log and return the error messages to the user _drupal_log_error(_drupal_decode_exception($exception), TRUE); } catch (Exception $excp2) { // Another uncaught exception was thrown while handling the first one. // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown. if (error_displayable()) { print '<h1>Additional uncaught exception thrown while handling exception.</h1>'; print '<h2>Original</h2> <p>'. _drupal_render_exception_safe($exception).'</p>'; print '<h2>Additional</h2> <p>'. _drupal_render_exception_safe($excp2).'</p><hr/>'; } } } The function must be used on every Drupal request. This function is present at the line 2328 in the file includes/bootstrap.inc. There are two string references to _drupal_exception_handler such as_drupal_bootstrap_configuration() present in the bootstrap.inc file and_drupal_get_last_caller present in the errors.inc file. Both these files are present in the ‘includes’ folder. In this chapter, we will learn about multilingual content. That means your content can be written and will be displayed in different languages. For this you may either install a multilingual content module or an Internationalism module. Following are the steps to install multilingual content module on Drupal. Step 1 − Click Modules from the menu bar. Step 2 − Check the Multilingual content box from the modules and click Configure. Step 3 − The Multilingual settings page will get displayed. Enabled language only − When you check this box, you can only view languages that are enabled. Enabled language only − When you check this box, you can only view languages that are enabled. All Defined languages will be allowed − Only the defined languages will be allowed. All Defined languages will be allowed − Only the defined languages will be allowed. Here, we have three different tabs where you can make the required changes. Selection − You can select nodes and taxonomy according to language. Selection − You can select nodes and taxonomy according to language. Select nodes by language − Check box if you want nodes by language. Select nodes by language − Check box if you want nodes by language. Select taxonomy terms by language − If you want taxonomy terms by language then check this box. Select taxonomy terms by language − If you want taxonomy terms by language then check this box. Skip tags − Write those tags which you don't want to include. Skip tags − Write those tags which you don't want to include. Enable for specific pages − If you want to enable settings for specific pages then use this checkbox. Enable for specific pages − If you want to enable settings for specific pages then use this checkbox. Click the save button, once completed. Variables − Select variables to be set as shown in the following screen. Variables − Select variables to be set as shown in the following screen. Menu Settings − Manages menu settings. Menu Settings − Manages menu settings. Site Information − Helps to make changes on site. Site Information − Helps to make changes on site. Feed settings − You can set your feed description. Feed settings − You can set your feed description. Regional Settings − Changes time zone and day. Regional Settings − Changes time zone and day. Theme Settings − Specifies managing themes. Theme Settings − Specifies managing themes. User Settings − You can use this to set users. User Settings − You can use this to set users. User emails − Any issues related to user emails can be done. User emails − Any issues related to user emails can be done. Examples − You can give examples. Examples − You can give examples. Click Save when you complete the settings. Node Options − Help you set nodes. Node Options − Help you set nodes. You can hide content translations and change the language on this page. Later, click the Save configuration button. Strings − This option helps to change format of the page. Change and translate strings using Translatable text formats settings. You can even change sources as you choose many languages. After completion, click Save button. In this chapter, we will learn about Triggers and Actions in Drupal. First let's look into Triggers. It can be defined as changes happening within your site. The actions can be carried out either after creating a new content or any page. Following are the steps that will help you use triggers in Drupal. Step 1 − First click Modules from the menu bar. Step 2 − When you click Modules, you get the following page. Here enable Trigger module. Then click Save Configuration at the bottom of the page. Step 3 − Go back to the Trigger module and click Configure on the right side of the page as shown in the following image. Step 4 − When you click Configure, you get the following page. We have different tabs on the page that specify each trigger. Comment Module − You can assign action to only those triggers relating to comment module. Node Module − You can assign action to those triggers relating to Node module. System Module − You can assign action to only those triggers relating to System module. Taxonomy Module − You can trigger actions to the Taxonomy module. User Module − At last we have the user module, here actions must be assigned in User module. Tasks carried on a particular system object are called actions. Step 1 − Click Configuration from the menu bar. Step 2 − Click on Actions from the system section. Step 3 − When you click Actions, you get the following page. Step 4 − Select any one action from the dropdown and click Create. Step 5 − When you choose an option and click Create, The following page appears. Following are the option fields present on the page − Label − Give a name to your action Label − Give a name to your action Recipient − Enter your email address Recipient − Enter your email address Subject − Enter a subject you want to add to the action Subject − Enter a subject you want to add to the action Message − Enter the message you want to send to the visitor when clicked on any action. Message − Enter the message you want to send to the visitor when clicked on any action. After filling all the details, click Save. Step(6) − You can see that your action is added to the list. In this chapter, let us study about Social Networking in Drupal. Social media is becoming very important these days, Drupal has many social media modules for this purpose. Let us take ShareThis module as our example, you can choose any other of your choice. Following are the simple steps used to install ShareThis module. Step 1 − Click ShareThis to visit ShareThis module page and click the Version as shown in the following screen. Step 2 − Copy the link address of the module as shown in the following screen. Step 3 − Next, go to Modules and click Install new module as shown in the following screen. Step 4 − Now, paste the link address that you copied in step(2) and click Install as shown in the following screen. Step 5 − You will see the following screen. Click Enable newly added modules. Step 6 − Next, go to Modules. Enable the module and click Save configuration as shown in the following screen. Step 7 − Go to Configuration, under WEB SERVICES and click ShareThis as shown in the following screen. Step 8 − The following screen pops up. Step 9 − You can click any of the button style, under the Display section to share your content online as shown in the following screen. Step 10 − Click any of the services you want to remove. You can also use Extra services like Google Plus One and Facebook Like by checking them as shown in the following screen. You can choose services from the Possible Services section and you can also remove or re-order services from Selected Service section. Step 11 − Next, click Context as shown in the following screen to configure where the ShareThis widget should appear. Following the details of the fields present on the screen. Under Location you can choose any of Node content or Block or Links area. Under Location you can choose any of Node content or Block or Links area. Under Node Types you can select Article and Basic page, if you want ShareThis widget to appear on it. Under Node Types you can select Article and Basic page, if you want ShareThis widget to appear on it. If you select Comments you can display ShareThis on comments as well. If you select Comments you can display ShareThis on comments as well. The Weight of the widget determines the location on the page where it will appear. The Weight of the widget determines the location on the page where it will appear. Step 12 − Next, select Advanced as shown in the following screen. Following are the details of the fields present on the preceding screen. When you install the module, a random publisher key will be created. When you install the module, a random publisher key will be created. Twitter Suffix will optionally append a Twitter handle, or text, so that you get a ping when someone shares an article. Twitter Suffix will optionally append a Twitter handle, or text, so that you get a ping when someone shares an article. Twitter Handle will be used when sharing on twitter. Twitter Handle will be used when sharing on twitter. Twitter recommends will specify a twitter handle to be recommended to the user while sharing. Twitter recommends will specify a twitter handle to be recommended to the user while sharing. If Display ShareThis widget on hover is disabled, ShareThis widget will be displayed on click instead of hover. If Display ShareThis widget on hover is disabled, ShareThis widget will be displayed on click instead of hover. If Display count "0" instead of "New" is checked, zero is displayed instead of New in the count for content not yet shared. If Display count "0" instead of "New" is checked, zero is displayed instead of New in the count for content not yet shared. Display short URL will display either the full or the shortened URL. Display short URL will display either the full or the shortened URL. CopyNShare will measure copy and shares of your site's content or URLs as checked respectively. CopyNShare will measure copy and shares of your site's content or URLs as checked respectively. Step 13 − After checking all the details, click Save configuration as shown in the following screen. Step 14 − Now you can see the social media buttons appearing on the Article page. In this chapter, we will learn about Internationalization in Drupal. Internationalization is a module which lets you create multilingual sites. This way you can display your website in different languages. Following are the steps for Internationalization − Step 1 − Click Module from the menu bar. Step 2 − To get the Internationalization module you must first download and install it in Drupal. Then you must enable the Internationalization module, and click Save Configuration. Step 3 − Next, you can see a Configure setting on the right side of the page for Internationalization module as shown in the following screen. Step 4 − Click Configure and you get the following page. In Languages for content − Enabled language only − When you check this box, you can only view those languages that are enabled. Enabled language only − When you check this box, you can only view those languages that are enabled. All Defined languages will be allowed − Only the defined languages will be allowed, when you check this box. All Defined languages will be allowed − Only the defined languages will be allowed, when you check this box. You can see some tabs on the top right corner of the page − Multilingual Settings − You can study about multilingual settings in detail in the chapter Drupal - Multilingual Content Multilingual Settings − You can study about multilingual settings in detail in the chapter Drupal - Multilingual Content Selection − You can select nodes and taxonomy according to language. Selection − You can select nodes and taxonomy according to language. Variables − Select variables to be set. Variables − Select variables to be set. Node Options − Helps you set nodes. Node Options − Helps you set nodes. Strings − Helps to change the format of the page. Strings − Helps to change the format of the page. Once you are done with the changes, click Save Configuration. In this chapter, we will learn about Drupal Extensions. To extend the functionality of the site, different extensions can be installed. Following are the steps to install Extension module in Drupal. Step 1 − Click on Modules from the menu bar. Step 2 − Click on Install new module. Step 3 − The following page gets displayed. Here, enter the module URL in the box as shown in the following image and click Install. Step 4 − The module starts getting installed as shown in the following screen. Step 5 − Once installation is complete, you get the following screen. Here, click Enable newly added modules link. Step 6 − Next, a Module page gets displayed where your module has been installed, now you can enable the module. In this chapter, we will study about Default Modules in Drupal. After installing Drupal, you will see total 44 default modules. You can see all these modules in Core section. By default 29 modules are enabled after installation. Step 1 − Click Modules, you will see the list of modules in CORE section as shown in the following screen. Following is the list of default modules installed in Durpal7. These are the core modules required by Drupal and it cannot be disabled. Block − Controls the constructed page with visual building blocks. Blocks are boxes of content provided into an area or region of a web page. Block − Controls the constructed page with visual building blocks. Blocks are boxes of content provided into an area or region of a web page. Color − Permits administrators to modify the color scheme of compatible themes. Color − Permits administrators to modify the color scheme of compatible themes. Comment − Permits users to comment and discuss about the published content. Comment − Permits users to comment and discuss about the published content. Contextual links − Provides contextual links to execute actions associated with elements on a page. Contextual links − Provides contextual links to execute actions associated with elements on a page. Dashboard − Offers a dashboard page in the administrative interface for forming administrative projects and tracking information within your website. Dashboard − Offers a dashboard page in the administrative interface for forming administrative projects and tracking information within your website. Database logging − Logs and records system events to the database. Database logging − Logs and records system events to the database. Field − Field API allows adding fields to entities like nodes and users. Field − Field API allows adding fields to entities like nodes and users. Field SQL storage − It sets to store field data in an SQL database. Field SQL storage − It sets to store field data in an SQL database. Field UI − User interface for the Field API. Field UI − User interface for the Field API. File − Specifies a file field type. File − Specifies a file field type. Filter − Filters content and exhibits in order. Filter − Filters content and exhibits in order. Help − Manages the display of online help. Help − Manages the display of online help. Image − Allows image handling tools. Image − Allows image handling tools. List − Specifies list field types. Creates choice lists with this selection. List − Specifies list field types. Creates choice lists with this selection. Menu − Permits administrators to customize the site navigation menu as per the choice. Menu − Permits administrators to customize the site navigation menu as per the choice. Node − Allows content to be submitted to the site and displayed on pages. Node − Allows content to be submitted to the site and displayed on pages. Number − It sets the numeric field types. Number − It sets the numeric field types. Options − It specifies the choice, check box and radio button widgets for text and numeric fields. Options − It specifies the choice, check box and radio button widgets for text and numeric fields. Overlay − It specifies the Drupal administration interface in an overlay. Overlay − It specifies the Drupal administration interface in an overlay. Path − Permits users to rename URLs. Path − Permits users to rename URLs. RDF − It improves your content with metadata to allow other applications (e.g. search engines, aggregators) to its relationships and attributes in understand in a better manner. RDF − It improves your content with metadata to allow other applications (e.g. search engines, aggregators) to its relationships and attributes in understand in a better manner. Search − Permits site-wide keyword searching. Search − Permits site-wide keyword searching. Shortcut − Permits users to manage customizable lists of shortcut links. Shortcut − Permits users to manage customizable lists of shortcut links. System − Handles general site configuration for administrators. System − Handles general site configuration for administrators. Taxonomy − Enables the categorization of content. Taxonomy − Enables the categorization of content. Text − Defines simple text field types. Text − Defines simple text field types. Toolbar − Provides a toolbar that shows the top-level administration menu items and links from other modules. Toolbar − Provides a toolbar that shows the top-level administration menu items and links from other modules. Update manager − Checks for available updates and can securely install or update modules and themes via a web interface. Update manager − Checks for available updates and can securely install or update modules and themes via a web interface. User − Manages the user registration and login system. User − Manages the user registration and login system. In this chapter, we will learn about using Pane Module in Drupal. Pane module is used to translate the custom panel's pane with optional title that will be stored as variables and it can be translate or edit quickly. Following are the steps to add Pane Module. Step 1 − Download the latest file of Pane module from the link and install in your Drupal site. Step 2 − Enable the one you want to use and click Save Configuration at the bottom of the page. Step 3 − Click Structure from the menu bar. Step 4 − Click on Panes. Step 5 − Then click Add pane to add a new pane. Step 6 − The Panes page gets displayed as shown in the following screen. It contains the following fields. Title − Enter your pane title in this box. Title − Enter your pane title in this box. Description − Describe your pane in a line or a sentence. Description − Describe your pane in a line or a sentence. Type − Select type accordingly, it may be either Text or Entity Host. Type − Select type accordingly, it may be either Text or Entity Host. After filling the details, click Save Configuration. Step 7 − Your Pane module gets displayed as shown in the following image. If you want to make any changes in the pane, then click Edit. Step 8 − The Pane page gets displayed. Make the required changes and click Save Content. In this chapter, we will study about Book Module in Drupal. Books have an in-built hierarchical navigation, which means that you can organize them to read in a special order. The book content type also allows you to make your website content easier to print by site visitors. Following are the simple steps to configure Book module in Drupal. Step 1 − Enable the Book in Modules and click Save configuration. Step 2 − Click on Content and check the boxes, select the content type that you want to enable for books. Click Save configuration to save your content type. Step 3 − Click Create content -> Book page or on Shortcut bar Book page as shown in the following screen. Spread out the section under Book outline and select create a new book. You can set the weight to 0. Click the Save button and your top level page is created. Step 4 − Once your book has been created, you can create child pages by clicking the Add child link at the bottom of the book page. Step 5 − Further, click Content management -> Books -> List as shown in the following screen. Click on edit order and titles under Operations column. Step 6 − You will see the screen as shown in the following screen. This page allows you to move your book pages around to fit your needs. Press and hold on the four pronged arrow and move it to the position to rearrange your pages. You can also drag the page to the right to make it a child page. In this chapter, we will study about Aggregator Module in Drupal. Aggregator Module takes the content from other websites but does not generate any feeds. It is also known as a feed reader. It gathers and displays texts and images from other sites and blogs. Following are the steps to enable Aggregator Module. Step 1 − Click Modules from the menu bar. Step 2 − A list of different modules gets displayed. Enable the Aggregator module and click Save Configuration as shown in the following screen. Step 3 − Now, go back to the aggregator module and click Configure option on the right side. Step 4 − A Feed aggregator page gets displayed. Following are the settings present on this page. Allowed HTML tags − This specifies that you can get only those HTML tags which are included in the given text box as you can see in the image. If you remove any of them you won't find that particular tag in your content. Allowed HTML tags − This specifies that you can get only those HTML tags which are included in the given text box as you can see in the image. If you remove any of them you won't find that particular tag in your content. Number of items shown in listing pages − Select the number of items you want to be displayed on your pages. Number of items shown in listing pages − Select the number of items you want to be displayed on your pages. Discard items older than − You can remove items that are older by using this option. Discard items older than − You can remove items that are older by using this option. Select categories using − You can select categories accordingly, either by clicking on Check boxes radio button or multiple selectors. Select categories using − You can select categories accordingly, either by clicking on Check boxes radio button or multiple selectors. Length of trimmed description − Select the length of your descriptions. Length of trimmed description − Select the length of your descriptions. Once you are done with all the settings, click Save Configuration. In this chapter, we will study about creating contact form in Drupal. Contact form is used to submit the information of user in Drupal. Following are the steps to add Contact module. Step 1 − Click Modules menu. Step 2 − A list of different modules gets displayed. Enable the Contact module and click Save Configuration as shown in the following screen. Step 3 − Go back to the contact module and click the Configure tab as shown in the following screen. Step 4 − Now you can view the information of all the categories and you can also add extra contacts. Click Add Category. Step 5 − The contact form gets displayed as shown in the following screen. It contains the following fields. Category − Specify the name of the category for feedback form. Category − Specify the name of the category for feedback form. Recipients − Specify the e-mail address where you wish to receive mails. Recipients − Specify the e-mail address where you wish to receive mails. Auto-reply − Sends the automatic reply message to the user. Auto-reply − Sends the automatic reply message to the user. Weight − Sets the list in order. Weight − Sets the list in order. Selected − Selecting Yes option, it sets the category as default. Selected − Selecting Yes option, it sets the category as default. After filling all information about the contact, click the Save button to save your contact form information. Step 6 − You can see the created contact form in the list as shown in the following screen. To view the contact form, click Contact form tab. Step 7 − The category which you have added will get displayed in the category field as shown in the following screen. In this chapter, we will learn about Form module in Drupal. This module lets you create a form in Drupal based on the website for your users. Following are the steps to install Form Module in Drupal. Step 1 − Download the latest file of Form Builder module from the link and install in your Drupal site. Step 2 − Enable Form Builder module from the module page. Step 3 − Click Form Builder example from the dashboard. Step 4 − A Form builder example page gets displayed as shown in the following screen. Here you can add, edit or remove the details manually. Sample Text Field (Properties) Title − Enter the title name for your form. Title − Enter the title name for your form. Default value − Sets the default value. Default value − Sets the default value. Description − Enter description related to the title in that box. Description − Enter description related to the title in that box. Sample Text Field (Display) Prefix − Enter the prefix text. Prefix − Enter the prefix text. Suffix − Here you must put the suffix text. Suffix − Here you must put the suffix text. Size − Input size accordingly. Size − Input size accordingly. Sample Text Field (Validation) Required − Check the box, when you want to validate the text field. Required − Check the box, when you want to validate the text field. Sample Checkboxes (Properties) Title − Enter your title name for your form. Title − Enter your title name for your form. Description − Enter description related to the title in that box. Description − Enter description related to the title in that box. Sample Checkboxes (Options) Options − Add items, mark as default and input the values. Options − Add items, mark as default and input the values. Customize Keys − Enable this setting if you want to save any one value. Customize Keys − Enable this setting if you want to save any one value. Sample Checkboxes (Validation) Required − Check the box when you want to validate the field. Required − Check the box when you want to validate the field. Sample Text Area (Properties) Title − Enter the title name for your form. Title − Enter the title name for your form. Default value − Set the default value. Default value − Set the default value. Description − Enter description related to the title in that box. Description − Enter description related to the title in that box. Sample Text Area (Display) Rows − Enter rows. Rows − Enter rows. Columns − Enter columns. Columns − Enter columns. Sample Text Area (Validation) Required − Check the box when you want to validate the field. Required − Check the box when you want to validate the field. Sample Radios (Properties) Title − Enter the title name for your form. Title − Enter the title name for your form. Description − Enter description related to the title in that box. Description − Enter description related to the title in that box. Sample Radios (Options) Options − Add items, mark as default and input the values. Options − Add items, mark as default and input the values. Customize Keys − Enable this setting if you want to save any one value. Customize Keys − Enable this setting if you want to save any one value. Sample Radios (Validation) Required − Check the box when you want to validate the field. Required − Check the box when you want to validate the field. Sample Select (Properties) Title − Enter the title name for your form. Title − Enter the title name for your form. Description − Enter description related to the title in that box. Description − Enter description related to the title in that box. Sample Select (Options) Customize Keys − Enable this setting if you want to save any one value. Customize Keys − Enable this setting if you want to save any one value. Allow Multiple values − This will help users choose multiple items in your lists. Allow Multiple values − This will help users choose multiple items in your lists. In this chapter, we will study how to create a Poll module in Drupal. This module helps you create polls for your website. You can ask questions, give any number of answers and your visitors can vote. Following are the steps to create a Poll Module. Step 1 − Click Module from the menu bar. Step 2 − Enable the Poll module and then click Save Configuration. Step 3 − Click Content → Add Content. Click Poll as shown in the following screen. Step 4 − A Create Poll page gets displayed where you can create a Poll. It contains the following fields. Question − Add a question you want to add in the poll. Question − Add a question you want to add in the poll. Poll Status − If you click Closed, then visitors cannot vote. And if you click Active then visitors are enabled to vote. Poll Status − If you click Closed, then visitors cannot vote. And if you click Active then visitors are enabled to vote. Poll Duration − Select a particular time period till you want your poll to exist. After the time period is completed the Poll closes by itself. Poll Duration − Select a particular time period till you want your poll to exist. After the time period is completed the Poll closes by itself. After you complete updating settings, click the Save button. In this chapter, we will study how to secure the Drupal site. This chapter specifies security configuration suggestions for site administrators and alerts the administrator how to secure the site. There are many contributed modules which help you with security configuration in which Security Review module automates testing the mistakes that makes your site insecure. You can report a security issue directly with Drupal core, contrib or Drupal.org by sending an e-mail regarding the issue. The security team will help in resolving your issue with the help of project maintainer. You can report a security issue directly with Drupal core, contrib or Drupal.org by sending an e-mail regarding the issue. The security team will help in resolving your issue with the help of project maintainer. Secure your file permissions and ownership by configuring the server file system, as the web server (e.g. Apache) should not have access to edit or write the files. It should be read only files, which gets executed later. Secure your file permissions and ownership by configuring the server file system, as the web server (e.g. Apache) should not have access to edit or write the files. It should be read only files, which gets executed later. The security risk levels are based on NIST Common Misuse Scoring System (NISTIR 7864), so that the organization can verify how to manage the problem. Below are the points that will help you understand the security risk level by assigning the number between 0 to 25 − 0 to 4 − Not Critical. 5 to 9 − Less Critical. 10 to 14 − Moderately Critical. 15 to 19 − Critical 20 to 25 − Highly Critical. The security risk levels are based on NIST Common Misuse Scoring System (NISTIR 7864), so that the organization can verify how to manage the problem. Below are the points that will help you understand the security risk level by assigning the number between 0 to 25 − 0 to 4 − Not Critical. 0 to 4 − Not Critical. 5 to 9 − Less Critical. 5 to 9 − Less Critical. 10 to 14 − Moderately Critical. 10 to 14 − Moderately Critical. 15 to 19 − Critical 15 to 19 − Critical 20 to 25 − Highly Critical. 20 to 25 − Highly Critical. While accepting the sensitive information like credit card number, the PCI (Payment Card Industry) defines a number of Data Security Standards. Though this is not Drupal specific, it is important for each Drupal developer to be aware of this. To know more about the PCI issues, you can refer this link Drupal PCI Compliance White Paper. While accepting the sensitive information like credit card number, the PCI (Payment Card Industry) defines a number of Data Security Standards. Though this is not Drupal specific, it is important for each Drupal developer to be aware of this. To know more about the PCI issues, you can refer this link Drupal PCI Compliance White Paper. The users are allowed to be deleted or even for the users to delete themselves in Drupal site which can lead to an unexpected situation sometimes. The users are allowed to be deleted or even for the users to delete themselves in Drupal site which can lead to an unexpected situation sometimes. Enable HTTPS, which is more secure to send sensitive information to a website such as− Credit cards Sensitive cookies such as PHP session cookies Passwords and Usernames Identifiable information (Social Security number, State ID numbers, etc) Confidential content Enable HTTPS, which is more secure to send sensitive information to a website such as− Credit cards Credit cards Sensitive cookies such as PHP session cookies Sensitive cookies such as PHP session cookies Passwords and Usernames Passwords and Usernames Identifiable information (Social Security number, State ID numbers, etc) Identifiable information (Social Security number, State ID numbers, etc) Confidential content Confidential content Enhance your security using contributed modules. Some standard module categories are − Enhance your security using contributed modules. Some standard module categories are − Security category Security category User access / authentication User access / authentication Spam prevention modules Spam prevention modules You can disable the roles and permissions of the user by installing the Secure Permission module. You can disable the roles and permissions of the user by installing the Secure Permission module. The security operation can be improved in the login operation by installing the Login Security module. The security operation can be improved in the login operation by installing the Login Security module. The site administrator can secure its site by making it private and by restricting the site to limited access for the users by the role. Due to this process, your site will not be reachable to search engines and other crawlers (to create an index of data in www). The site administrator can secure its site by making it private and by restricting the site to limited access for the users by the role. Due to this process, your site will not be reachable to search engines and other crawlers (to create an index of data in www). Basically cart is a process of collecting items or services and uses checkout to collect payment. In this article, we will see how to set up a shopping cart for Drupal site by using Commerce Kickstart module. Commerce Kickstart is a good way to work with Drupal - E-Commerce which comes with different types of features to create user-friendly web store making it easier to launch and administer. You can download the Drupal Commerce Kickstart from here. Step 1 − Download the latest file of Commerce Kickstart module from the above link and install it on your system. After installing the module, you will get the following screen. Step 2 − Before adding products in your cart, you need to create products in the store. Click Add Product --> Create Product. Step 3 − You can create product as shown in the following screen. Following are the details of the fields present on the page. Product SKU − Unique identifier for the product is given here. Product SKU − Unique identifier for the product is given here. Title − This specifies the title of the product. Title − This specifies the title of the product. Image − Here you can upload image and give alternate text for your product which will be used by screen readers, search engines, when the image cannot be loaded. Image − Here you can upload image and give alternate text for your product which will be used by screen readers, search engines, when the image cannot be loaded. Price − It contains price of the product. Price − It contains price of the product. Status − Set this field to Active option, so that it can be added to shopping cart. If it is set to Disabled option, products cannot be added to shopping carts and may be hidden in administrative product lists. Status − Set this field to Active option, so that it can be added to shopping cart. If it is set to Disabled option, products cannot be added to shopping carts and may be hidden in administrative product lists. Change History − It provides history of changes made to the product. Change History − It provides history of changes made to the product. After you are done with all settings, click the Save product button. Step 4 − You will see the created product in the table. Step 5 − To display your product in the cart, click Add product display. In this window, Title field contains title of the product, you can add summary for the product in the Body field. Product field uses product SKU to display for the sale. After you are done with the settings, click the Save button. Step 6 − You will see the product displayed on the home page as shown in the following screen. Step 7 − Click the Add to cart button to add the created product in the cart. It will display the successful message after adding product to the cart. You can see the product name along with price in the Shopping cart block. Step 8 − Now click the View cart link to see the added product in the shopping cart. Step 9 − You will see the shopping cart table along with the products as shown in the following screen. In this chapter, we'll study about Creating Products in Drupal site. Products are the items that are offered for sale. Following are the simple steps used for Creating Product. Step 1 − Click Add Product. Step 2 − Click on Create Product. Step 3 − Now you have to create a product by filling the product information as shown in the following screen. It contains the following fields − Product SKU − Enter the unique identifying number for the product. Product SKU − Enter the unique identifying number for the product. Title − Enter the title of the product. Title − Enter the title of the product. Image − Upload image and give alternate text for your product which will be used by screen readers, search engines, or when the image cannot be loaded. Image − Upload image and give alternate text for your product which will be used by screen readers, search engines, or when the image cannot be loaded. Price − Enter the price of the product. Price − Enter the price of the product. Status − Set this field to Active option, so that it can be added to shopping cart. If it is set to Disabled option, products cannot be added to shopping carts and may be hidden in administrative product lists. Status − Set this field to Active option, so that it can be added to shopping cart. If it is set to Disabled option, products cannot be added to shopping carts and may be hidden in administrative product lists. Change History − It provides history of changes made to the product. Change History − It provides history of changes made to the product. After filling the fields, click Save Configuration. Step(4) − Now you can see that your product is added, click Add product display as shown in the following screen. Step(5) − The Create Product display page will get displayed as shown in the following screen. It contains below fields − Title − Add title of the product. Title − Add title of the product. Body − Here you can add summary for the product. Body − Here you can add summary for the product. Product − Choose the products to display for sale on this node by SKU. You can also enter multiple SKU's using a comma separated list. Product − Choose the products to display for sale on this node by SKU. You can also enter multiple SKU's using a comma separated list. Step(6) − You can see your product displayed on the front page. In this chapter, we will study how to Create Categories in Drupal. Taxonomy can be considered as categories or tags. Drupal taxonomy is built up of vocabularies and terms. A vocabulary is a set of terms and terms are just another word for categories. Following are the simple steps to create categories in Drupal. Step 1 − Go to Structure and click Taxonomy in the category as shown in the following screen. Step 2 − Click on Add vocabulary link. Step 3 − Enter your new vocabulary (category) Name and Description as shown in the following screen. Click the Save button and your category is created. Step 4 − You will see your new category is added to the list. Further you can click add terms link to add some terms to it. Step 5 − You can add some sub categories to it. Enter the required details and click the Save button as shown in the following screen. Step 6 − Choose your parent category from the list and click list terms link to view your sub categories list. Following are the details about the fields present in the preceding screen. Edit vocabulary − You can edit your category name and description. Edit vocabulary − You can edit your category name and description. List terms − It displays your subcategory list. List terms − It displays your subcategory list. Add terms − You can add your subcategories through this link. Add terms − You can add your subcategories through this link. Step 7 − You will see the subcategories list. Here, you can edit your subcategory by clicking on the edit link as shown in the following screen. Step 8 − Next, you can also rearrange your subcategories by dragging them as per the demand. After rearranging, click the Save button. In general, tax is a financial charge upon a taxpayer or is a source of public revenue. Sales tax is a basic type of tax levied on the sale of certain goods and services. You can specify the tax rate for the products as defined in the following steps − Step 1 − Go to Store and click Configuration. Step 2 − Click on the Taxes link which manages tax rates and types. Step 3 − Click Add a tax rate link to add tax for the product. Step 4 − It will open the taxes window for adding tax rate to the product as shown in the following screen. It contains some fields such as − Title − It is title of the tax rate. Title − It is title of the tax rate. Display title − It is the front-end display title of the tax rate shown to customers. Display title − It is the front-end display title of the tax rate shown to customers. Description − It is used to describe the tax rate. Description − It is used to describe the tax rate. Rate − It is a percentage used to calculate the tax which is expressed as a decimal. Rate − It is a percentage used to calculate the tax which is expressed as a decimal. Type − It selects the tax type for the tax rate using drop-down menu. Type − It selects the tax type for the tax rate using drop-down menu. After filling all the fields, click the Save tax rate button. Step 5 − You will see the created tax rate name which is used for the product as shown in the following screen. Step 6 − Go to Home page and click the View cart link to see the products in shopping cart. Step 7 − Click the Checkout button to see the tax rate added for the products. Step 8 − You can see the tax rate added along with the Subtotal as shown in the following screen. In general, discount is a amount or percentage deducted from the normal selling price of the product. It is the way of offering products for sale at a low or reduced price. You can specify the discount for the products as defined in the below steps− Step 1 − Go to Store and click Configuration. Step 2 − Click on the Taxes link which manages tax rates and types. Step 3 − Go to TAX TYPES tab and click the Add a tax type link. Step 4 − Tax types categorize tax rates and specify whether or not the calculated tax should be included in product prices on display. It contains some fields such as − Title − It specifies the title of tax type. Title − It specifies the title of tax type. Display title − It is the front-end display of the title of tax type shown to customers. Display title − It is the front-end display of the title of tax type shown to customers. Description − It describes the tax type if necessary. Description − It describes the tax type if necessary. Tax amount rounding mode − Specifies what type of rounding should occur when tax rates of tax type are calculated for the unit price of a line item. Tax amount rounding mode − Specifies what type of rounding should occur when tax rates of tax type are calculated for the unit price of a line item. After filling all the details, click the Save tax type button. Step 5 − Go to TAX RATES tab and click the Add a tax rate link. Step 6 − It will open the taxes window for adding tax rate to the product as shown in the following screen. It contains some fields such as − Title − It is the title of the tax rate. Title − It is the title of the tax rate. Display title − It is the front-end display title of the tax rate shown to customers. Display title − It is the front-end display title of the tax rate shown to customers. Description − It is used to describe the tax rate. Description − It is used to describe the tax rate. Rate − It is a percentage used to calculate the tax which is expressed as a decimal. Rate − It is a percentage used to calculate the tax which is expressed as a decimal. Type − It selects the tax type for the tax rate using drop-down menu. Type − It selects the tax type for the tax rate using drop-down menu. After filling the details, click the Save tax rate button. Step 7 − Once tax rate is saved, click the Home link. Step 8 − On the home page, click the Checkout link to see the shopping cart contents. Step 9 − On the checkout page, you will see the discount for the product which is included in product price. In this chapter, we will learn how to Receive Donation in Drupal. Donation is some amount of gift given by an organization or individual to a non-profit organization or private foundation. Following are the steps to receive donation in Drupal. Step 1 − Download the latest file of Commerce Custom Line Items module and install in your Drupal site. Step 2 − Enable the Commerce Custom Line Items and Others in Modules and click Save configuration. Step 3 − Next, go to Store --> Configuration Step 4 − Click on Line item types. Step 5 − Then, click Add line item types to add items. Step 6 − Now, Add line item type page will get displayed as shown in the following screen. It contains fields such as − Line item type name − Enter the name of the line item type. Line item type name − Enter the name of the line item type. Description − Enter a brief description about the line item type. Description − Enter a brief description about the line item type. Add form submit value − Enter the text of the button on the order page which allows adding line items. Add form submit value − Enter the text of the button on the order page which allows adding line items. Step 7 − You can view the created donation item in the list. Click manage fields. Step 8 − Add a new field as Donation Amount, Select Integer for type of data from the dropdown. Click the Save button. Step 9 − Now, after clicking on save, the page redirects to the field setting page as shown in the following screen. Click the Save field settings button. Step 10 − The page is redirected to the Donation Amount page. It contains fields such as − Label − Donation type identifier. Label − Donation type identifier. Help text − Enter instructions to present to the user. Help text − Enter instructions to present to the user. Minimum − Enter the minimum value that should be allowed. Minimum − Enter the minimum value that should be allowed. Maximum − Enter the maximum value that should be allowed. Maximum − Enter the maximum value that should be allowed. Prefix − Enter the string that should be prefixed to the value. Prefix − Enter the string that should be prefixed to the value. Suffix − Enter the string that should be suffixed to the value. Suffix − Enter the string that should be suffixed to the value. Default Value − Enter the default donation amount. Default Value − Enter the default donation amount. Add to Cart Form Settings − Includes the product line item types in the ‘add to cart form’ to collect information. Add to Cart Form Settings − Includes the product line item types in the ‘add to cart form’ to collect information. Donation Amount Field settings − Number of values user can enter for this field. Donation Amount Field settings − Number of values user can enter for this field. After filling the page, click the Save settings button. Step 11 − Next, you can view the created Donation Amount field in the list. Following are the steps to create product for donation. Step 1 − Click on Store --> Products Step 2 − Click Add a product to add product. Step 3 − Next, it will open a Create Product screen as shown in the following screen. It contain fields such as − Product SKU − It is a unique identifier for the product. Product SKU − It is a unique identifier for the product. Title − It is title for the specified product. Title − It is title for the specified product. Image − Add image for the product. Image − Add image for the product. Price − Enter the amount of the product. Price − Enter the amount of the product. Status − Set this field to Active option, so that it can be added to shopping cart. If it set to Disabled option, products cannot be added to shopping carts and may be hidden in administrative product lists. Status − Set this field to Active option, so that it can be added to shopping cart. If it set to Disabled option, products cannot be added to shopping carts and may be hidden in administrative product lists. After filling all the details, click the Save product button. Step 4 − Now you can see the newly created product as shown in the following screen. Step 5 − Go to Structure --> Content Types. The following page will get displayed, click Add content type. Step 6 − Add a name as Donation and click Save and add fields. Step 7 − It will open the Manage Fields tab as shown in the following screen. Add fields into Add existing field section as Product and select Product reference from the dropdown and click the Save button. Step 8 − Now, Product page will get displayed, click the Save settings button. Step 9 − You can view the created Product field in the list. Step 10 − Now, click the Manage Display tab. Click the symbol present on the right side of the field Product, and the following screen will get displayed. Here, Select as Donation from the dropdown in Add to Cart line item type. Later click the Update button and then on Save button. Step 11 − Next, click Content --> Add Content to add donation information. Step 12 − Click on Donation. Step 13 − Enter your Donation information and click the Save button. Step 14 − The page of donation will get displayed as shown in the following screen. Here, you can fill the amount according to your wish and click the Add to cart button. Step 15 − Now, you can view the donation amounts in the block present on the right side of the page. Click View Cart. Step 16 − You can view the Shopping cart donation amount and click the Checkout button. Step 17 − Now, you can enter the information of billing and click Continue to next step. Step 18 − The next step is the review order page, where you can review the order information and click Continue to next step. Step 19 − A message will get displayed as Checkout complete as shown in the following screen. In this chapter, let us study about setting up Shipping options in Drupal. In general, Shipping refers to transport of goods from one location to another. In order to set up Shipping you have to install Commerce Flat Rate and Commerce Shipping modules. In this chapter, let us create Free Shipping for orders greater than $100 and Paid Shipping for orders less than $100. Following are the simple steps to set up Shipping. Step 1 − Go to Store and click Configuration as shown in the following screen. Step 2 − Click on Shipping. Step 3 − Click Add a flat rate service as shown in the following screen. Step 4 − The Shipping page will get displayed as shown in the following screen. It contains the following fields − Title − Provide a title which will be the administrative title of this flat rate. Title − Provide a title which will be the administrative title of this flat rate. Display title − Enter title that will be displayed on front-end of the flat rate shown to customers. Display title − Enter title that will be displayed on front-end of the flat rate shown to customers. Description − Enter brief description about the flat rate. Description − Enter brief description about the flat rate. Base rate − Provide a value for the flat rate. Base rate − Provide a value for the flat rate. Later, click the Save button. Step 5 − Next, you have to configure the component by clicking configure component as shown in the following screen. Step 6 − Click Add condition. Step 7 − Choose Data comparison from dropdown and click Continue. Step 8 − For Data selector field, choose commerce-order...(Order) from the dropdown as shown in the following screen. Step 9 − Then, choose commerce-order:commerce-order-total:... (Order total) from the dropdown as shown in the following screen. Step 10 − Choose commerce-order:commerce-order-total:amount (Amount) from the dropdown and click Continue as shown in the following screen. Step 11 − Next, under OPERATOR section, you have to select is lower than value from the dropdown and click Switch to the direct input mode as shown below. Step 12 − Under DATA VALUE section, provide the value (usually the value given here is in cents (i.e. $100 = 10000 cents)). Later, click the Save button. Step 13 − Click Save changes as shown in the following screen. Step 14 − For Free Shipping you have to create another Flat rate service (as we did in Step(3 and 4)) and provide zero(0) for Base rate as shown in the following screen. Step 15 − Configure the component for Free Shipping (follow the same steps from 5 to 10 for free shipping as well), choose ‘is greater than’ and provide 10000 (i.e. 10000 cents) value as shown in the following screen and click the Save button. Step 16 − Add a product to the cart which is less than $100 and click the Check out tab. Step 17 − Next, fill up Shipping information, Billing information and click Continue to next step as shown in the following screen. Step 18 − Now you can see the Paid Shipping option displayed as shown in the following screen. Step 19 − You can add some more products, so that Order total exceeds $100. Step 20 − Finally, you can see that Free Shipping option is displayed after it exceeds the $100. In this chapter, we will study how to set up Payments in Drupal. Payment is a process of paying money in exchange of goods, services or both to a company or a person. Following are the steps to set up payments in Drupal. Step 1 − Download the latest file of Basic Payment module and PayPal Payment module from the link and install in your Drupal site. Step 2 − Next, Enable the Basic Payment and PayPal Payment in Modules and click Save configuration. Step 3 − Click Configuration --> Payment as shown in the following screen. Step 4 − Click Payment methods. Step 5 − Then, click Add payment method. Step 6 − Click PayPal Payments Standard. Step 7 − You have to fill the form for PayPal payments. It contains the following fields − Title(specific) − Enter the specific title name. Title(specific) − Enter the specific title name. Title(generic) − Enter the generic title name. Title(generic) − Enter the generic title name. Owner − Enter the name of the owner. Owner − Enter the name of the owner. PayPal account email address − Enter your email address. PayPal account email address − Enter your email address. Server − Select the server from either of the one i.e. Production or Sandbox. Server − Select the server from either of the one i.e. Production or Sandbox. Capture − Select either of the one capture method i.e. Manual or Automatic. Capture − Select either of the one capture method i.e. Manual or Automatic. Step 8 − You can view the above created PayPal in the following list. Step 9 − Next, go to Structure --> Content Types. The following page will get displayed, click Add content type. Step 10 − Create a content type name as Products and save it. Step 11 − You can view the created Products content in the list. Click manage fields. Step 12 − Add a new field as Buy Now, Select Payment form for type of data from the dropdown. Click the Save button. Step 13 − Now, you can view the created Buy Now field in the list. Step 14 − Go to Content, click Add content. Step 15 − Click Products. Step 16 − Enter your product information inside the fields as shown in the following screen and click the Save button. Step 17 − You can now view your content on your site as shown in the following screen. Click Pay button. Step 18 − You will be redirected to the offsite payment server to authorize the payment. Later, it will direct you to the PayPal site for future payments process. Step 19 − Once the payment process is complete, you can view the details of the payment as shown in the following screen. Step 20 − Go to Content --> Payments tab. Here, you can view the payment status of your product. In this chapter, we'll study how to generate invoice in Drupal. Invoice is a document with a statement of amount and cost, unique invoice number and tax information. Following are the steps to generate invoice in Drupal. Step 1 − Download the latest file of Invoice module and install in your Drupal site. Step 2 − Enable the Invoice in Modules and click Save configuration. Step 3 − Go to Store --> Invoices. Step 4 − Click Add Invoice. Step 5 − You can view the Add Invoice page. Invoice # − Enter the invoice id number sent to the customer. Invoice # − Enter the invoice id number sent to the customer. Company Name − Enter the company name who should pay the invoice. Company Name − Enter the company name who should pay the invoice. Invoice Amount in USD − Enter the amount that customer has to pay. Invoice Amount in USD − Enter the amount that customer has to pay. After filling the invoice details, click Add Invoice. Step 6 − Go to Store --> Invoice --> Manage Invoices. Here, you can view your pending and paid invoices. Copy the link given in the detail column and it'll redirect you to the checkout page. Step 7 − You can also pay by navigating to the given link localhost<Your Site Name>user/invoices/pay, it'll redirect you to Pay Invoice page as shown in the following screen. Here, you have to enter the invoice number and click Pay Invoice button. It will then redirect you to the Checkout page as shown in the following screen. You can enter the information for billing and click Continue to next step button. Step 8 − You can review the product information and also the invoice number and company name. Click on Continue to next step button. Step 9 − A final message will get displayed as Checkout complete as shown in the following screen. In this chapter, we will learn how to send E-mail Notifications to the owner or creator, when a new comment is posted to the article. E-mail Notification is an alert that a new mail has arrived in your mail box. Following are the simple steps to set up e-mail notification in Drupal. Step 1 − Click Configuration menu on Drupal. Step 2 − Next, click Rules link in the WORKFLOW section as shown in the following screen. Step 3 − Click Add new rule link. Step 4 − Next, the Rules page will get displayed as shown in the following screen. It contains the following fields − Name − Enter the name. Name − Enter the name. Tags − Enter the tags Tags − Enter the tags React on Event − Select the event where the notification should arrive. React on Event − Select the event where the notification should arrive. Restrict by Type − Select the type where you need to filter the values or events. Restrict by Type − Select the type where you need to filter the values or events. After filling all the fields, click the Save button to save the rule. Step 5 − Now, Editing reaction rule "Comment Notification" page gets displayed. Click Add action link in Actions section as shown in the following screen. Step 6 − Add a new action page gets displayed. Select Send mail option in System section from the dropdown menu. Step 7 − Next, a page will get displayed as shown in the following screen. Following are the details about the fields present in the preceding screen. Data selector − Select comment→node→author→mail from the dropdown menu. Data selector − Select comment→node→author→mail from the dropdown menu. Subject − Enter the mail subject in the Value text box. Subject − Enter the mail subject in the Value text box. REPLACEMENT PATTERNS − This data selection input mode may help you find more complex replacement patterns. You can select the TOKEN type and replace it as per demand. REPLACEMENT PATTERNS − This data selection input mode may help you find more complex replacement patterns. You can select the TOKEN type and replace it as per demand. MESSAGE − Enter mail's message body content in the message Value text box. MESSAGE − Enter mail's message body content in the message Value text box. FROM − It displays the mail address from which mails will be sent to the receiver. FROM − It displays the mail address from which mails will be sent to the receiver. LANGUAGE − It specifies the language used for getting the mail message and subject. You can choose the language from the dropdown menu. LANGUAGE − It specifies the language used for getting the mail message and subject. You can choose the language from the dropdown menu. Click the Save button to save the notification. Step 8 − You will see the following screen, after you save your notification. Order history is dependent on the ordered products by the user after checkout. It includes history of the product which includes order number, user name, order status etc. You can view the order history of the product by using the following steps − Step 1 − Go to Store and click the Orders link. Step 2 − You will get the screen of the ordered products list. It contains fields such as − Order Number − It is the order number of product. Order Number − It is the order number of product. Updated − It specifies when the product has been updated last. Updated − It specifies when the product has been updated last. Name − It is the name of the user who has ordered the product. Name − It is the name of the user who has ordered the product. User − It is the account name of the user. It may be authenticated by user or admin. User − It is the account name of the user. It may be authenticated by user or admin. Total − It specifies total amount of the ordered product. Total − It specifies total amount of the ordered product. Order Status − Defines the order status such as processing or pending or completed or cancelled. Order Status − Defines the order status such as processing or pending or completed or cancelled. Operations − Here you can perform some operations on the product such as − Operations − Here you can perform some operations on the product such as − View option displays the billing information and shipping information. View option displays the billing information and shipping information. Edit option allows to edit the price, shipping information, billing information etc. Edit option allows to edit the price, shipping information, billing information etc. Delete option deletes the product order and payment option specifies paid amount for the product, date of expiry, etc.. Delete option deletes the product order and payment option specifies paid amount for the product, date of expiry, etc.. 61 Lectures 3.5 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 3259, "s": 2827, "text": "Drupal is a free and open source Content Management System (CMS) that allows organizing, managing and publishing your content. It is built on PHP based environments. This is carried out under GNU i.e. General Public License, which means everyone has the freedom of downloading and sharing it with others. Drupal is used on million sites such as WhiteHouse.gov, World Economic Forum, Stanford University, Examiner.com and many more." }, { "code": null, "e": 3514, "s": 3259, "text": "The Content Management System (CMS) is a software which stores all the data of your content (such as text, photos, music, documents, etc.) and is made available on your website. A CMS helps in editing, publishing and modifying the content of the website." }, { "code": null, "e": 3676, "s": 3514, "text": "The standard release of Drupal known as Drupal core was developed by Dries Buytaerti in January 2001. It is considered as a leading CMS in variety of industries." }, { "code": null, "e": 4218, "s": 3676, "text": "If you are developing a website with content management system, Drupal CMS is very flexible than any other CMS. Drupal is very powerful and can be used for building large, complex sites. It is PHP based template and allows non-technical users to add and edit the content without any HTML or Web design knowledge. Using Drupal CMS, it is easy to interact with other sites or technologies as Drupal can handle complex forms and workflows. It is available with more than 16000 modules which can be addressed with Drupal core and add-on modules." }, { "code": null, "e": 4271, "s": 4218, "text": "Drupal makes it easy to create and manage your site." }, { "code": null, "e": 4324, "s": 4271, "text": "Drupal makes it easy to create and manage your site." }, { "code": null, "e": 4396, "s": 4324, "text": "Drupal translates anything in the system with built-in user interfaces." }, { "code": null, "e": 4468, "s": 4396, "text": "Drupal translates anything in the system with built-in user interfaces." }, { "code": null, "e": 4582, "s": 4468, "text": "Drupal connects your website to other sites and services using feeds, search engine connection capabilities, etc." }, { "code": null, "e": 4696, "s": 4582, "text": "Drupal connects your website to other sites and services using feeds, search engine connection capabilities, etc." }, { "code": null, "e": 4765, "s": 4696, "text": "Drupal is an open source software hence requires no licensing costs." }, { "code": null, "e": 4834, "s": 4765, "text": "Drupal is an open source software hence requires no licensing costs." }, { "code": null, "e": 4959, "s": 4834, "text": "Drupal designs highly flexible and creative website with effective display quality thus increasing the visitors to the site." }, { "code": null, "e": 5084, "s": 4959, "text": "Drupal designs highly flexible and creative website with effective display quality thus increasing the visitors to the site." }, { "code": null, "e": 5184, "s": 5084, "text": "Drupal can publish your content on social media such as Twitter, Facebook and other social mediums." }, { "code": null, "e": 5284, "s": 5184, "text": "Drupal can publish your content on social media such as Twitter, Facebook and other social mediums." }, { "code": null, "e": 5440, "s": 5284, "text": "Drupal provides more number of customizable themes, including several base themes which are used to design your own themes for developing web applications." }, { "code": null, "e": 5596, "s": 5440, "text": "Drupal provides more number of customizable themes, including several base themes which are used to design your own themes for developing web applications." }, { "code": null, "e": 5709, "s": 5596, "text": "Drupal manages content on informational sites, social media sites, member sites, intranets and web applications." }, { "code": null, "e": 5822, "s": 5709, "text": "Drupal manages content on informational sites, social media sites, member sites, intranets and web applications." }, { "code": null, "e": 5953, "s": 5822, "text": "Drupal is a flexible CMS that allows handling content types including video, text, blog, menu handling, real-time statistics, etc." }, { "code": null, "e": 6084, "s": 5953, "text": "Drupal is a flexible CMS that allows handling content types including video, text, blog, menu handling, real-time statistics, etc." }, { "code": null, "e": 6254, "s": 6084, "text": "Drupal provides a number of templates for developing web applications. There is no need to start from scratch if you are building simple or complicated web applications." }, { "code": null, "e": 6424, "s": 6254, "text": "Drupal provides a number of templates for developing web applications. There is no need to start from scratch if you are building simple or complicated web applications." }, { "code": null, "e": 6533, "s": 6424, "text": "Drupal is easy to manage or create blog or website. It helps to organize, structure, find and reuse content." }, { "code": null, "e": 6642, "s": 6533, "text": "Drupal is easy to manage or create blog or website. It helps to organize, structure, find and reuse content." }, { "code": null, "e": 6741, "s": 6642, "text": "Drupal provides some interesting themes and templates which gives your website an attractive look." }, { "code": null, "e": 6840, "s": 6741, "text": "Drupal provides some interesting themes and templates which gives your website an attractive look." }, { "code": null, "e": 6959, "s": 6840, "text": "Drupal has over 7000 plug-ins to boost your website. Since Drupal is an open source, you can create your own plug-ins." }, { "code": null, "e": 7078, "s": 6959, "text": "Drupal has over 7000 plug-ins to boost your website. Since Drupal is an open source, you can create your own plug-ins." }, { "code": null, "e": 7213, "s": 7078, "text": "Drupal is not a user-friendly interface. It requires advanced knowledge and few basic things about the platform to install and modify." }, { "code": null, "e": 7348, "s": 7213, "text": "Drupal is not a user-friendly interface. It requires advanced knowledge and few basic things about the platform to install and modify." }, { "code": null, "e": 7433, "s": 7348, "text": "Drupal is a new content management system. It is not compatible with other software." }, { "code": null, "e": 7518, "s": 7433, "text": "Drupal is a new content management system. It is not compatible with other software." }, { "code": null, "e": 7684, "s": 7518, "text": "Performance is low compared to other CMS. The website which is built using Drupal will generate big server loads and will never open with a slow internet connection." }, { "code": null, "e": 7850, "s": 7684, "text": "Performance is low compared to other CMS. The website which is built using Drupal will generate big server loads and will never open with a slow internet connection." }, { "code": null, "e": 7995, "s": 7850, "text": "This chapter provides step-by-step procedure for Drupal installation. Before installing Drupal, the following system requirements are necessary." }, { "code": null, "e": 8019, "s": 7995, "text": "Database − MySQL 5.1 + " }, { "code": null, "e": 8043, "s": 8019, "text": "Database − MySQL 5.1 + " }, { "code": null, "e": 8147, "s": 8043, "text": "Web Server − \n\nWAMP (Windows)\nLAMP (Linux)\nXAMP (Multi-platform)\nMAMP (Macintosh)\nNginx\nMicrosoft IIS\n\n" }, { "code": null, "e": 8162, "s": 8147, "text": "Web Server − \n" }, { "code": null, "e": 8177, "s": 8162, "text": "WAMP (Windows)" }, { "code": null, "e": 8192, "s": 8177, "text": "WAMP (Windows)" }, { "code": null, "e": 8205, "s": 8192, "text": "LAMP (Linux)" }, { "code": null, "e": 8218, "s": 8205, "text": "LAMP (Linux)" }, { "code": null, "e": 8240, "s": 8218, "text": "XAMP (Multi-platform)" }, { "code": null, "e": 8262, "s": 8240, "text": "XAMP (Multi-platform)" }, { "code": null, "e": 8279, "s": 8262, "text": "MAMP (Macintosh)" }, { "code": null, "e": 8296, "s": 8279, "text": "MAMP (Macintosh)" }, { "code": null, "e": 8302, "s": 8296, "text": "Nginx" }, { "code": null, "e": 8308, "s": 8302, "text": "Nginx" }, { "code": null, "e": 8322, "s": 8308, "text": "Microsoft IIS" }, { "code": null, "e": 8336, "s": 8322, "text": "Microsoft IIS" }, { "code": null, "e": 8370, "s": 8336, "text": "Operating System − Cross-platform" }, { "code": null, "e": 8404, "s": 8370, "text": "Operating System − Cross-platform" }, { "code": null, "e": 8487, "s": 8404, "text": "Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera" }, { "code": null, "e": 8570, "s": 8487, "text": "Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari, Opera" }, { "code": null, "e": 8650, "s": 8570, "text": "SSL (Secure Socket Layer) − A valid security certificate is required for HTTPS " }, { "code": null, "e": 8730, "s": 8650, "text": "SSL (Secure Socket Layer) − A valid security certificate is required for HTTPS " }, { "code": null, "e": 8760, "s": 8730, "text": "PHP Compatibility − PHP 5.2+ " }, { "code": null, "e": 8790, "s": 8760, "text": "PHP Compatibility − PHP 5.2+ " }, { "code": null, "e": 8902, "s": 8790, "text": "Step 1 − Download the Drupal and copy to your web server from this link − https://www.drupal.org/project/drupal" }, { "code": null, "e": 9085, "s": 8902, "text": "Step 2 − Select the latest version of zip file which you want to download as shown in the following screen. The Recommended releases are the latest stable releases of either version." }, { "code": null, "e": 9205, "s": 9085, "text": "It's very easy to setup Drupal on your system. The following steps describe how to setup Drupal locally on your system." }, { "code": null, "e": 9365, "s": 9205, "text": "Step 1 − Download the zip file and extract it to your local computer. Rename the folder from its current name to any name of your choice to refer to your site." }, { "code": null, "e": 9562, "s": 9365, "text": "Step 2 − Drupal requires MySQL database. Create a new empty database with user/password for Drupal to use. (For e.g., user as \"root\" and password as \"root\" or else you can set as per your choice)." }, { "code": null, "e": 9822, "s": 9562, "text": "Step 3 − Open your browser and navigate to your Drupal file path, you will see the first Drupal installer screen as shown in the following image. In our case the path is localhost/< Your_drupal_folder >. Select the Standard option and click Save and continue." }, { "code": null, "e": 9879, "s": 9822, "text": "Step 4 − Select the default language for Drupal website." }, { "code": null, "e": 9934, "s": 9879, "text": "After selecting the language, click Save and continue." }, { "code": null, "e": 10066, "s": 9934, "text": "Step 5 − Go to Database configuration page. You need to enter the type of database you will be using, and other details as follows." }, { "code": null, "e": 10138, "s": 10066, "text": "Database Type − Select the database type. By default, it will be MySQL." }, { "code": null, "e": 10210, "s": 10138, "text": "Database Type − Select the database type. By default, it will be MySQL." }, { "code": null, "e": 10262, "s": 10210, "text": "Database name − Enter the database name for Drupal." }, { "code": null, "e": 10314, "s": 10262, "text": "Database name − Enter the database name for Drupal." }, { "code": null, "e": 10378, "s": 10314, "text": "Database username − Enter the user name of your MySQL database." }, { "code": null, "e": 10442, "s": 10378, "text": "Database username − Enter the user name of your MySQL database." }, { "code": null, "e": 10519, "s": 10442, "text": "Database password − Enter the password which you had set for MySQL Database." }, { "code": null, "e": 10596, "s": 10519, "text": "Database password − Enter the password which you had set for MySQL Database." }, { "code": null, "e": 10669, "s": 10596, "text": "When you click the ADVANCED OPTIONS, you will see the following screen −" }, { "code": null, "e": 10722, "s": 10669, "text": "You can fill the advanced options for the database −" }, { "code": null, "e": 10790, "s": 10722, "text": "Database Host − Enter the host name where your database is located." }, { "code": null, "e": 10858, "s": 10790, "text": "Database Host − Enter the host name where your database is located." }, { "code": null, "e": 10899, "s": 10858, "text": "Database port − Enter the database port." }, { "code": null, "e": 10940, "s": 10899, "text": "Database port − Enter the database port." }, { "code": null, "e": 11060, "s": 10940, "text": "Table Prefix − It is used to add prefix in the database tables, which helps to run multiple sites on the same database." }, { "code": null, "e": 11180, "s": 11060, "text": "Table Prefix − It is used to add prefix in the database tables, which helps to run multiple sites on the same database." }, { "code": null, "e": 11251, "s": 11180, "text": "After filling all the information, click the Save and continue button." }, { "code": null, "e": 11309, "s": 11251, "text": "Step 6 − The installation process starts on your machine." }, { "code": null, "e": 11366, "s": 11309, "text": "Step 7 − The Configure site page appears on the screen −" }, { "code": null, "e": 11401, "s": 11366, "text": "It contains the following fields −" }, { "code": null, "e": 11458, "s": 11401, "text": "Site name − The name that you want to give to your site." }, { "code": null, "e": 11515, "s": 11458, "text": "Site name − The name that you want to give to your site." }, { "code": null, "e": 11597, "s": 11515, "text": "Site e-mail address − The e-mail address to which automated e-mails will be sent." }, { "code": null, "e": 11679, "s": 11597, "text": "Site e-mail address − The e-mail address to which automated e-mails will be sent." }, { "code": null, "e": 11789, "s": 11679, "text": "Username, Email-address and Password − These are all administrative details used for the maintenance account." }, { "code": null, "e": 11899, "s": 11789, "text": "Username, Email-address and Password − These are all administrative details used for the maintenance account." }, { "code": null, "e": 11963, "s": 11899, "text": "You need to enter all these fields and click Save and continue." }, { "code": null, "e": 12074, "s": 11963, "text": "Step 8 − The following page indicating that your Drupal installation is successful will appear on your screen." }, { "code": null, "e": 12142, "s": 12074, "text": "Step 9 − Click the Visit your new site link as shown in this image." }, { "code": null, "e": 12252, "s": 12142, "text": "Step 10 − Finally, the newly installed Drupal homepage appears on your screen as seen in the preceding image." }, { "code": null, "e": 12530, "s": 12252, "text": "Drupal is a platform for web content management which is a powerful tool for building simple and complex sites. In this chapter, we are going to discuss the architectural style of Drupal for implementing user interfaces. The following diagram shows the architecture of Drupal −" }, { "code": null, "e": 12595, "s": 12530, "text": "The architecture of Drupal contains the following layers &miuns;" }, { "code": null, "e": 12601, "s": 12595, "text": "Users" }, { "code": null, "e": 12607, "s": 12601, "text": "Users" }, { "code": null, "e": 12621, "s": 12607, "text": "Administrator" }, { "code": null, "e": 12635, "s": 12621, "text": "Administrator" }, { "code": null, "e": 12642, "s": 12635, "text": "Drupal" }, { "code": null, "e": 12649, "s": 12642, "text": "Drupal" }, { "code": null, "e": 12653, "s": 12649, "text": "PHP" }, { "code": null, "e": 12657, "s": 12653, "text": "PHP" }, { "code": null, "e": 12668, "s": 12657, "text": "Web Server" }, { "code": null, "e": 12679, "s": 12668, "text": "Web Server" }, { "code": null, "e": 12688, "s": 12679, "text": "Database" }, { "code": null, "e": 12697, "s": 12688, "text": "Database" }, { "code": null, "e": 12862, "s": 12697, "text": "Users − These are the users on the Drupal community. The user sends a request to a server using Drupal CMS and web browsers, search engines, etc. acts like clients." }, { "code": null, "e": 13091, "s": 12862, "text": "Administrator − Administrator can provide access permission to authorized users and will be able to block unauthorized access. Administrative account will be having all privileges for managing content and administering the site." }, { "code": null, "e": 13503, "s": 13091, "text": "Drupal − Drupal is a free and open source Content Management System (CMS) that allows organizing, managing and publishing your content and is built on PHP based environments. Drupal CMS is very flexible and powerful and can be used for building large, complex sites. It is very easy to interact with other sites and technologies using Drupal CMS. Further, you will be able to handle complex forms and workflows." }, { "code": null, "e": 13814, "s": 13503, "text": "PHP − Drupal uses PHP in order to work with an application which is created by a user. It takes the help of web server to fetch data from the database. PHP memory requirements depend on the modules which are used in your site. Drupal 6 requires at least 16MB, Drupal 7 requires 32MB and Drupal 8 requires 64MB." }, { "code": null, "e": 14149, "s": 13814, "text": "Web Server − Web server is a server where the user interacts and processes requests via HTTP (Hyper Text Transfer Protocol) and serves files that form web pages to web users. The communication between the user and the server takes place using HTTP. You can use different types of web servers such as Apache, IIS, Nginx, Lighttpd, etc." }, { "code": null, "e": 14420, "s": 14149, "text": "Database − Database stores the user information, content and other required data of the site. It is used to store the administrative information to manage the Drupal site. Drupal uses the database to extract the data and enables to store, modify and update the database." }, { "code": null, "e": 14674, "s": 14420, "text": "In this chapter, we will study how to Create Menus in Drupal. Menus are very important to easily navigate in your website. Menus offer a set of links that helps you navigate. The Drupal menu allows you to add, remove and rename the menus and menu items." }, { "code": null, "e": 14732, "s": 14674, "text": "Following are the simple steps to create menus in Drupal." }, { "code": null, "e": 14799, "s": 14732, "text": "Step 1 − Click Structure → Menus as shown in the following screen." }, { "code": null, "e": 14846, "s": 14799, "text": "Step 2 − Click on Add menu option to add menu." }, { "code": null, "e": 14918, "s": 14846, "text": "Step 3 − Fill in the required details as shown in the following screen." }, { "code": null, "e": 14975, "s": 14918, "text": "Title − It displays title in the Administrator Menu bar." }, { "code": null, "e": 15032, "s": 14975, "text": "Title − It displays title in the Administrator Menu bar." }, { "code": null, "e": 15230, "s": 15032, "text": "Description − Enter a brief description about the menu. The description field will display only in the admin dashboard under the menu list, but it does not display any information to site visitors." }, { "code": null, "e": 15428, "s": 15230, "text": "Description − Enter a brief description about the menu. The description field will display only in the admin dashboard under the menu list, but it does not display any information to site visitors." }, { "code": null, "e": 15530, "s": 15428, "text": "After filling all the information about the menu, click on Save button to save your created menu bar." }, { "code": null, "e": 15722, "s": 15530, "text": "Step 4 − Once you save the menu bar, the following screen will get displayed. Here you have to define the path link to your created menu page. Click Add link as shown in the following screen." }, { "code": null, "e": 15804, "s": 15722, "text": "Step 5 − The created Menu 1 page gets displayed as shown in the following screen." }, { "code": null, "e": 15831, "s": 15804, "text": "It contains below fields −" }, { "code": null, "e": 15883, "s": 15831, "text": "Menu link title− Specify the name of the menu item." }, { "code": null, "e": 15935, "s": 15883, "text": "Menu link title− Specify the name of the menu item." }, { "code": null, "e": 16002, "s": 15935, "text": "Path − Specify the URL path of the page which you want to display." }, { "code": null, "e": 16069, "s": 16002, "text": "Path − Specify the URL path of the page which you want to display." }, { "code": null, "e": 16116, "s": 16069, "text": "Description − Description about the menu link." }, { "code": null, "e": 16163, "s": 16116, "text": "Description − Description about the menu link." }, { "code": null, "e": 16213, "s": 16163, "text": "Enabled − It enables the item to display on menu." }, { "code": null, "e": 16263, "s": 16213, "text": "Enabled − It enables the item to display on menu." }, { "code": null, "e": 16366, "s": 16263, "text": "Show as expanded − If it consists of sub menus, then it will be displayed under the parent menu item.\n" }, { "code": null, "e": 16468, "s": 16366, "text": "Show as expanded − If it consists of sub menus, then it will be displayed under the parent menu item." }, { "code": null, "e": 16518, "s": 16468, "text": "Parent Link − It sets the main structure of menu." }, { "code": null, "e": 16568, "s": 16518, "text": "Parent Link − It sets the main structure of menu." }, { "code": null, "e": 16607, "s": 16568, "text": "Weight − Sets the order of menu items." }, { "code": null, "e": 16646, "s": 16607, "text": "Weight − Sets the order of menu items." }, { "code": null, "e": 16755, "s": 16646, "text": "After filling all the information about the menu link, click the Save button, this will save your Menu link." }, { "code": null, "e": 16797, "s": 16755, "text": "Step 6− Now the following screen pops up." }, { "code": null, "e": 16859, "s": 16797, "text": "Step 7 − Click Structure → Menus to get the following screen." }, { "code": null, "e": 16924, "s": 16859, "text": "Here, you will see the created Menu 1 name in the list of Menus." }, { "code": null, "e": 17120, "s": 16924, "text": "In this chapter, we will study about Drupal Blocks & Regions. Blocks are container objects that are used to organize your content of your website. It can be displayed in the regions on your page." }, { "code": null, "e": 17179, "s": 17120, "text": "Following are the simple steps for creating Drupal Blocks." }, { "code": null, "e": 17248, "s": 17179, "text": "Step 1 − Click Structure in Drupal as shown in the following screen." }, { "code": null, "e": 17277, "s": 17248, "text": "Step 2 − Then, click Blocks." }, { "code": null, "e": 17331, "s": 17277, "text": "Step 3 − Blocks page gets displayed. Click Add block." }, { "code": null, "e": 17436, "s": 17331, "text": "Step 4 − A block page will gets displayed to create a new custom block as shown in the following screen." }, { "code": null, "e": 17484, "s": 17436, "text": "The following fields appear on the Blocks page." }, { "code": null, "e": 17499, "s": 17484, "text": "Block Settings" }, { "code": null, "e": 17514, "s": 17499, "text": "Block Settings" }, { "code": null, "e": 17560, "s": 17514, "text": "Block title − Enter the title for your block." }, { "code": null, "e": 17606, "s": 17560, "text": "Block title − Enter the title for your block." }, { "code": null, "e": 17661, "s": 17606, "text": "Block description − Enter the description about block." }, { "code": null, "e": 17716, "s": 17661, "text": "Block description − Enter the description about block." }, { "code": null, "e": 17761, "s": 17716, "text": "Block body − Enter the content of the block." }, { "code": null, "e": 17806, "s": 17761, "text": "Block body − Enter the content of the block." }, { "code": null, "e": 17899, "s": 17806, "text": "Text format − Select the format for your text i.e. Filtered HTML, Full HTML, and Plain text." }, { "code": null, "e": 17992, "s": 17899, "text": "Text format − Select the format for your text i.e. Filtered HTML, Full HTML, and Plain text." }, { "code": null, "e": 18008, "s": 17992, "text": "Region Settings" }, { "code": null, "e": 18024, "s": 18008, "text": "Region Settings" }, { "code": null, "e": 18098, "s": 18024, "text": "Bartik (default theme) − Select the region to display block in the theme." }, { "code": null, "e": 18172, "s": 18098, "text": "Bartik (default theme) − Select the region to display block in the theme." }, { "code": null, "e": 18267, "s": 18172, "text": "Seven (administration theme) − Select the region to display block in the administration theme." }, { "code": null, "e": 18362, "s": 18267, "text": "Seven (administration theme) − Select the region to display block in the administration theme." }, { "code": null, "e": 18381, "s": 18362, "text": "Visibility Setting" }, { "code": null, "e": 18400, "s": 18381, "text": "Visibility Setting" }, { "code": null, "e": 18458, "s": 18400, "text": "Page − Allows displaying blocks on all or specific pages." }, { "code": null, "e": 18516, "s": 18458, "text": "Page − Allows displaying blocks on all or specific pages." }, { "code": null, "e": 18611, "s": 18516, "text": "Content Types − Allows to display the blocks in specific content, i.e. Article or Basic Page." }, { "code": null, "e": 18706, "s": 18611, "text": "Content Types − Allows to display the blocks in specific content, i.e. Article or Basic Page." }, { "code": null, "e": 18836, "s": 18706, "text": "Roles − Allows displaying the blocks for specific types of users, i.e. anonymous user, authenticated user, or administrator user." }, { "code": null, "e": 18966, "s": 18836, "text": "Roles − Allows displaying the blocks for specific types of users, i.e. anonymous user, authenticated user, or administrator user." }, { "code": null, "e": 19047, "s": 18966, "text": "Users − Allows each user to customize the visibility of block in their settings." }, { "code": null, "e": 19128, "s": 19047, "text": "Users − Allows each user to customize the visibility of block in their settings." }, { "code": null, "e": 19184, "s": 19128, "text": "Now, click the Save block after filling all the fields." }, { "code": null, "e": 19258, "s": 19184, "text": "Step 5 − You can view the created block as shown in the following screen." }, { "code": null, "e": 19606, "s": 19258, "text": "In this chapter, let us study about Themes and Layouts. Drupal will install Bartik theme as default theme during installation. You can select paid or free themes from Drupal official site. In general, layout is an arrangement of text and graphics. It is a good thought to choose a theme, keeping in mind what different layouts to use on your site." }, { "code": null, "e": 19665, "s": 19606, "text": "Step 1 − Go to Drupal official site and click Get Started." }, { "code": null, "e": 19728, "s": 19665, "text": "Step 2 − Click on All Themes as shown in the following screen." }, { "code": null, "e": 19965, "s": 19728, "text": "Step 3 − You will get a list of themes. Select theme of your choice (let us select Adaptive theme as it consists Layout & General Settings, which will be covered later in this chapter) and click Version as shown in the following screen." }, { "code": null, "e": 20066, "s": 19965, "text": "Step 4 − Next, right click Download file and copy the link address as shown in the following screen." }, { "code": null, "e": 20237, "s": 20066, "text": "Step 5 − You can also download the theme directly by clicking on archive file and the module will be downloaded locally on your computer as shown in the following screen." }, { "code": null, "e": 20325, "s": 20237, "text": "Step 6 − Go to Appearance and click Install new theme as shown in the following screen." }, { "code": null, "e": 20451, "s": 20325, "text": "Step 7 − You can paste the link address you copied in step (4) and click the install button as shown in the following screen." }, { "code": null, "e": 20614, "s": 20451, "text": "Step 8 − You can also upload the theme archive, instead of copying the link address, if you have downloaded it and click Install as shown in the following screen." }, { "code": null, "e": 20688, "s": 20614, "text": "Step 9 − The following screen appears, wait until installation completes." }, { "code": null, "e": 20770, "s": 20688, "text": "Step 10 − Next, click Enable newly added themes as shown in the following screen." }, { "code": null, "e": 20895, "s": 20770, "text": "Step 11 − By default the themes are disabled. To enable them, click Enable and set default as shown in the following screen." }, { "code": null, "e": 20993, "s": 20895, "text": "Step 12 − Click on Settings as shown in the following screen to set the appearance for your site." }, { "code": null, "e": 21378, "s": 20993, "text": "Step 13 − The Layout & General Settings option pops up on the screen, in this Adaptive theme consists of Standard layout, Tablet Layout, Smalltouch layout and Panels & Gpanels. These options control the display settings for the current AT Admin theme that is already in use. When your site displays the theme, these settings will be used. Now, let us discuss these layouts one by one." }, { "code": null, "e": 21483, "s": 21378, "text": "Step 14 − In Standard layout you can choose layout for desktops, laptops and other large screen devices." }, { "code": null, "e": 21571, "s": 21483, "text": "Choose sidebar positions − You can choose sidebar position by clicking on radio button." }, { "code": null, "e": 21659, "s": 21571, "text": "Choose sidebar positions − You can choose sidebar position by clicking on radio button." }, { "code": null, "e": 21772, "s": 21659, "text": "Set the width of each sidebar − You can set width of first sidebar and second sidebar and unit in % or px or em." }, { "code": null, "e": 21885, "s": 21772, "text": "Set the width of each sidebar − You can set width of first sidebar and second sidebar and unit in % or px or em." }, { "code": null, "e": 21937, "s": 21885, "text": "Set the page width − You can set width of the page." }, { "code": null, "e": 21989, "s": 21937, "text": "Set the page width − You can set width of the page." }, { "code": null, "e": 22054, "s": 21989, "text": "Set a max width −You can check or uncheck to set maximum width. " }, { "code": null, "e": 22119, "s": 22054, "text": "Set a max width −You can check or uncheck to set maximum width. " }, { "code": null, "e": 22266, "s": 22119, "text": "Media query for this layout − Media query defines different style rules for different media devices and by default for this layout will be 1025px." }, { "code": null, "e": 22413, "s": 22266, "text": "Media query for this layout − Media query defines different style rules for different media devices and by default for this layout will be 1025px." }, { "code": null, "e": 22608, "s": 22413, "text": "Step 15 − Next, click Tablet Layout as shown in the following screen. Tablet devices will have two orientations Landscape and Portrait. You can configure a different layout for each orientation." }, { "code": null, "e": 22868, "s": 22608, "text": "Under Landscape tablet and Portrait tablet you can choose sidebar position, width of each sidebar and page width. Media query for Landscape tablet will be min-width:769px and max-width:1024px. For Portrait tablet it will be min-width:581px and max-width:768px" }, { "code": null, "e": 23074, "s": 22868, "text": "Step 16 − Now, click Smalltouch Layout as shown in the following screen. Smalltouch layout will also have two orientations Landscape and Portrait. You can configure a different layout for each orientation." }, { "code": null, "e": 23395, "s": 23074, "text": "In Landscape Smalltouch you can choose sidebar position and set width. The Portrait Smalltouch always displays in one column with sidebars stacked horizontally below the main content. Media query for Landscape Smalltouch will be min-width:321px and max-width:580px and for Portrait Smalltouch it will be max-width:320px." }, { "code": null, "e": 23656, "s": 23395, "text": "Step 17 − Next, click Panels & Gpanels as shown in the following screen. Adaptive theme supports responsive Panels and Gpanel layouts. To use this capability, you can use the Panels module, Display Suite (with Panels) or Adaptive themes native Gpanels layouts." }, { "code": null, "e": 23747, "s": 23656, "text": "You can select options for each device range and layout their type. Let us see one by one." }, { "code": null, "e": 23988, "s": 23747, "text": "Under Standard layout you can select the layouts you want to use when the site is being viewed in standard layout. By clicking on TWO, THREE, FOUR, FIVE, SIX or INSET, you can select the columns arrangement as shown in the following screen." }, { "code": null, "e": 24229, "s": 23988, "text": "Under Standard layout you can select the layouts you want to use when the site is being viewed in standard layout. By clicking on TWO, THREE, FOUR, FIVE, SIX or INSET, you can select the columns arrangement as shown in the following screen." }, { "code": null, "e": 24322, "s": 24229, "text": "Follow the same step for TABLET LANDSCAPE, TABLET PORTRAIT and SMALLTOUCH LANDSCAPE layouts." }, { "code": null, "e": 24415, "s": 24322, "text": "Follow the same step for TABLET LANDSCAPE, TABLET PORTRAIT and SMALLTOUCH LANDSCAPE layouts." }, { "code": null, "e": 24525, "s": 24415, "text": "Step 18 − Once done with all your configurations, click Save configurations as shown in the following screen." }, { "code": null, "e": 24774, "s": 24525, "text": "In this chapter, let us study how to create Front Page in Drupal. If you have good content on your website and expect your visitor to see that particular content first, then that article must be on the front page. Drupal provides solution for this." }, { "code": null, "e": 24842, "s": 24774, "text": "Following are the simple steps used for creating Drupal Front Page." }, { "code": null, "e": 24899, "s": 24842, "text": "Step 1 − Click Content as shown in the following screen." }, { "code": null, "e": 25005, "s": 24899, "text": "Step 2 − A list of articles and pages pop up on screen. Click edit link as shown in the following screen." }, { "code": null, "e": 25107, "s": 25005, "text": "Step 3 − Then, click Publishing option and check mark all the boxes as shown in the following screen." }, { "code": null, "e": 25167, "s": 25107, "text": "Following are the functions of the checkboxes on the page −" }, { "code": null, "e": 25233, "s": 25167, "text": "Published − Publish your page or article by marking the check box" }, { "code": null, "e": 25299, "s": 25233, "text": "Published − Publish your page or article by marking the check box" }, { "code": null, "e": 25388, "s": 25299, "text": "Promoted to front page− Promote your page or article, to the front page of your website." }, { "code": null, "e": 25477, "s": 25388, "text": "Promoted to front page− Promote your page or article, to the front page of your website." }, { "code": null, "e": 25547, "s": 25477, "text": "Sticky at top of lists− Fixes your page at top of lists on your site." }, { "code": null, "e": 25617, "s": 25547, "text": "Sticky at top of lists− Fixes your page at top of lists on your site." }, { "code": null, "e": 25660, "s": 25617, "text": "Click the Save button to save the changes." }, { "code": null, "e": 25758, "s": 25660, "text": "Step 4− You will see your page on the front page of your website similar to the following screen." }, { "code": null, "e": 26010, "s": 25758, "text": "In this chapter, we will study about how to create Static Pages in Drupal. Let's add some static pages named About Us and Services. The main purpuse for using a static pages is speed and steadiness. Static websites are more faster than a dynamic site." }, { "code": null, "e": 26064, "s": 26010, "text": "Following are the simple steps to create static page." }, { "code": null, "e": 26109, "s": 26064, "text": "Step 1 − Click Content --> Add content link." }, { "code": null, "e": 26141, "s": 26109, "text": "Step 2 − Click on Basic pages." }, { "code": null, "e": 26221, "s": 26141, "text": "Step 3 − Create basic page will get displayed as shown in the following screen." }, { "code": null, "e": 26290, "s": 26221, "text": "Following are the details of the fields present in the above screen." }, { "code": null, "e": 26341, "s": 26290, "text": "Title − It specifies the title of the static page." }, { "code": null, "e": 26392, "s": 26341, "text": "Title − It specifies the title of the static page." }, { "code": null, "e": 26441, "s": 26392, "text": "Body − It displays the body content of the page." }, { "code": null, "e": 26490, "s": 26441, "text": "Body − It displays the body content of the page." }, { "code": null, "e": 26576, "s": 26490, "text": "URL path settings − You can specify alternative URL by which content can be accessed." }, { "code": null, "e": 26662, "s": 26576, "text": "URL path settings − You can specify alternative URL by which content can be accessed." }, { "code": null, "e": 26752, "s": 26662, "text": "Note − Don't add slash at the end or beginning of the URL alias or else it will not work." }, { "code": null, "e": 26939, "s": 26752, "text": "You can see about-us URL path has been added under URL alias heading. The process is same for both About Us and Services static pages, only the content will be changed as per the demand." }, { "code": null, "e": 27032, "s": 26939, "text": "You can click Publishing options and check the box of published option to publish your page." }, { "code": null, "e": 27137, "s": 27032, "text": "Step 4 − Click on About Us tab, you will see the created about us page as shown in the following screen." }, { "code": null, "e": 27243, "s": 27137, "text": "Step 5 − Click the Services tab, you will see the created services page as shown in the following screen." }, { "code": null, "e": 27425, "s": 27243, "text": "In this chapter, we will study how to Create Blogs in Drupal. Blog entries can be made public or private, for the site members, depending on which roles have access to view content." }, { "code": null, "e": 27488, "s": 27425, "text": "Following are the simple steps used for creating Drupal Blogs." }, { "code": null, "e": 27552, "s": 27488, "text": "Step 1 − Click on the Modules as shown in the following screen." }, { "code": null, "e": 27690, "s": 27552, "text": "Step 2 − Next, Check the box of Blog to install it. Enable the Blog module and click Save configuration as shown in the following screen." }, { "code": null, "e": 27752, "s": 27690, "text": "Step 3 − Now, click Content as shown in the following screen." }, { "code": null, "e": 27783, "s": 27752, "text": "Step 4 − Click on Add content." }, { "code": null, "e": 27813, "s": 27783, "text": "Step 5 − Click on Blog entry." }, { "code": null, "e": 27903, "s": 27813, "text": "Step 6 − You can add the content to blog as shown in the following screen and click Save." }, { "code": null, "e": 27979, "s": 27903, "text": "Following are the details about the fields present in the preceding screen." }, { "code": null, "e": 28022, "s": 27979, "text": "Title − It displays the title of the blog." }, { "code": null, "e": 28065, "s": 28022, "text": "Title − It displays the title of the blog." }, { "code": null, "e": 28109, "s": 28065, "text": "Body − It displays the content of the body." }, { "code": null, "e": 28153, "s": 28109, "text": "Body − It displays the content of the body." }, { "code": null, "e": 28283, "s": 28153, "text": "Publishing options − It allows you to publish your blog content on Front Page or you can stick at top of lists as per the demand." }, { "code": null, "e": 28413, "s": 28283, "text": "Publishing options − It allows you to publish your blog content on Front Page or you can stick at top of lists as per the demand." }, { "code": null, "e": 28478, "s": 28413, "text": "Step 7 − Once you are done, you will see your post on home page." }, { "code": null, "e": 28632, "s": 28478, "text": "In this chapter, we will study about creating articles in Drupal. Creating articles help your visitors know about the company and your website in detail." }, { "code": null, "e": 28691, "s": 28632, "text": "Following are the steps used to create articles in Drupal." }, { "code": null, "e": 28729, "s": 28691, "text": "Step 1 − Click Add content in Drupal." }, { "code": null, "e": 28819, "s": 28729, "text": "Step 2 − You will get the pop-up window as shown in the following screen. Select Article." }, { "code": null, "e": 28864, "s": 28819, "text": "Step 3 − You will get the following screen." }, { "code": null, "e": 28917, "s": 28864, "text": "Below are the fields present in Create Article page." }, { "code": null, "e": 28965, "s": 28917, "text": "Title − It specifies the title for new article." }, { "code": null, "e": 29013, "s": 28965, "text": "Title − It specifies the title for new article." }, { "code": null, "e": 29131, "s": 29013, "text": "Tags − Describes the content of your article. Tags contain those related words which are included into your articles." }, { "code": null, "e": 29249, "s": 29131, "text": "Tags − Describes the content of your article. Tags contain those related words which are included into your articles." }, { "code": null, "e": 29279, "s": 29249, "text": "Body − Enter the description." }, { "code": null, "e": 29309, "s": 29279, "text": "Body − Enter the description." }, { "code": null, "e": 29403, "s": 29309, "text": "Text format − It specifies the Text format such as Filtered HTML, Full HTML and Plain text." }, { "code": null, "e": 29497, "s": 29403, "text": "Text format − It specifies the Text format such as Filtered HTML, Full HTML and Plain text." }, { "code": null, "e": 29551, "s": 29497, "text": "Image − Upload images by choosing a particular file." }, { "code": null, "e": 29605, "s": 29551, "text": "Image − Upload images by choosing a particular file." }, { "code": null, "e": 29767, "s": 29605, "text": "When you click choose file, a pop-up window appears, you can select an image from your local file, once you choose a file, click Upload. The image gets uploaded." }, { "code": null, "e": 29931, "s": 29767, "text": "Menu settings − By clicking on Provide a menu link checkbox it shows all the related details of Menu such as Menu link title, Description, Parent item, and Weight." }, { "code": null, "e": 30095, "s": 29931, "text": "Menu settings − By clicking on Provide a menu link checkbox it shows all the related details of Menu such as Menu link title, Description, Parent item, and Weight." }, { "code": null, "e": 30187, "s": 30095, "text": "Revision information − Provides revised information if any changes are made in the article." }, { "code": null, "e": 30279, "s": 30187, "text": "Revision information − Provides revised information if any changes are made in the article." }, { "code": null, "e": 30360, "s": 30279, "text": "URL path settings − Add URL alias to access the content of article to the users." }, { "code": null, "e": 30441, "s": 30360, "text": "URL path settings − Add URL alias to access the content of article to the users." }, { "code": null, "e": 30539, "s": 30441, "text": "Comment settings − By selecting open or close, it allows others to write comment for the article." }, { "code": null, "e": 30637, "s": 30539, "text": "Comment settings − By selecting open or close, it allows others to write comment for the article." }, { "code": null, "e": 30735, "s": 30637, "text": "Authoring information − Specifies the authored name and the date when article has been authored." }, { "code": null, "e": 30833, "s": 30735, "text": "Authoring information − Specifies the authored name and the date when article has been authored." }, { "code": null, "e": 30964, "s": 30833, "text": "Publishing options − Allows options for articles to be Published, Promoted to front page and Sticky at top of lists for the users." }, { "code": null, "e": 31095, "s": 30964, "text": "Publishing options − Allows options for articles to be Published, Promoted to front page and Sticky at top of lists for the users." }, { "code": null, "e": 31167, "s": 31095, "text": "After filling all the details about the article, click the Save button." }, { "code": null, "e": 31278, "s": 31167, "text": "In this chapter, we will study about how to Create Pages in Drupal. It is very easy to create pages in Drupal." }, { "code": null, "e": 31341, "s": 31278, "text": "Following are the simple steps used to create pages in Drupal." }, { "code": null, "e": 31381, "s": 31341, "text": "Step 1 − Click Content in the top menu." }, { "code": null, "e": 31444, "s": 31381, "text": "Step 2− Click on Add content as shown in the following screen." }, { "code": null, "e": 31481, "s": 31444, "text": "Step 3− Click the Basic page option." }, { "code": null, "e": 31608, "s": 31481, "text": "Step 4− Create Basic page will get displayed where you need to fill all the required details as shown in the following screen." }, { "code": null, "e": 31678, "s": 31608, "text": "Following are the details of the fields present on Create Basic page." }, { "code": null, "e": 31723, "s": 31678, "text": "Title − It specifies the title for new page." }, { "code": null, "e": 31768, "s": 31723, "text": "Title − It specifies the title for new page." }, { "code": null, "e": 31817, "s": 31768, "text": "Body − It specifies the description of the page." }, { "code": null, "e": 31866, "s": 31817, "text": "Body − It specifies the description of the page." }, { "code": null, "e": 31973, "s": 31866, "text": "Text format − It specifies the Text format for your page such as Filtered HTML, Full HTML, and Plain text." }, { "code": null, "e": 32080, "s": 31973, "text": "Text format − It specifies the Text format for your page such as Filtered HTML, Full HTML, and Plain text." }, { "code": null, "e": 32233, "s": 32080, "text": "Menu settings − By clicking on checkbox Provide a menu link, it shows the details of Menu such as Menu link title, Description, Parent item, and Weight." }, { "code": null, "e": 32386, "s": 32233, "text": "Menu settings − By clicking on checkbox Provide a menu link, it shows the details of Menu such as Menu link title, Description, Parent item, and Weight." }, { "code": null, "e": 32491, "s": 32386, "text": "Revision information − It specifies to provide revise information, if any changes are made in the pages." }, { "code": null, "e": 32596, "s": 32491, "text": "Revision information − It specifies to provide revise information, if any changes are made in the pages." }, { "code": null, "e": 32692, "s": 32596, "text": "URL path settings − It specifies to add URL alias to access the content of pages to the users." }, { "code": null, "e": 32788, "s": 32692, "text": "URL path settings − It specifies to add URL alias to access the content of pages to the users." }, { "code": null, "e": 32884, "s": 32788, "text": "Comment settings − By selecting open or close, it allows displaying a comment box for the page." }, { "code": null, "e": 32980, "s": 32884, "text": "Comment settings − By selecting open or close, it allows displaying a comment box for the page." }, { "code": null, "e": 33077, "s": 32980, "text": "Authoring information − It specifies the authored name and the date when page has been authored." }, { "code": null, "e": 33174, "s": 33077, "text": "Authoring information − It specifies the authored name and the date when page has been authored." }, { "code": null, "e": 33308, "s": 33174, "text": "Publishing options − It specifies that the page should be Published, Promoted to front page and Sticky at top of lists for the users." }, { "code": null, "e": 33442, "s": 33308, "text": "Publishing options − It specifies that the page should be Published, Promoted to front page and Sticky at top of lists for the users." }, { "code": null, "e": 33624, "s": 33442, "text": "Once you complete adding the content to the page. Click the Save button to create the page. Before saving the details, you can also preview the filled page using the Preview button." }, { "code": null, "e": 33982, "s": 33624, "text": "In this chapter, let us study about Creating content. In Drupal, content type defines the style in which contents are collected and displayed. When you install Drupal, by default two content types will be fixed and they are Articles and Basic page. When you enable other core and contributed modules by visiting Modules you can also use other content types." }, { "code": null, "e": 34040, "s": 33982, "text": "Following are the simple steps used for creating content." }, { "code": null, "e": 34097, "s": 34040, "text": "Step 1 − Click Content as shown in the following screen." }, { "code": null, "e": 34161, "s": 34097, "text": "Step 2 − Click on Add content as shown in the following screen." }, { "code": null, "e": 34350, "s": 34161, "text": "Step 3 − You can choose any of the content type. We shall take Basic page as we have already studied about Articles and Blog entry. Click Basic page as shown below in the following screen." }, { "code": null, "e": 34502, "s": 34350, "text": "Step 4 − Next, you will see the screen as shown in the following screen. You can add content to the page and click the Save button to save the content." }, { "code": null, "e": 34578, "s": 34502, "text": "Following are the details about the fields present in the preceding screen." }, { "code": null, "e": 34622, "s": 34578, "text": "Title − It specifies the title of the page." }, { "code": null, "e": 34666, "s": 34622, "text": "Title − It specifies the title of the page." }, { "code": null, "e": 34705, "s": 34666, "text": "Body − Write the content of your page." }, { "code": null, "e": 34744, "s": 34705, "text": "Body − Write the content of your page." }, { "code": null, "e": 34797, "s": 34744, "text": "Menu setting − It allows you to provide a menu link." }, { "code": null, "e": 34850, "s": 34797, "text": "Menu setting − It allows you to provide a menu link." }, { "code": null, "e": 34929, "s": 34850, "text": "Revision Information It provides an explanation of the changes you are making." }, { "code": null, "e": 35008, "s": 34929, "text": "Revision Information It provides an explanation of the changes you are making." }, { "code": null, "e": 35122, "s": 35008, "text": "URL path settings − It allows you to optionally define an alternative URL, by which your content can be accessed." }, { "code": null, "e": 35236, "s": 35122, "text": "URL path settings − It allows you to optionally define an alternative URL, by which your content can be accessed." }, { "code": null, "e": 35355, "s": 35236, "text": "Comment Setting − It allows users to send their comments depending upon the permission you set that is Open or closed." }, { "code": null, "e": 35474, "s": 35355, "text": "Comment Setting − It allows users to send their comments depending upon the permission you set that is Open or closed." }, { "code": null, "e": 35537, "s": 35474, "text": "Authorizing information − It specifies the author information." }, { "code": null, "e": 35600, "s": 35537, "text": "Authorizing information − It specifies the author information." }, { "code": null, "e": 35739, "s": 35600, "text": "Publishing options − It permits you to promote your content to the front page and stick your content on top of the list on the front page." }, { "code": null, "e": 35878, "s": 35739, "text": "Publishing options − It permits you to promote your content to the front page and stick your content on top of the list on the front page." }, { "code": null, "e": 35981, "s": 35878, "text": "Step 5 − Finally, you can see your page will be created and displayed similar to the following screen." }, { "code": null, "e": 36154, "s": 35981, "text": "In this chapter, let us study how to Modify content in Drupal. You can modify any of the previously used content type's content such as Articles, Basic page and Blog entry." }, { "code": null, "e": 36213, "s": 36154, "text": "Following are the simple steps used for modifying content." }, { "code": null, "e": 36279, "s": 36213, "text": "Step 1 − Click the tab Content as shown in the following screen." }, { "code": null, "e": 36336, "s": 36279, "text": "Step 2 − You will see the same screen as the following." }, { "code": null, "e": 36530, "s": 36336, "text": "Step 3 − If you have lot of content you can use Filter to search the content that you want to modify. You can modify About us (About us page was created in the chapter Drupal - Create Content)." }, { "code": null, "e": 36643, "s": 36530, "text": "You can select the status of the content as shown in the following screen. Select published for About us status." }, { "code": null, "e": 36716, "s": 36643, "text": "Following are the details of the fields present in the preceding screen." }, { "code": null, "e": 36765, "s": 36716, "text": "Published − It displays all the published items." }, { "code": null, "e": 36814, "s": 36765, "text": "Published − It displays all the published items." }, { "code": null, "e": 36873, "s": 36814, "text": "Promoted − It displays the promoted items on your website." }, { "code": null, "e": 36932, "s": 36873, "text": "Promoted − It displays the promoted items on your website." }, { "code": null, "e": 37004, "s": 36932, "text": "Not promoted − It displays the items that not promoted on your website." }, { "code": null, "e": 37076, "s": 37004, "text": "Not promoted − It displays the items that not promoted on your website." }, { "code": null, "e": 37131, "s": 37076, "text": "Sticky − It displays the sticky items on your website." }, { "code": null, "e": 37186, "s": 37131, "text": "Sticky − It displays the sticky items on your website." }, { "code": null, "e": 37249, "s": 37186, "text": "Not sticky − It displays the non-sticky items on your website." }, { "code": null, "e": 37312, "s": 37249, "text": "Not sticky − It displays the non-sticky items on your website." }, { "code": null, "e": 37489, "s": 37312, "text": "You can select type of the content like Articles, Basic page or Blog entry. Select Basic page as About us type is Basic page, and click filter as shown in the following screen." }, { "code": null, "e": 37612, "s": 37489, "text": "Step 4 − Now you can see the filtered content as shown in the following screen. To edit the content, click the edit link." }, { "code": null, "e": 37666, "s": 37612, "text": "Step 5 − You can modify your content and click Save." }, { "code": null, "e": 37731, "s": 37666, "text": "Step 6 − You will see the following screen with updated content." }, { "code": null, "e": 37883, "s": 37731, "text": "In this chapter, let us study about Deleting content. You can delete any of the previously written content such as Articles, Basic page and Blog entry." }, { "code": null, "e": 37938, "s": 37883, "text": "Following are the simple steps used to delete content." }, { "code": null, "e": 37966, "s": 37938, "text": "Step 1 − Click the Content." }, { "code": null, "e": 38126, "s": 37966, "text": "Step 2 − You can delete About us (About us page was created in the chapter Drupal - Create Content), and click the delete tab as shown in the following screen." }, { "code": null, "e": 38319, "s": 38126, "text": "Step 3 − Next, you will see the following screen. You need to confirm deletion of the content. Click the Delete button if you want to delete or Cancel button if you want to cancel the process." }, { "code": null, "e": 38442, "s": 38319, "text": "Step 4 − Immediately, you will see a confirmation message as your page has been deleted, as shown in the following screen." }, { "code": null, "e": 38727, "s": 38442, "text": "In this chapter, let us study how to Publish content. Every content is either published or unpublished. Published content is open for visitors to view while unpublished content cannot be viewed. We can make use of this feature to hide the content from public view without deleting it." }, { "code": null, "e": 38811, "s": 38727, "text": "Following are the simple steps to enable or disable publishing options for content." }, { "code": null, "e": 38879, "s": 38811, "text": "Step 1 − Click on the Content tab as shown in the following screen." }, { "code": null, "e": 39063, "s": 38879, "text": "Step 2 − You can select any of the content. Let us choose About us (About us page was created in the chapter Drupal - Create Content), and click edit as shown in the following screen." }, { "code": null, "e": 39137, "s": 39063, "text": "Step 3 − Next, click Publishing options as shown in the following screen." }, { "code": null, "e": 39229, "s": 39137, "text": "Step 4 − Check the box of Published option and click Save as shown in the following screen." }, { "code": null, "e": 39302, "s": 39229, "text": "Following are the details of the fields present in the preceding screen." }, { "code": null, "e": 39349, "s": 39302, "text": "Published − It specifies to publish your page." }, { "code": null, "e": 39396, "s": 39349, "text": "Published − It specifies to publish your page." }, { "code": null, "e": 39474, "s": 39396, "text": "Promoted to front page − It displays your page on front page of your website." }, { "code": null, "e": 39552, "s": 39474, "text": "Promoted to front page − It displays your page on front page of your website." }, { "code": null, "e": 39641, "s": 39552, "text": "Sticky at top of lists − It displays your article or page, etc. at the top of the lists." }, { "code": null, "e": 39730, "s": 39641, "text": "Sticky at top of lists − It displays your article or page, etc. at the top of the lists." }, { "code": null, "e": 39794, "s": 39730, "text": "Step 5 − You can see the status of the content will be changed." }, { "code": null, "e": 39987, "s": 39794, "text": "In this chapter, we will study about Menu Management in Drupal. Menu Management is the important part to navigate through Drupal admin page. Following is the screen for Drupal Menu Management." }, { "code": null, "e": 40134, "s": 39987, "text": "It displays the list of articles or pages which are created. It is the first screen that will get displayed when you log into administration area." }, { "code": null, "e": 40332, "s": 40134, "text": "This feature can help you in creating, managing and finding new pages. The table gets displayed with the detail of the articles, i.e. status, title, updated, author and operation (Edit and delete)." }, { "code": null, "e": 40462, "s": 40332, "text": "Structure includes the blocks, manage content types, add new menu links to the site and manage administrative tagging of content." }, { "code": null, "e": 40597, "s": 40462, "text": "Block − Blocks are a container objects used to organize your content on your website. It can be displayed in the region on your page." }, { "code": null, "e": 40732, "s": 40597, "text": "Block − Blocks are a container objects used to organize your content on your website. It can be displayed in the region on your page." }, { "code": null, "e": 40820, "s": 40732, "text": "Content types − Content type defines the way the contents are collected and displayed." }, { "code": null, "e": 40908, "s": 40820, "text": "Content types − Content type defines the way the contents are collected and displayed." }, { "code": null, "e": 40968, "s": 40908, "text": "Menus − Menus are used to set the URL links for your site." }, { "code": null, "e": 41028, "s": 40968, "text": "Menus − Menus are used to set the URL links for your site." }, { "code": null, "e": 41151, "s": 41028, "text": "Taxonomy − Taxonomy can be thought of classifying website content which display specific content based on taxonomy terms." }, { "code": null, "e": 41274, "s": 41151, "text": "Taxonomy − Taxonomy can be thought of classifying website content which display specific content based on taxonomy terms." }, { "code": null, "e": 41381, "s": 41274, "text": "A list of themes are displayed. You can install the theme, update the existing theme or switch the themes." }, { "code": null, "e": 41443, "s": 41381, "text": "You can create a new user account or mange the existing user." }, { "code": null, "e": 41524, "s": 41443, "text": "You can enable or disable the modules present in it or can install a new module." }, { "code": null, "e": 41742, "s": 41524, "text": "This is an important part in the Drupal backend. Any changes done in this configuration, will affect the entire website. You can do the user account setting, site information setting or any other general site setting." }, { "code": null, "e": 41815, "s": 41742, "text": "Following are the details of the fields present in the preceding screen." }, { "code": null, "e": 41875, "s": 41815, "text": "People − Manages the user settings and IP address setting." }, { "code": null, "e": 41935, "s": 41875, "text": "People − Manages the user settings and IP address setting." }, { "code": null, "e": 42025, "s": 41935, "text": "System − Manages the basic site information, advanced actions and site maintenance task." }, { "code": null, "e": 42115, "s": 42025, "text": "System − Manages the basic site information, advanced actions and site maintenance task." }, { "code": null, "e": 42196, "s": 42115, "text": "Content Authoring − Manages the content input by the users including HTML tags." }, { "code": null, "e": 42277, "s": 42196, "text": "Content Authoring − Manages the content input by the users including HTML tags." }, { "code": null, "e": 42349, "s": 42277, "text": "User Interface − Sets the shortcut for menu on the admin account page." }, { "code": null, "e": 42421, "s": 42349, "text": "User Interface − Sets the shortcut for menu on the admin account page." }, { "code": null, "e": 42474, "s": 42421, "text": "Media − Manages the media settings in Drupal sites." }, { "code": null, "e": 42527, "s": 42474, "text": "Media − Manages the media settings in Drupal sites." }, { "code": null, "e": 42589, "s": 42527, "text": "Development − Manages the errors and page caching for users." }, { "code": null, "e": 42651, "s": 42589, "text": "Development − Manages the errors and page caching for users." }, { "code": null, "e": 42790, "s": 42651, "text": "Search and Meta Data − Set the alternative URL for specific page and the search engine maintains an index of words found in site content." }, { "code": null, "e": 42929, "s": 42790, "text": "Search and Meta Data − Set the alternative URL for specific page and the search engine maintains an index of words found in site content." }, { "code": null, "e": 42983, "s": 42929, "text": "Web Services − Displays the RSS feed from your site." }, { "code": null, "e": 43037, "s": 42983, "text": "Web Services − Displays the RSS feed from your site." }, { "code": null, "e": 43120, "s": 43037, "text": "Regional and Language − Sets the website time zone and displays the date and time." }, { "code": null, "e": 43203, "s": 43120, "text": "Regional and Language − Sets the website time zone and displays the date and time." }, { "code": null, "e": 43293, "s": 43203, "text": "It displays the information of available updates, recent log messages, and site security." }, { "code": null, "e": 43366, "s": 43293, "text": "Following are the details of the fields present in the preceding screen." }, { "code": null, "e": 43423, "s": 43366, "text": "Status report − Creates your Drupal site status report." }, { "code": null, "e": 43480, "s": 43423, "text": "Status report − Creates your Drupal site status report." }, { "code": null, "e": 43569, "s": 43480, "text": "Available updates − Gives status update for you available installed modules and themes." }, { "code": null, "e": 43658, "s": 43569, "text": "Available updates − Gives status update for you available installed modules and themes." }, { "code": null, "e": 43726, "s": 43658, "text": "Recent log messages − Displays messages which are recently logged." }, { "code": null, "e": 43794, "s": 43726, "text": "Recent log messages − Displays messages which are recently logged." }, { "code": null, "e": 43861, "s": 43794, "text": "Field List − Displays the list of fields configured on your site." }, { "code": null, "e": 43928, "s": 43861, "text": "Field List − Displays the list of fields configured on your site." }, { "code": null, "e": 44044, "s": 43928, "text": "Top 'access denied' errors − Displays access denied error message when user tries to access the unauthorized page." }, { "code": null, "e": 44160, "s": 44044, "text": "Top 'access denied' errors − Displays access denied error message when user tries to access the unauthorized page." }, { "code": null, "e": 44294, "s": 44160, "text": "Top 'Page not found' errors − Displays an error message as Page not found when there is no specified URL present in the Drupal site." }, { "code": null, "e": 44428, "s": 44294, "text": "Top 'Page not found' errors − Displays an error message as Page not found when there is no specified URL present in the Drupal site." }, { "code": null, "e": 44506, "s": 44428, "text": "Top search phrases − Displays the most searched phrases on your Drupal site." }, { "code": null, "e": 44584, "s": 44506, "text": "Top search phrases − Displays the most searched phrases on your Drupal site." }, { "code": null, "e": 44669, "s": 44584, "text": "It displays the help screen, where documentation pages of online modules are listed." }, { "code": null, "e": 44813, "s": 44669, "text": "Taxonomy can be thought of classifying website content which display specific content based on taxonomy terms. Drupal taxonomy is made up of − " }, { "code": null, "e": 44866, "s": 44813, "text": "Term − It is used to manage or describe the content." }, { "code": null, "e": 44919, "s": 44866, "text": "Term − It is used to manage or describe the content." }, { "code": null, "e": 44952, "s": 44919, "text": "Vocabulary − It is set of terms." }, { "code": null, "e": 44985, "s": 44952, "text": "Vocabulary − It is set of terms." }, { "code": null, "e": 45041, "s": 44985, "text": "Following are the steps to work with Drupal Taxonomy − " }, { "code": null, "e": 45097, "s": 45041, "text": "Step 1 − Go to Structure and click the Taxonomy option." }, { "code": null, "e": 45194, "s": 45097, "text": "Step 2 − You can create a new vocabulary for Drupal taxonomy by clicking on Add vocabulary link." }, { "code": null, "e": 45392, "s": 45194, "text": "Step 3 − You will get a screen with Name field for adding name for your vocabulary which is mandatory and Description field is used for adding description for the vocabulary. Click the Save button." }, { "code": null, "e": 45494, "s": 45392, "text": "Step 4 − Click add terms to add new terms to the created vocabulary as shown in the following screen." }, { "code": null, "e": 45565, "s": 45494, "text": "Step 5 − The screen shows some fields as seen in the following screen." }, { "code": null, "e": 45638, "s": 45565, "text": "Following are the details of the fields present in the preceding screen." }, { "code": null, "e": 45675, "s": 45638, "text": "Name− It specifies name of the term." }, { "code": null, "e": 45712, "s": 45675, "text": "Name− It specifies name of the term." }, { "code": null, "e": 45773, "s": 45712, "text": "Description− It is used for adding description for the term." }, { "code": null, "e": 45834, "s": 45773, "text": "Description− It is used for adding description for the term." }, { "code": null, "e": 45910, "s": 45834, "text": "Text format− It provides different types of formats by using dropdown menu." }, { "code": null, "e": 45986, "s": 45910, "text": "Text format− It provides different types of formats by using dropdown menu." }, { "code": null, "e": 46076, "s": 45986, "text": "URL alias− It optionally specifies an alternative URL by which this term can be accessed." }, { "code": null, "e": 46166, "s": 46076, "text": "URL alias− It optionally specifies an alternative URL by which this term can be accessed." }, { "code": null, "e": 46176, "s": 46166, "text": "Relations" }, { "code": null, "e": 46186, "s": 46176, "text": "Relations" }, { "code": null, "e": 46255, "s": 46186, "text": "Parent Terms − In this field, you can set a term as the parent term." }, { "code": null, "e": 46324, "s": 46255, "text": "Parent Terms − In this field, you can set a term as the parent term." }, { "code": null, "e": 46418, "s": 46324, "text": "Weight − Specifies weight for each term which will then display in ascending order by weight." }, { "code": null, "e": 46512, "s": 46418, "text": "Weight − Specifies weight for each term which will then display in ascending order by weight." }, { "code": null, "e": 46565, "s": 46512, "text": "After filling all the fields, click the Save button." }, { "code": null, "e": 46772, "s": 46565, "text": "In this chapter, we will study about Comments in Drupal. You can enable or disable the comments on your website. You can control, who can comment on your website's content and who can manage those comments." }, { "code": null, "e": 46836, "s": 46772, "text": "Following are the simple steps to configure comments in Drupal." }, { "code": null, "e": 46919, "s": 46836, "text": "Step 1 − Go to Structure and click Content types as shown in the following screen." }, { "code": null, "e": 46998, "s": 46919, "text": "Step 2 − Click on Edit link that you would like to change the comment setting." }, { "code": null, "e": 47073, "s": 46998, "text": "Step 3 − Click Comment settings category as shown in the following screen." }, { "code": null, "e": 47207, "s": 47073, "text": "Step 4 − Select open from the drop-down menu under Default comment setting for new content. This will allow comments on your website." }, { "code": null, "e": 47279, "s": 47207, "text": "Click the Save Content type button to save your configuration settings." }, { "code": null, "e": 47412, "s": 47279, "text": "User Management manages the information of the user, which allows creating or deleting the user, changing passwords, time and roles." }, { "code": null, "e": 47474, "s": 47412, "text": "Following are the simple steps to manage the users in Drupal." }, { "code": null, "e": 47517, "s": 47474, "text": "Step 1 − Click People --> Permissions Tab." }, { "code": null, "e": 47624, "s": 47517, "text": "In Permission tab, you can view two more tabs i.e. Permissions and Roles as shown in the preceding screen." }, { "code": null, "e": 47738, "s": 47624, "text": "Permission\nThis section is related to posting content permission. It contains the following types of permission −" }, { "code": null, "e": 47749, "s": 47738, "text": "Permission" }, { "code": null, "e": 47852, "s": 47749, "text": "This section is related to posting content permission. It contains the following types of permission −" }, { "code": null, "e": 47924, "s": 47852, "text": "Block − Sets permission to view, create, enable and disable the blocks." }, { "code": null, "e": 47996, "s": 47924, "text": "Block − Sets permission to view, create, enable and disable the blocks." }, { "code": null, "e": 48085, "s": 47996, "text": "Comment − Sets permission to users to view, edit, post comment or skip comment approval." }, { "code": null, "e": 48174, "s": 48085, "text": "Comment − Sets permission to users to view, edit, post comment or skip comment approval." }, { "code": null, "e": 48281, "s": 48174, "text": "Contextual links − Sets permission to use contextual link to perform action related to elements on a page." }, { "code": null, "e": 48388, "s": 48281, "text": "Contextual links − Sets permission to use contextual link to perform action related to elements on a page." }, { "code": null, "e": 48474, "s": 48388, "text": "Dashboard − Sets permission to allow users to view and make changes in the dashboard." }, { "code": null, "e": 48560, "s": 48474, "text": "Dashboard − Sets permission to allow users to view and make changes in the dashboard." }, { "code": null, "e": 48638, "s": 48560, "text": "Filter − Permission to filter the amount of roles and permission on the site." }, { "code": null, "e": 48716, "s": 48638, "text": "Filter − Permission to filter the amount of roles and permission on the site." }, { "code": null, "e": 48777, "s": 48716, "text": "Image − Permission to create or modify the styles of images." }, { "code": null, "e": 48838, "s": 48777, "text": "Image − Permission to create or modify the styles of images." }, { "code": null, "e": 48929, "s": 48838, "text": "Menu − Allows permission to access menu items and create menu through the admin interface." }, { "code": null, "e": 49020, "s": 48929, "text": "Menu − Allows permission to access menu items and create menu through the admin interface." }, { "code": null, "e": 49100, "s": 49020, "text": "Node − Allows to manage the view, edit and delete permissions for content type." }, { "code": null, "e": 49180, "s": 49100, "text": "Node − Allows to manage the view, edit and delete permissions for content type." }, { "code": null, "e": 49271, "s": 49180, "text": "Overlay − Sets permission to display administrative page as a layer over the current page." }, { "code": null, "e": 49362, "s": 49271, "text": "Overlay − Sets permission to display administrative page as a layer over the current page." }, { "code": null, "e": 49429, "s": 49362, "text": "Path − Sets permission to access path to all pages of Drupal site." }, { "code": null, "e": 49496, "s": 49429, "text": "Path − Sets permission to access path to all pages of Drupal site." }, { "code": null, "e": 49556, "s": 49496, "text": "Search − Sets permission to use normal and advanced search." }, { "code": null, "e": 49616, "s": 49556, "text": "Search − Sets permission to use normal and advanced search." }, { "code": null, "e": 49693, "s": 49616, "text": "Shortcut − Allows permission to set the shortcut toolbar on top of the page." }, { "code": null, "e": 49770, "s": 49693, "text": "Shortcut − Allows permission to set the shortcut toolbar on top of the page." }, { "code": null, "e": 49871, "s": 49770, "text": "System − Permission is granted to administer site configuration, view the themes, site reports, etc." }, { "code": null, "e": 49972, "s": 49871, "text": "System − Permission is granted to administer site configuration, view the themes, site reports, etc." }, { "code": null, "e": 50072, "s": 49972, "text": "Taxonomy − Permission to set the vocabularies and terms, and also to edit and delete terms in tags." }, { "code": null, "e": 50172, "s": 50072, "text": "Taxonomy − Permission to set the vocabularies and terms, and also to edit and delete terms in tags." }, { "code": null, "e": 50238, "s": 50172, "text": "Toolbar − Allows permission to access the administration toolbar." }, { "code": null, "e": 50304, "s": 50238, "text": "Toolbar − Allows permission to access the administration toolbar." }, { "code": null, "e": 50407, "s": 50304, "text": "User − Sets permission to individual users without assigning any special role to provide an interface." }, { "code": null, "e": 50510, "s": 50407, "text": "User − Sets permission to individual users without assigning any special role to provide an interface." }, { "code": null, "e": 50655, "s": 50510, "text": "Roles\nIt allows to set permissions for group of users by defining there roles. Here you can create the roles and edit permissions for each user." }, { "code": null, "e": 50661, "s": 50655, "text": "Roles" }, { "code": null, "e": 50800, "s": 50661, "text": "It allows to set permissions for group of users by defining there roles. Here you can create the roles and edit permissions for each user." }, { "code": null, "e": 50902, "s": 50800, "text": "Anonymous user − Allows user to access your website without asking them for the username or password." }, { "code": null, "e": 51004, "s": 50902, "text": "Anonymous user − Allows user to access your website without asking them for the username or password." }, { "code": null, "e": 51106, "s": 51004, "text": "Authenticated user − Allows only those users to access your website, who are authenticated to use it." }, { "code": null, "e": 51208, "s": 51106, "text": "Authenticated user − Allows only those users to access your website, who are authenticated to use it." }, { "code": null, "e": 51332, "s": 51208, "text": "Administrator − User who is responsible to manage the complete website and allow users to create or view by his permission." }, { "code": null, "e": 51456, "s": 51332, "text": "Administrator − User who is responsible to manage the complete website and allow users to create or view by his permission." }, { "code": null, "e": 51629, "s": 51456, "text": "In this chapter, we will learn how to optimize Drupal to improve its performance and speed. There are few steps through which we can improve the performance of the website." }, { "code": null, "e": 51685, "s": 51629, "text": "Following are some of the ways to optimize the website." }, { "code": null, "e": 51911, "s": 51685, "text": "Enable Cache blocks and Cache pages for Anonymous Users. Page caching lets your contents store in different database cache tables. Page cache is stored in the HTML content. It optimizes the page load time for anonymous users." }, { "code": null, "e": 51959, "s": 51911, "text": "Step 1 − Click Configuration from the menu bar." }, { "code": null, "e": 52010, "s": 51959, "text": "Step 2 − In Development section click Performance." }, { "code": null, "e": 52135, "s": 52010, "text": "Step 3 − Enable Cache blocks and Cache pages for Anonymous Users by checking both the boxes. Then, click Save Configuration." }, { "code": null, "e": 52257, "s": 52135, "text": "If you have many CSS files, it can lower your websites speed. Compress them by enabling Aggregate and Compress CSS files." }, { "code": null, "e": 52399, "s": 52257, "text": "Enable this setting from AdministrationConfiguration→Development→Performance section. Drupal decreases the number and size of your CSS files." }, { "code": null, "e": 52625, "s": 52399, "text": "Java files can also affect the performance and speed of your website. To compress this enable the Aggregate JavaScript files from the Administration→Configuration→Development→Performance in the bandwidth optimization section." }, { "code": null, "e": 52893, "s": 52625, "text": "This decreases the number of requests that a shared hosting handles. Use CDN (Content Delivery Network) that hosts your media files and static files. CDN acts as an external cache for your files and will store them in high performance servers so that it is optimized." }, { "code": null, "e": 53046, "s": 52893, "text": "Do not have many images which consume more space as this leads to slow website. Always resize your images and have few that are related to your website." }, { "code": null, "e": 53317, "s": 53046, "text": "Optimizing themes is a very important aspect. Media files like high quality images, videos, audios and flash can affect your website and slow down the speed resulting in low performance. Try reducing the size and number of media files or maybe you can avoid using flash." }, { "code": null, "e": 53433, "s": 53317, "text": "In this chapter, we will study about Site Backup in Drupal. It helps in backing up the files and the database file." }, { "code": null, "e": 53456, "s": 53433, "text": "Backup Files in Drupal" }, { "code": null, "e": 53482, "s": 53456, "text": "Backup Database in Drupal" }, { "code": null, "e": 53570, "s": 53482, "text": "To get the backup files of Drupal, you need to install FileZilla Client on your system." }, { "code": null, "e": 53629, "s": 53570, "text": "Following are the simple steps for file backup in Drupal −" }, { "code": null, "e": 53698, "s": 53629, "text": "Step 1 − Open the FileZilla Client as shown in the following screen." }, { "code": null, "e": 53793, "s": 53698, "text": "Step 2 − Enter the Host, Username, Password and Port as you have used to login to your cPanel." }, { "code": null, "e": 53850, "s": 53793, "text": "After filling all the fields, click Quickconnect button." }, { "code": null, "e": 53965, "s": 53850, "text": "Step 3 − You will get all files and folder of your Drupal site on the right side as shown in the following screen." }, { "code": null, "e": 54061, "s": 53965, "text": "Step 4 − Select all the files and folders and right click the mouse, click the Download option." }, { "code": null, "e": 54143, "s": 54061, "text": "After downloading the Drupal files from cPanel, it will get saved on your system." }, { "code": null, "e": 54206, "s": 54143, "text": "Following are the simple steps for database backup in Drupal −" }, { "code": null, "e": 54304, "s": 54206, "text": "Step 1 − Type the path http://localhost/phpmyadmin in browser. You will get the following screen." }, { "code": null, "e": 54380, "s": 54304, "text": "Step 2 − Click the database name drupal, which you have created for Drupal." }, { "code": null, "e": 54475, "s": 54380, "text": "Step 3 − After clicking on database drupal, it will open the following page, click Export tab." }, { "code": null, "e": 54617, "s": 54475, "text": "Step 4 − Next, you will find two methods to export the database i.e. Quick and Custom. Select any one of the methods and click the Go button." }, { "code": null, "e": 54686, "s": 54617, "text": "After exporting the database file, it will get saved on your system." }, { "code": null, "e": 54877, "s": 54686, "text": "In this chapter, we will study how to upgrade the Drupal site. Upgrade is a process of enhancing the old version to the latest version. Here we will upgrade the Drupal to the latest version." }, { "code": null, "e": 54931, "s": 54877, "text": "Below are simple steps to upgrade the site in Drupal." }, { "code": null, "e": 55038, "s": 54931, "text": "Step 1 − Backup your Drupal files. You can study about this in detail in the chapter Drupal - Site Backup." }, { "code": null, "e": 55179, "s": 55038, "text": "Step 2 − If there is any upgradation to be done on Drupal site, then a message gets displayed on your site as shown in the following screen." }, { "code": null, "e": 55252, "s": 55179, "text": "Step 3 − Click on the highlighted word available updates in the message." }, { "code": null, "e": 55458, "s": 55252, "text": "Step 4 − You can now view the Available Updates page, where it shows exactly what upgradation is to be done on the site. Here, it shows you the recommended version to update your site. Click Release notes." }, { "code": null, "e": 55686, "s": 55458, "text": "Step 5 − It will take you to Drupal official site page where you can see the latest version tar.gz files available in Drupal. While writing this tutorial, the latest version was drupal - 7.39.tar.gz. Click drupal - 7.39.tar.gz." }, { "code": null, "e": 55734, "s": 55686, "text": "The tar.gz files get downloaded on your system." }, { "code": null, "e": 55932, "s": 55734, "text": "Step 6 − Extract the downloaded file, copy all the files and folder except the Sites folder available inside the latest downloaded folder. Later, paste these files into your existing Drupal folder." }, { "code": null, "e": 56074, "s": 55932, "text": "Step 7 − Go to Reports --> Available updates or else you can refresh the page; here you will view a message as shown in the following screen." }, { "code": null, "e": 56119, "s": 56074, "text": "Step 8 − Click on Reports --> Status report." }, { "code": null, "e": 56283, "s": 56119, "text": "You can now see that your site is upgraded to latest version and it will show the status Up to date for Drupal core update status as shown in the preceding screen." }, { "code": null, "e": 56345, "s": 56283, "text": "In this chapter, we will learn about Announcements in Drupal." }, { "code": null, "e": 56688, "s": 56345, "text": "If you want to make any announcements on your website then you can do it through this feature. Declaration given to a visitor or user with the help of your website is announcements. It can be some important news, report, etc. It can be useful if you want to declare something important through your site that can be helpful for your visitors." }, { "code": null, "e": 56747, "s": 56688, "text": "Following are the steps to create Announcements in Drupal." }, { "code": null, "e": 56779, "s": 56747, "text": "Step 1 − First click Structure." }, { "code": null, "e": 56812, "s": 56779, "text": "Step 2 − Click on Content Types." }, { "code": null, "e": 56859, "s": 56812, "text": "Step 3 − Then you must click Add Content type." }, { "code": null, "e": 56945, "s": 56859, "text": "Step 4 − When you click Add content, the following page will get displayed on screen." }, { "code": null, "e": 57063, "s": 56945, "text": "Step 5 − Enter the content that you want to announce in the Name section. After adding name, click Save content type." }, { "code": null, "e": 57129, "s": 57063, "text": "Your new content gets displayed as shown in the following screen." }, { "code": null, "e": 57232, "s": 57129, "text": "Step 6 − If you want to make changes you must click the Edit section, you will get the following page." }, { "code": null, "e": 57392, "s": 57232, "text": "Step 7 − You can make the required changes, such as adding description and then click Save Content type. If you want to delete, then click Delete Content type." }, { "code": null, "e": 57497, "s": 57392, "text": "You can manage the fields by clicking on Manage Fields and manage display by clicking on Manage Display." }, { "code": null, "e": 57683, "s": 57497, "text": "In this chapter, we will study about Drupal URL Alias. URL or Uniform Resource Locater Aliases is a page address on your web page, it changes the existing system path to new path alias." }, { "code": null, "e": 57747, "s": 57683, "text": "Following are the simple steps to create URL Aliases in Drupal." }, { "code": null, "e": 57810, "s": 57747, "text": "Step 1 − Click Configuration as shown in the following screen." }, { "code": null, "e": 57841, "s": 57810, "text": "Step 2 − Click on URL aliases." }, { "code": null, "e": 57873, "s": 57841, "text": "Step 3 − Then, click Add alias." }, { "code": null, "e": 57956, "s": 57873, "text": "Step 4 − The Url aliases page will get displayed as shown in the following screen." }, { "code": null, "e": 58028, "s": 57956, "text": "Following are the details about the fields present in URL aliases page." }, { "code": null, "e": 58089, "s": 58028, "text": "Language − Specifies the language to be used in URL aliases." }, { "code": null, "e": 58150, "s": 58089, "text": "Language − Specifies the language to be used in URL aliases." }, { "code": null, "e": 58229, "s": 58150, "text": "Existing system path − Existing system path of an Article/Page in Drupal site." }, { "code": null, "e": 58308, "s": 58229, "text": "Existing system path − Existing system path of an Article/Page in Drupal site." }, { "code": null, "e": 58400, "s": 58308, "text": "Path alias − New path alias that replaces with the existing system path of an Article/Page." }, { "code": null, "e": 58492, "s": 58400, "text": "Path alias − New path alias that replaces with the existing system path of an Article/Page." }, { "code": null, "e": 58515, "s": 58492, "text": "Click the Save button." }, { "code": null, "e": 58608, "s": 58515, "text": "Step 5 − You can view your created URL aliases in the list as shown in the following screen." }, { "code": null, "e": 58790, "s": 58608, "text": "Step 6 − When you go back to Drupal Admin panel and hover over Article, it will display the newly added Path alias at the left bottom of the screen as shown in the following screen." }, { "code": null, "e": 58988, "s": 58790, "text": "Drupal allows to search for specific content on your site. You can search for both users and words on the site. We will see how to set up site search in Drupal as specified in the following steps −" }, { "code": null, "e": 59087, "s": 58988, "text": "Step 1 − Go to Configuration and click the Search settings link under SEARCH AND METADATA section." }, { "code": null, "e": 59243, "s": 59087, "text": "Step 2 − The search engine maintains an index of words found on your site's content. You can adjust the indexing behavior as shown in the following screen." }, { "code": null, "e": 59516, "s": 59243, "text": "The Indexing Status section indexes the content of nodes on the site. When you click the Re-index site button, the previous content remains until cron runs and sets the number of items to index per cron run by, using the drop-down menu under the Indexing Throttle section." }, { "code": null, "e": 59809, "s": 59516, "text": "Step 3 − Next it provides settings related to the indexing which will cause the site index to be rebuilt. It updates systematically to reflect the new settings. You can set minimum word length to index, i.e., the number of characters a word has to be indexed as shown in the following screen." }, { "code": null, "e": 59928, "s": 59809, "text": "Step 4 − You can choose which search modules are active from the available modules as defined in the following screen." }, { "code": null, "e": 60076, "s": 59928, "text": "You can search for both users and words (node) by checking the required modules and set the default search module as shown in the preceding screen." }, { "code": null, "e": 60168, "s": 60076, "text": "Step 5 − The last section is Content Ranking which comes with Factor and Influence columns." }, { "code": null, "e": 60440, "s": 60168, "text": "Influence is a numeric multiplier used in ordering search results. If you set higher number for a corresponding factor, it will have more influence on search results; zero means the factor is ignored. After you are done with settings, click the Save configuration button." }, { "code": null, "e": 60554, "s": 60440, "text": "Step 6 − Now go to home page, search the content that matches for the keywords in your content in the search bar." }, { "code": null, "e": 60657, "s": 60554, "text": "In this chapter, we will study about Drupal error handling for managing error messages on Drupal site." }, { "code": null, "e": 60807, "s": 60657, "text": "Error Handling is a process of detection and finding the resolutions for the errors. It can be programming application errors or communicable errors." }, { "code": null, "e": 60876, "s": 60807, "text": "The following steps describe how to manage error messages in Drupa −" }, { "code": null, "e": 60935, "s": 60876, "text": "Step 1 − Go to Configuration and click Logging and errors." }, { "code": null, "e": 61025, "s": 60935, "text": "Step 2 − The Logging and errors page will get displayed as shown in the following screen." }, { "code": null, "e": 61099, "s": 61025, "text": "Following are the details of the fields as seen in the preceding screen −" }, { "code": null, "e": 61191, "s": 61099, "text": "Error messages to display − It specifies error messages to be displayed on the Drupal site." }, { "code": null, "e": 61283, "s": 61191, "text": "Error messages to display − It specifies error messages to be displayed on the Drupal site." }, { "code": null, "e": 61337, "s": 61283, "text": "None − This option doesn't display any error message." }, { "code": null, "e": 61391, "s": 61337, "text": "None − This option doesn't display any error message." }, { "code": null, "e": 61480, "s": 61391, "text": "Errors and warnings − This option displays only messages related to errors and warnings." }, { "code": null, "e": 61569, "s": 61480, "text": "Errors and warnings − This option displays only messages related to errors and warnings." }, { "code": null, "e": 61694, "s": 61569, "text": "All messages − This option specifies all types of error messages such as errors, warnings, etc. to be displayed on the site." }, { "code": null, "e": 61819, "s": 61694, "text": "All messages − This option specifies all types of error messages such as errors, warnings, etc. to be displayed on the site." }, { "code": null, "e": 61927, "s": 61819, "text": "Database log messages to keep − It indicates the maximum number of messages to be kept in the database log." }, { "code": null, "e": 62035, "s": 61927, "text": "Database log messages to keep − It indicates the maximum number of messages to be kept in the database log." }, { "code": null, "e": 62256, "s": 62035, "text": "Drupal uses _drupal_exception_handler ($exception) function to handle the errors on the site. These errors will not be enclosed in a try/catch block. The script won't execute the function when an exception handler exits." }, { "code": null, "e": 62311, "s": 62256, "text": "The code for _drupal_exception_handler is as follows −" }, { "code": null, "e": 63148, "s": 62311, "text": "function _drupal_exception_handler($exception) {\n require_once DRUPAL_ROOT . '/includes/errors.inc';\n try {\n // display the error message in the log and return the error messages to the user\n _drupal_log_error(_drupal_decode_exception($exception), TRUE);\n }\n catch (Exception $excp2) {\n // Another uncaught exception was thrown while handling the first one.\n // If we are displaying errors, then do so with no possibility of \n a further uncaught exception being thrown.\n \n if (error_displayable()) {\n print '<h1>Additional uncaught exception thrown while handling exception.</h1>';\n print '<h2>Original</h2> <p>'. _drupal_render_exception_safe($exception).'</p>';\n print '<h2>Additional</h2> <p>'. _drupal_render_exception_safe($excp2).'</p><hr/>';\n }\n }\n}" }, { "code": null, "e": 63277, "s": 63148, "text": "The function must be used on every Drupal request. This function is present at the line 2328 in the file includes/bootstrap.inc." }, { "code": null, "e": 63527, "s": 63277, "text": "There are two string references to _drupal_exception_handler such as_drupal_bootstrap_configuration() present in the bootstrap.inc file and_drupal_get_last_caller present in the errors.inc file. Both these files are present in the ‘includes’ folder." }, { "code": null, "e": 63766, "s": 63529, "text": "In this chapter, we will learn about multilingual content. That means your content can be written and will be displayed in different languages. For this you may either install a multilingual content module or an Internationalism module." }, { "code": null, "e": 63840, "s": 63766, "text": "Following are the steps to install multilingual content module on Drupal." }, { "code": null, "e": 63882, "s": 63840, "text": "Step 1 − Click Modules from the menu bar." }, { "code": null, "e": 63964, "s": 63882, "text": "Step 2 − Check the Multilingual content box from the modules and click Configure." }, { "code": null, "e": 64024, "s": 63964, "text": "Step 3 − The Multilingual settings page will get displayed." }, { "code": null, "e": 64119, "s": 64024, "text": "Enabled language only − When you check this box, you can only view languages that are enabled." }, { "code": null, "e": 64214, "s": 64119, "text": "Enabled language only − When you check this box, you can only view languages that are enabled." }, { "code": null, "e": 64298, "s": 64214, "text": "All Defined languages will be allowed − Only the defined languages will be allowed." }, { "code": null, "e": 64382, "s": 64298, "text": "All Defined languages will be allowed − Only the defined languages will be allowed." }, { "code": null, "e": 64458, "s": 64382, "text": "Here, we have three different tabs where you can make the required changes." }, { "code": null, "e": 64527, "s": 64458, "text": "Selection − You can select nodes and taxonomy according to language." }, { "code": null, "e": 64596, "s": 64527, "text": "Selection − You can select nodes and taxonomy according to language." }, { "code": null, "e": 64664, "s": 64596, "text": "Select nodes by language − Check box if you want nodes by language." }, { "code": null, "e": 64732, "s": 64664, "text": "Select nodes by language − Check box if you want nodes by language." }, { "code": null, "e": 64828, "s": 64732, "text": "Select taxonomy terms by language − If you want taxonomy terms by language then check this box." }, { "code": null, "e": 64924, "s": 64828, "text": "Select taxonomy terms by language − If you want taxonomy terms by language then check this box." }, { "code": null, "e": 64986, "s": 64924, "text": "Skip tags − Write those tags which you don't want to include." }, { "code": null, "e": 65048, "s": 64986, "text": "Skip tags − Write those tags which you don't want to include." }, { "code": null, "e": 65150, "s": 65048, "text": "Enable for specific pages − If you want to enable settings for specific pages then use this checkbox." }, { "code": null, "e": 65252, "s": 65150, "text": "Enable for specific pages − If you want to enable settings for specific pages then use this checkbox." }, { "code": null, "e": 65291, "s": 65252, "text": "Click the save button, once completed." }, { "code": null, "e": 65364, "s": 65291, "text": "Variables − Select variables to be set as shown in the following screen." }, { "code": null, "e": 65437, "s": 65364, "text": "Variables − Select variables to be set as shown in the following screen." }, { "code": null, "e": 65476, "s": 65437, "text": "Menu Settings − Manages menu settings." }, { "code": null, "e": 65515, "s": 65476, "text": "Menu Settings − Manages menu settings." }, { "code": null, "e": 65565, "s": 65515, "text": "Site Information − Helps to make changes on site." }, { "code": null, "e": 65615, "s": 65565, "text": "Site Information − Helps to make changes on site." }, { "code": null, "e": 65666, "s": 65615, "text": "Feed settings − You can set your feed description." }, { "code": null, "e": 65717, "s": 65666, "text": "Feed settings − You can set your feed description." }, { "code": null, "e": 65764, "s": 65717, "text": "Regional Settings − Changes time zone and day." }, { "code": null, "e": 65811, "s": 65764, "text": "Regional Settings − Changes time zone and day." }, { "code": null, "e": 65855, "s": 65811, "text": "Theme Settings − Specifies managing themes." }, { "code": null, "e": 65899, "s": 65855, "text": "Theme Settings − Specifies managing themes." }, { "code": null, "e": 65946, "s": 65899, "text": "User Settings − You can use this to set users." }, { "code": null, "e": 65993, "s": 65946, "text": "User Settings − You can use this to set users." }, { "code": null, "e": 66054, "s": 65993, "text": "User emails − Any issues related to user emails can be done." }, { "code": null, "e": 66115, "s": 66054, "text": "User emails − Any issues related to user emails can be done." }, { "code": null, "e": 66149, "s": 66115, "text": "Examples − You can give examples." }, { "code": null, "e": 66183, "s": 66149, "text": "Examples − You can give examples." }, { "code": null, "e": 66226, "s": 66183, "text": "Click Save when you complete the settings." }, { "code": null, "e": 66261, "s": 66226, "text": "Node Options − Help you set nodes." }, { "code": null, "e": 66296, "s": 66261, "text": "Node Options − Help you set nodes." }, { "code": null, "e": 66412, "s": 66296, "text": "You can hide content translations and change the language on this page. Later, click the Save configuration button." }, { "code": null, "e": 66470, "s": 66412, "text": "Strings − This option helps to change format of the page." }, { "code": null, "e": 66636, "s": 66470, "text": "Change and translate strings using Translatable text formats settings. You can even change sources as you choose many languages. After completion, click Save button." }, { "code": null, "e": 66737, "s": 66636, "text": "In this chapter, we will learn about Triggers and Actions in Drupal. First let's look into Triggers." }, { "code": null, "e": 66874, "s": 66737, "text": "It can be defined as changes happening within your site. The actions can be carried out either after creating a new content or any page." }, { "code": null, "e": 66941, "s": 66874, "text": "Following are the steps that will help you use triggers in Drupal." }, { "code": null, "e": 66989, "s": 66941, "text": "Step 1 − First click Modules from the menu bar." }, { "code": null, "e": 67050, "s": 66989, "text": "Step 2 − When you click Modules, you get the following page." }, { "code": null, "e": 67135, "s": 67050, "text": "Here enable Trigger module. Then click Save Configuration at the bottom of the page." }, { "code": null, "e": 67257, "s": 67135, "text": "Step 3 − Go back to the Trigger module and click Configure on the right side of the page as shown in the following image." }, { "code": null, "e": 67320, "s": 67257, "text": "Step 4 − When you click Configure, you get the following page." }, { "code": null, "e": 67382, "s": 67320, "text": "We have different tabs on the page that specify each trigger." }, { "code": null, "e": 67472, "s": 67382, "text": "Comment Module − You can assign action to only those triggers relating to comment module." }, { "code": null, "e": 67551, "s": 67472, "text": "Node Module − You can assign action to those triggers relating to Node module." }, { "code": null, "e": 67639, "s": 67551, "text": "System Module − You can assign action to only those triggers relating to System module." }, { "code": null, "e": 67705, "s": 67639, "text": "Taxonomy Module − You can trigger actions to the Taxonomy module." }, { "code": null, "e": 67798, "s": 67705, "text": "User Module − At last we have the user module, here actions must be assigned in User module." }, { "code": null, "e": 67862, "s": 67798, "text": "Tasks carried on a particular system object are called actions." }, { "code": null, "e": 67910, "s": 67862, "text": "Step 1 − Click Configuration from the menu bar." }, { "code": null, "e": 67961, "s": 67910, "text": "Step 2 − Click on Actions from the system section." }, { "code": null, "e": 68022, "s": 67961, "text": "Step 3 − When you click Actions, you get the following page." }, { "code": null, "e": 68089, "s": 68022, "text": "Step 4 − Select any one action from the dropdown and click Create." }, { "code": null, "e": 68170, "s": 68089, "text": "Step 5 − When you choose an option and click Create, The following page appears." }, { "code": null, "e": 68224, "s": 68170, "text": "Following are the option fields present on the page −" }, { "code": null, "e": 68259, "s": 68224, "text": "Label − Give a name to your action" }, { "code": null, "e": 68294, "s": 68259, "text": "Label − Give a name to your action" }, { "code": null, "e": 68331, "s": 68294, "text": "Recipient − Enter your email address" }, { "code": null, "e": 68368, "s": 68331, "text": "Recipient − Enter your email address" }, { "code": null, "e": 68424, "s": 68368, "text": "Subject − Enter a subject you want to add to the action" }, { "code": null, "e": 68480, "s": 68424, "text": "Subject − Enter a subject you want to add to the action" }, { "code": null, "e": 68568, "s": 68480, "text": "Message − Enter the message you want to send to the visitor when clicked on any action." }, { "code": null, "e": 68656, "s": 68568, "text": "Message − Enter the message you want to send to the visitor when clicked on any action." }, { "code": null, "e": 68699, "s": 68656, "text": "After filling all the details, click Save." }, { "code": null, "e": 68760, "s": 68699, "text": "Step(6) − You can see that your action is added to the list." }, { "code": null, "e": 69018, "s": 68760, "text": "In this chapter, let us study about Social Networking in Drupal. Social media is becoming very important these days, Drupal has many social media modules for this purpose. Let us take ShareThis module as our example, you can choose any other of your choice." }, { "code": null, "e": 69083, "s": 69018, "text": "Following are the simple steps used to install ShareThis module." }, { "code": null, "e": 69195, "s": 69083, "text": "Step 1 − Click ShareThis to visit ShareThis module page and click the Version as shown in the following screen." }, { "code": null, "e": 69274, "s": 69195, "text": "Step 2 − Copy the link address of the module as shown in the following screen." }, { "code": null, "e": 69366, "s": 69274, "text": "Step 3 − Next, go to Modules and click Install new module as shown in the following screen." }, { "code": null, "e": 69482, "s": 69366, "text": "Step 4 − Now, paste the link address that you copied in step(2) and click Install as shown in the following screen." }, { "code": null, "e": 69560, "s": 69482, "text": "Step 5 − You will see the following screen. Click Enable newly added modules." }, { "code": null, "e": 69671, "s": 69560, "text": "Step 6 − Next, go to Modules. Enable the module and click Save configuration as shown in the following screen." }, { "code": null, "e": 69774, "s": 69671, "text": "Step 7 − Go to Configuration, under WEB SERVICES and click ShareThis as shown in the following screen." }, { "code": null, "e": 69813, "s": 69774, "text": "Step 8 − The following screen pops up." }, { "code": null, "e": 69950, "s": 69813, "text": "Step 9 − You can click any of the button style, under the Display section to share your content online as shown in the following screen." }, { "code": null, "e": 70128, "s": 69950, "text": "Step 10 − Click any of the services you want to remove. You can also use Extra services like Google Plus One and Facebook Like by checking them as shown in the following screen." }, { "code": null, "e": 70263, "s": 70128, "text": "You can choose services from the Possible Services section and you can also remove or re-order services from Selected Service section." }, { "code": null, "e": 70381, "s": 70263, "text": "Step 11 − Next, click Context as shown in the following screen to configure where the ShareThis widget should appear." }, { "code": null, "e": 70440, "s": 70381, "text": "Following the details of the fields present on the screen." }, { "code": null, "e": 70514, "s": 70440, "text": "Under Location you can choose any of Node content or Block or Links area." }, { "code": null, "e": 70588, "s": 70514, "text": "Under Location you can choose any of Node content or Block or Links area." }, { "code": null, "e": 70690, "s": 70588, "text": "Under Node Types you can select Article and Basic page, if you want ShareThis widget to appear on it." }, { "code": null, "e": 70792, "s": 70690, "text": "Under Node Types you can select Article and Basic page, if you want ShareThis widget to appear on it." }, { "code": null, "e": 70862, "s": 70792, "text": "If you select Comments you can display ShareThis on comments as well." }, { "code": null, "e": 70932, "s": 70862, "text": "If you select Comments you can display ShareThis on comments as well." }, { "code": null, "e": 71015, "s": 70932, "text": "The Weight of the widget determines the location on the page where it will appear." }, { "code": null, "e": 71098, "s": 71015, "text": "The Weight of the widget determines the location on the page where it will appear." }, { "code": null, "e": 71164, "s": 71098, "text": "Step 12 − Next, select Advanced as shown in the following screen." }, { "code": null, "e": 71237, "s": 71164, "text": "Following are the details of the fields present on the preceding screen." }, { "code": null, "e": 71306, "s": 71237, "text": "When you install the module, a random publisher key will be created." }, { "code": null, "e": 71375, "s": 71306, "text": "When you install the module, a random publisher key will be created." }, { "code": null, "e": 71495, "s": 71375, "text": "Twitter Suffix will optionally append a Twitter handle, or text, so that you get a ping when someone shares an article." }, { "code": null, "e": 71615, "s": 71495, "text": "Twitter Suffix will optionally append a Twitter handle, or text, so that you get a ping when someone shares an article." }, { "code": null, "e": 71668, "s": 71615, "text": "Twitter Handle will be used when sharing on twitter." }, { "code": null, "e": 71721, "s": 71668, "text": "Twitter Handle will be used when sharing on twitter." }, { "code": null, "e": 71815, "s": 71721, "text": "Twitter recommends will specify a twitter handle to be recommended to the user while sharing." }, { "code": null, "e": 71909, "s": 71815, "text": "Twitter recommends will specify a twitter handle to be recommended to the user while sharing." }, { "code": null, "e": 72021, "s": 71909, "text": "If Display ShareThis widget on hover is disabled, ShareThis widget will be displayed on click instead of hover." }, { "code": null, "e": 72133, "s": 72021, "text": "If Display ShareThis widget on hover is disabled, ShareThis widget will be displayed on click instead of hover." }, { "code": null, "e": 72257, "s": 72133, "text": "If Display count \"0\" instead of \"New\" is checked, zero is displayed instead of New in the count for content not yet shared." }, { "code": null, "e": 72381, "s": 72257, "text": "If Display count \"0\" instead of \"New\" is checked, zero is displayed instead of New in the count for content not yet shared." }, { "code": null, "e": 72450, "s": 72381, "text": "Display short URL will display either the full or the shortened URL." }, { "code": null, "e": 72519, "s": 72450, "text": "Display short URL will display either the full or the shortened URL." }, { "code": null, "e": 72615, "s": 72519, "text": "CopyNShare will measure copy and shares of your site's content or URLs as checked respectively." }, { "code": null, "e": 72711, "s": 72615, "text": "CopyNShare will measure copy and shares of your site's content or URLs as checked respectively." }, { "code": null, "e": 72812, "s": 72711, "text": "Step 13 − After checking all the details, click Save configuration as shown in the following screen." }, { "code": null, "e": 72894, "s": 72812, "text": "Step 14 − Now you can see the social media buttons appearing on the Article page." }, { "code": null, "e": 73100, "s": 72894, "text": "In this chapter, we will learn about Internationalization in Drupal. Internationalization is a module which lets you create multilingual sites. This way you can display your website in different languages." }, { "code": null, "e": 73151, "s": 73100, "text": "Following are the steps for Internationalization −" }, { "code": null, "e": 73192, "s": 73151, "text": "Step 1 − Click Module from the menu bar." }, { "code": null, "e": 73374, "s": 73192, "text": "Step 2 − To get the Internationalization module you must first download and install it in Drupal. Then you must enable the Internationalization module, and click Save Configuration." }, { "code": null, "e": 73517, "s": 73374, "text": "Step 3 − Next, you can see a Configure setting on the right side of the page for Internationalization module as shown in the following screen." }, { "code": null, "e": 73574, "s": 73517, "text": "Step 4 − Click Configure and you get the following page." }, { "code": null, "e": 73601, "s": 73574, "text": "In Languages for content −" }, { "code": null, "e": 73702, "s": 73601, "text": "Enabled language only − When you check this box, you can only view those languages that are enabled." }, { "code": null, "e": 73803, "s": 73702, "text": "Enabled language only − When you check this box, you can only view those languages that are enabled." }, { "code": null, "e": 73912, "s": 73803, "text": "All Defined languages will be allowed − Only the defined languages will be allowed, when you check this box." }, { "code": null, "e": 74021, "s": 73912, "text": "All Defined languages will be allowed − Only the defined languages will be allowed, when you check this box." }, { "code": null, "e": 74081, "s": 74021, "text": "You can see some tabs on the top right corner of the page −" }, { "code": null, "e": 74202, "s": 74081, "text": "Multilingual Settings − You can study about multilingual settings in detail in the chapter Drupal - Multilingual Content" }, { "code": null, "e": 74323, "s": 74202, "text": "Multilingual Settings − You can study about multilingual settings in detail in the chapter Drupal - Multilingual Content" }, { "code": null, "e": 74392, "s": 74323, "text": "Selection − You can select nodes and taxonomy according to language." }, { "code": null, "e": 74461, "s": 74392, "text": "Selection − You can select nodes and taxonomy according to language." }, { "code": null, "e": 74501, "s": 74461, "text": "Variables − Select variables to be set." }, { "code": null, "e": 74541, "s": 74501, "text": "Variables − Select variables to be set." }, { "code": null, "e": 74577, "s": 74541, "text": "Node Options − Helps you set nodes." }, { "code": null, "e": 74613, "s": 74577, "text": "Node Options − Helps you set nodes." }, { "code": null, "e": 74663, "s": 74613, "text": "Strings − Helps to change the format of the page." }, { "code": null, "e": 74713, "s": 74663, "text": "Strings − Helps to change the format of the page." }, { "code": null, "e": 74775, "s": 74713, "text": "Once you are done with the changes, click Save Configuration." }, { "code": null, "e": 74911, "s": 74775, "text": "In this chapter, we will learn about Drupal Extensions. To extend the functionality of the site, different extensions can be installed." }, { "code": null, "e": 74974, "s": 74911, "text": "Following are the steps to install Extension module in Drupal." }, { "code": null, "e": 75019, "s": 74974, "text": "Step 1 − Click on Modules from the menu bar." }, { "code": null, "e": 75057, "s": 75019, "text": "Step 2 − Click on Install new module." }, { "code": null, "e": 75190, "s": 75057, "text": "Step 3 − The following page gets displayed. Here, enter the module URL in the box as shown in the following image and click Install." }, { "code": null, "e": 75269, "s": 75190, "text": "Step 4 − The module starts getting installed as shown in the following screen." }, { "code": null, "e": 75384, "s": 75269, "text": "Step 5 − Once installation is complete, you get the following screen. Here, click Enable newly added modules link." }, { "code": null, "e": 75497, "s": 75384, "text": "Step 6 − Next, a Module page gets displayed where your module has been installed, now you can enable the module." }, { "code": null, "e": 75726, "s": 75497, "text": "In this chapter, we will study about Default Modules in Drupal. After installing Drupal, you will see total 44 default modules. You can see all these modules in Core section. By default 29 modules are enabled after installation." }, { "code": null, "e": 75833, "s": 75726, "text": "Step 1 − Click Modules, you will see the list of modules in CORE section as shown in the following screen." }, { "code": null, "e": 75969, "s": 75833, "text": "Following is the list of default modules installed in Durpal7. These are the core modules required by Drupal and it cannot be disabled." }, { "code": null, "e": 76111, "s": 75969, "text": "Block − Controls the constructed page with visual building blocks. Blocks are boxes of content provided into an area or region of a web page." }, { "code": null, "e": 76253, "s": 76111, "text": "Block − Controls the constructed page with visual building blocks. Blocks are boxes of content provided into an area or region of a web page." }, { "code": null, "e": 76333, "s": 76253, "text": "Color − Permits administrators to modify the color scheme of compatible themes." }, { "code": null, "e": 76413, "s": 76333, "text": "Color − Permits administrators to modify the color scheme of compatible themes." }, { "code": null, "e": 76489, "s": 76413, "text": "Comment − Permits users to comment and discuss about the published content." }, { "code": null, "e": 76565, "s": 76489, "text": "Comment − Permits users to comment and discuss about the published content." }, { "code": null, "e": 76665, "s": 76565, "text": "Contextual links − Provides contextual links to execute actions associated with elements on a page." }, { "code": null, "e": 76765, "s": 76665, "text": "Contextual links − Provides contextual links to execute actions associated with elements on a page." }, { "code": null, "e": 76915, "s": 76765, "text": "Dashboard − Offers a dashboard page in the administrative interface for forming administrative projects and tracking information within your website." }, { "code": null, "e": 77065, "s": 76915, "text": "Dashboard − Offers a dashboard page in the administrative interface for forming administrative projects and tracking information within your website." }, { "code": null, "e": 77132, "s": 77065, "text": "Database logging − Logs and records system events to the database." }, { "code": null, "e": 77199, "s": 77132, "text": "Database logging − Logs and records system events to the database." }, { "code": null, "e": 77272, "s": 77199, "text": "Field − Field API allows adding fields to entities like nodes and users." }, { "code": null, "e": 77345, "s": 77272, "text": "Field − Field API allows adding fields to entities like nodes and users." }, { "code": null, "e": 77413, "s": 77345, "text": "Field SQL storage − It sets to store field data in an SQL database." }, { "code": null, "e": 77481, "s": 77413, "text": "Field SQL storage − It sets to store field data in an SQL database." }, { "code": null, "e": 77526, "s": 77481, "text": "Field UI − User interface for the Field API." }, { "code": null, "e": 77571, "s": 77526, "text": "Field UI − User interface for the Field API." }, { "code": null, "e": 77607, "s": 77571, "text": "File − Specifies a file field type." }, { "code": null, "e": 77643, "s": 77607, "text": "File − Specifies a file field type." }, { "code": null, "e": 77691, "s": 77643, "text": "Filter − Filters content and exhibits in order." }, { "code": null, "e": 77739, "s": 77691, "text": "Filter − Filters content and exhibits in order." }, { "code": null, "e": 77782, "s": 77739, "text": "Help − Manages the display of online help." }, { "code": null, "e": 77825, "s": 77782, "text": "Help − Manages the display of online help." }, { "code": null, "e": 77862, "s": 77825, "text": "Image − Allows image handling tools." }, { "code": null, "e": 77899, "s": 77862, "text": "Image − Allows image handling tools." }, { "code": null, "e": 77976, "s": 77899, "text": "List − Specifies list field types. Creates choice lists with this selection." }, { "code": null, "e": 78053, "s": 77976, "text": "List − Specifies list field types. Creates choice lists with this selection." }, { "code": null, "e": 78140, "s": 78053, "text": "Menu − Permits administrators to customize the site navigation menu as per the choice." }, { "code": null, "e": 78227, "s": 78140, "text": "Menu − Permits administrators to customize the site navigation menu as per the choice." }, { "code": null, "e": 78301, "s": 78227, "text": "Node − Allows content to be submitted to the site and displayed on pages." }, { "code": null, "e": 78375, "s": 78301, "text": "Node − Allows content to be submitted to the site and displayed on pages." }, { "code": null, "e": 78417, "s": 78375, "text": "Number − It sets the numeric field types." }, { "code": null, "e": 78459, "s": 78417, "text": "Number − It sets the numeric field types." }, { "code": null, "e": 78558, "s": 78459, "text": "Options − It specifies the choice, check box and radio button widgets for text and numeric fields." }, { "code": null, "e": 78657, "s": 78558, "text": "Options − It specifies the choice, check box and radio button widgets for text and numeric fields." }, { "code": null, "e": 78731, "s": 78657, "text": "Overlay − It specifies the Drupal administration interface in an overlay." }, { "code": null, "e": 78805, "s": 78731, "text": "Overlay − It specifies the Drupal administration interface in an overlay." }, { "code": null, "e": 78842, "s": 78805, "text": "Path − Permits users to rename URLs." }, { "code": null, "e": 78879, "s": 78842, "text": "Path − Permits users to rename URLs." }, { "code": null, "e": 79057, "s": 78879, "text": "RDF − It improves your content with metadata to allow other applications (e.g. search engines, aggregators) to its relationships and attributes in understand in a better manner." }, { "code": null, "e": 79235, "s": 79057, "text": "RDF − It improves your content with metadata to allow other applications (e.g. search engines, aggregators) to its relationships and attributes in understand in a better manner." }, { "code": null, "e": 79281, "s": 79235, "text": "Search − Permits site-wide keyword searching." }, { "code": null, "e": 79327, "s": 79281, "text": "Search − Permits site-wide keyword searching." }, { "code": null, "e": 79400, "s": 79327, "text": "Shortcut − Permits users to manage customizable lists of shortcut links." }, { "code": null, "e": 79473, "s": 79400, "text": "Shortcut − Permits users to manage customizable lists of shortcut links." }, { "code": null, "e": 79537, "s": 79473, "text": "System − Handles general site configuration for administrators." }, { "code": null, "e": 79601, "s": 79537, "text": "System − Handles general site configuration for administrators." }, { "code": null, "e": 79651, "s": 79601, "text": "Taxonomy − Enables the categorization of content." }, { "code": null, "e": 79701, "s": 79651, "text": "Taxonomy − Enables the categorization of content." }, { "code": null, "e": 79741, "s": 79701, "text": "Text − Defines simple text field types." }, { "code": null, "e": 79781, "s": 79741, "text": "Text − Defines simple text field types." }, { "code": null, "e": 79891, "s": 79781, "text": "Toolbar − Provides a toolbar that shows the top-level administration menu items and links from other modules." }, { "code": null, "e": 80001, "s": 79891, "text": "Toolbar − Provides a toolbar that shows the top-level administration menu items and links from other modules." }, { "code": null, "e": 80122, "s": 80001, "text": "Update manager − Checks for available updates and can securely install or update modules and themes via a web interface." }, { "code": null, "e": 80243, "s": 80122, "text": "Update manager − Checks for available updates and can securely install or update modules and themes via a web interface." }, { "code": null, "e": 80298, "s": 80243, "text": "User − Manages the user registration and login system." }, { "code": null, "e": 80353, "s": 80298, "text": "User − Manages the user registration and login system." }, { "code": null, "e": 80570, "s": 80353, "text": "In this chapter, we will learn about using Pane Module in Drupal. Pane module is used to translate the custom panel's pane with optional title that will be stored as variables and it can be translate or edit quickly." }, { "code": null, "e": 80614, "s": 80570, "text": "Following are the steps to add Pane Module." }, { "code": null, "e": 80712, "s": 80614, "text": "Step 1 − Download the latest file of Pane module from the link and install in your Drupal site." }, { "code": null, "e": 80808, "s": 80712, "text": "Step 2 − Enable the one you want to use and click Save Configuration at the bottom of the page." }, { "code": null, "e": 80852, "s": 80808, "text": "Step 3 − Click Structure from the menu bar." }, { "code": null, "e": 80877, "s": 80852, "text": "Step 4 − Click on Panes." }, { "code": null, "e": 80925, "s": 80877, "text": "Step 5 − Then click Add pane to add a new pane." }, { "code": null, "e": 80998, "s": 80925, "text": "Step 6 − The Panes page gets displayed as shown in the following screen." }, { "code": null, "e": 81032, "s": 80998, "text": "It contains the following fields." }, { "code": null, "e": 81075, "s": 81032, "text": "Title − Enter your pane title in this box." }, { "code": null, "e": 81118, "s": 81075, "text": "Title − Enter your pane title in this box." }, { "code": null, "e": 81176, "s": 81118, "text": "Description − Describe your pane in a line or a sentence." }, { "code": null, "e": 81234, "s": 81176, "text": "Description − Describe your pane in a line or a sentence." }, { "code": null, "e": 81304, "s": 81234, "text": "Type − Select type accordingly, it may be either Text or Entity Host." }, { "code": null, "e": 81374, "s": 81304, "text": "Type − Select type accordingly, it may be either Text or Entity Host." }, { "code": null, "e": 81427, "s": 81374, "text": "After filling the details, click Save Configuration." }, { "code": null, "e": 81563, "s": 81427, "text": "Step 7 − Your Pane module gets displayed as shown in the following image. If you want to make any changes in the pane, then click Edit." }, { "code": null, "e": 81602, "s": 81563, "text": "Step 8 − The Pane page gets displayed." }, { "code": null, "e": 81652, "s": 81602, "text": "Make the required changes and click Save Content." }, { "code": null, "e": 81928, "s": 81652, "text": "In this chapter, we will study about Book Module in Drupal. Books have an in-built hierarchical navigation, which means that you can organize them to read in a special order. The book content type also allows you to make your website content easier to print by site visitors." }, { "code": null, "e": 81995, "s": 81928, "text": "Following are the simple steps to configure Book module in Drupal." }, { "code": null, "e": 82061, "s": 81995, "text": "Step 1 − Enable the Book in Modules and click Save configuration." }, { "code": null, "e": 82167, "s": 82061, "text": "Step 2 − Click on Content and check the boxes, select the content type that you want to enable for books." }, { "code": null, "e": 82219, "s": 82167, "text": "Click Save configuration to save your content type." }, { "code": null, "e": 82325, "s": 82219, "text": "Step 3 − Click Create content -> Book page or on Shortcut bar Book page as shown in the following screen." }, { "code": null, "e": 82426, "s": 82325, "text": "Spread out the section under Book outline and select create a new book. You can set the weight to 0." }, { "code": null, "e": 82484, "s": 82426, "text": "Click the Save button and your top level page is created." }, { "code": null, "e": 82616, "s": 82484, "text": "Step 4 − Once your book has been created, you can create child pages by clicking the Add child link at the bottom of the book page." }, { "code": null, "e": 82766, "s": 82616, "text": "Step 5 − Further, click Content management -> Books -> List as shown in the following screen. Click on edit order and titles under Operations column." }, { "code": null, "e": 83063, "s": 82766, "text": "Step 6 − You will see the screen as shown in the following screen. This page allows you to move your book pages around to fit your needs. Press and hold on the four pronged arrow and move it to the position to rearrange your pages. You can also drag the page to the right to make it a child page." }, { "code": null, "e": 83322, "s": 83063, "text": "In this chapter, we will study about Aggregator Module in Drupal. Aggregator Module takes the content from other websites but does not generate any feeds. It is also known as a feed reader. It gathers and displays texts and images from other sites and blogs." }, { "code": null, "e": 83375, "s": 83322, "text": "Following are the steps to enable Aggregator Module." }, { "code": null, "e": 83417, "s": 83375, "text": "Step 1 − Click Modules from the menu bar." }, { "code": null, "e": 83562, "s": 83417, "text": "Step 2 − A list of different modules gets displayed. Enable the Aggregator module and click Save Configuration as shown in the following screen." }, { "code": null, "e": 83655, "s": 83562, "text": "Step 3 − Now, go back to the aggregator module and click Configure option on the right side." }, { "code": null, "e": 83703, "s": 83655, "text": "Step 4 − A Feed aggregator page gets displayed." }, { "code": null, "e": 83752, "s": 83703, "text": "Following are the settings present on this page." }, { "code": null, "e": 83973, "s": 83752, "text": "Allowed HTML tags − This specifies that you can get only those HTML tags which are included in the given text box as you can see in the image. If you remove any of them you won't find that particular tag in your content." }, { "code": null, "e": 84194, "s": 83973, "text": "Allowed HTML tags − This specifies that you can get only those HTML tags which are included in the given text box as you can see in the image. If you remove any of them you won't find that particular tag in your content." }, { "code": null, "e": 84302, "s": 84194, "text": "Number of items shown in listing pages − Select the number of items you want to be displayed on your pages." }, { "code": null, "e": 84410, "s": 84302, "text": "Number of items shown in listing pages − Select the number of items you want to be displayed on your pages." }, { "code": null, "e": 84495, "s": 84410, "text": "Discard items older than − You can remove items that are older by using this option." }, { "code": null, "e": 84580, "s": 84495, "text": "Discard items older than − You can remove items that are older by using this option." }, { "code": null, "e": 84715, "s": 84580, "text": "Select categories using − You can select categories accordingly, either by clicking on Check boxes radio button or multiple selectors." }, { "code": null, "e": 84850, "s": 84715, "text": "Select categories using − You can select categories accordingly, either by clicking on Check boxes radio button or multiple selectors." }, { "code": null, "e": 84922, "s": 84850, "text": "Length of trimmed description − Select the length of your descriptions." }, { "code": null, "e": 84994, "s": 84922, "text": "Length of trimmed description − Select the length of your descriptions." }, { "code": null, "e": 85061, "s": 84994, "text": "Once you are done with all the settings, click Save Configuration." }, { "code": null, "e": 85197, "s": 85061, "text": "In this chapter, we will study about creating contact form in Drupal. Contact form is used to submit the information of user in Drupal." }, { "code": null, "e": 85244, "s": 85197, "text": "Following are the steps to add Contact module." }, { "code": null, "e": 85273, "s": 85244, "text": "Step 1 − Click Modules menu." }, { "code": null, "e": 85415, "s": 85273, "text": "Step 2 − A list of different modules gets displayed. Enable the Contact module and click Save Configuration as shown in the following screen." }, { "code": null, "e": 85516, "s": 85415, "text": "Step 3 − Go back to the contact module and click the Configure tab as shown in the following screen." }, { "code": null, "e": 85637, "s": 85516, "text": "Step 4 − Now you can view the information of all the categories and you can also add extra contacts. Click Add Category." }, { "code": null, "e": 85712, "s": 85637, "text": "Step 5 − The contact form gets displayed as shown in the following screen." }, { "code": null, "e": 85746, "s": 85712, "text": "It contains the following fields." }, { "code": null, "e": 85809, "s": 85746, "text": "Category − Specify the name of the category for feedback form." }, { "code": null, "e": 85872, "s": 85809, "text": "Category − Specify the name of the category for feedback form." }, { "code": null, "e": 85945, "s": 85872, "text": "Recipients − Specify the e-mail address where you wish to receive mails." }, { "code": null, "e": 86018, "s": 85945, "text": "Recipients − Specify the e-mail address where you wish to receive mails." }, { "code": null, "e": 86078, "s": 86018, "text": "Auto-reply − Sends the automatic reply message to the user." }, { "code": null, "e": 86138, "s": 86078, "text": "Auto-reply − Sends the automatic reply message to the user." }, { "code": null, "e": 86171, "s": 86138, "text": "Weight − Sets the list in order." }, { "code": null, "e": 86204, "s": 86171, "text": "Weight − Sets the list in order." }, { "code": null, "e": 86270, "s": 86204, "text": "Selected − Selecting Yes option, it sets the category as default." }, { "code": null, "e": 86336, "s": 86270, "text": "Selected − Selecting Yes option, it sets the category as default." }, { "code": null, "e": 86446, "s": 86336, "text": "After filling all information about the contact, click the Save button to save your contact form information." }, { "code": null, "e": 86588, "s": 86446, "text": "Step 6 − You can see the created contact form in the list as shown in the following screen. To view the contact form, click Contact form tab." }, { "code": null, "e": 86706, "s": 86588, "text": "Step 7 − The category which you have added will get displayed in the category field as shown in the following screen." }, { "code": null, "e": 86848, "s": 86706, "text": "In this chapter, we will learn about Form module in Drupal. This module lets you create a form in Drupal based on the website for your users." }, { "code": null, "e": 86906, "s": 86848, "text": "Following are the steps to install Form Module in Drupal." }, { "code": null, "e": 87010, "s": 86906, "text": "Step 1 − Download the latest file of Form Builder module from the link and install in your Drupal site." }, { "code": null, "e": 87068, "s": 87010, "text": "Step 2 − Enable Form Builder module from the module page." }, { "code": null, "e": 87124, "s": 87068, "text": "Step 3 − Click Form Builder example from the dashboard." }, { "code": null, "e": 87210, "s": 87124, "text": "Step 4 − A Form builder example page gets displayed as shown in the following screen." }, { "code": null, "e": 87265, "s": 87210, "text": "Here you can add, edit or remove the details manually." }, { "code": null, "e": 87296, "s": 87265, "text": "Sample Text Field (Properties)" }, { "code": null, "e": 87340, "s": 87296, "text": "Title − Enter the title name for your form." }, { "code": null, "e": 87384, "s": 87340, "text": "Title − Enter the title name for your form." }, { "code": null, "e": 87424, "s": 87384, "text": "Default value − Sets the default value." }, { "code": null, "e": 87464, "s": 87424, "text": "Default value − Sets the default value." }, { "code": null, "e": 87530, "s": 87464, "text": "Description − Enter description related to the title in that box." }, { "code": null, "e": 87596, "s": 87530, "text": "Description − Enter description related to the title in that box." }, { "code": null, "e": 87624, "s": 87596, "text": "Sample Text Field (Display)" }, { "code": null, "e": 87656, "s": 87624, "text": "Prefix − Enter the prefix text." }, { "code": null, "e": 87688, "s": 87656, "text": "Prefix − Enter the prefix text." }, { "code": null, "e": 87732, "s": 87688, "text": "Suffix − Here you must put the suffix text." }, { "code": null, "e": 87776, "s": 87732, "text": "Suffix − Here you must put the suffix text." }, { "code": null, "e": 87807, "s": 87776, "text": "Size − Input size accordingly." }, { "code": null, "e": 87838, "s": 87807, "text": "Size − Input size accordingly." }, { "code": null, "e": 87869, "s": 87838, "text": "Sample Text Field (Validation)" }, { "code": null, "e": 87937, "s": 87869, "text": "Required − Check the box, when you want to validate the text field." }, { "code": null, "e": 88005, "s": 87937, "text": "Required − Check the box, when you want to validate the text field." }, { "code": null, "e": 88036, "s": 88005, "text": "Sample Checkboxes (Properties)" }, { "code": null, "e": 88081, "s": 88036, "text": "Title − Enter your title name for your form." }, { "code": null, "e": 88126, "s": 88081, "text": "Title − Enter your title name for your form." }, { "code": null, "e": 88192, "s": 88126, "text": "Description − Enter description related to the title in that box." }, { "code": null, "e": 88258, "s": 88192, "text": "Description − Enter description related to the title in that box." }, { "code": null, "e": 88286, "s": 88258, "text": "Sample Checkboxes (Options)" }, { "code": null, "e": 88345, "s": 88286, "text": "Options − Add items, mark as default and input the values." }, { "code": null, "e": 88404, "s": 88345, "text": "Options − Add items, mark as default and input the values." }, { "code": null, "e": 88476, "s": 88404, "text": "Customize Keys − Enable this setting if you want to save any one value." }, { "code": null, "e": 88548, "s": 88476, "text": "Customize Keys − Enable this setting if you want to save any one value." }, { "code": null, "e": 88579, "s": 88548, "text": "Sample Checkboxes (Validation)" }, { "code": null, "e": 88641, "s": 88579, "text": "Required − Check the box when you want to validate the field." }, { "code": null, "e": 88703, "s": 88641, "text": "Required − Check the box when you want to validate the field." }, { "code": null, "e": 88733, "s": 88703, "text": "Sample Text Area (Properties)" }, { "code": null, "e": 88777, "s": 88733, "text": "Title − Enter the title name for your form." }, { "code": null, "e": 88821, "s": 88777, "text": "Title − Enter the title name for your form." }, { "code": null, "e": 88860, "s": 88821, "text": "Default value − Set the default value." }, { "code": null, "e": 88899, "s": 88860, "text": "Default value − Set the default value." }, { "code": null, "e": 88965, "s": 88899, "text": "Description − Enter description related to the title in that box." }, { "code": null, "e": 89031, "s": 88965, "text": "Description − Enter description related to the title in that box." }, { "code": null, "e": 89058, "s": 89031, "text": "Sample Text Area (Display)" }, { "code": null, "e": 89077, "s": 89058, "text": "Rows − Enter rows." }, { "code": null, "e": 89096, "s": 89077, "text": "Rows − Enter rows." }, { "code": null, "e": 89121, "s": 89096, "text": "Columns − Enter columns." }, { "code": null, "e": 89146, "s": 89121, "text": "Columns − Enter columns." }, { "code": null, "e": 89176, "s": 89146, "text": "Sample Text Area (Validation)" }, { "code": null, "e": 89238, "s": 89176, "text": "Required − Check the box when you want to validate the field." }, { "code": null, "e": 89300, "s": 89238, "text": "Required − Check the box when you want to validate the field." }, { "code": null, "e": 89327, "s": 89300, "text": "Sample Radios (Properties)" }, { "code": null, "e": 89371, "s": 89327, "text": "Title − Enter the title name for your form." }, { "code": null, "e": 89415, "s": 89371, "text": "Title − Enter the title name for your form." }, { "code": null, "e": 89481, "s": 89415, "text": "Description − Enter description related to the title in that box." }, { "code": null, "e": 89547, "s": 89481, "text": "Description − Enter description related to the title in that box." }, { "code": null, "e": 89571, "s": 89547, "text": "Sample Radios (Options)" }, { "code": null, "e": 89630, "s": 89571, "text": "Options − Add items, mark as default and input the values." }, { "code": null, "e": 89689, "s": 89630, "text": "Options − Add items, mark as default and input the values." }, { "code": null, "e": 89761, "s": 89689, "text": "Customize Keys − Enable this setting if you want to save any one value." }, { "code": null, "e": 89833, "s": 89761, "text": "Customize Keys − Enable this setting if you want to save any one value." }, { "code": null, "e": 89860, "s": 89833, "text": "Sample Radios (Validation)" }, { "code": null, "e": 89922, "s": 89860, "text": "Required − Check the box when you want to validate the field." }, { "code": null, "e": 89984, "s": 89922, "text": "Required − Check the box when you want to validate the field." }, { "code": null, "e": 90011, "s": 89984, "text": "Sample Select (Properties)" }, { "code": null, "e": 90055, "s": 90011, "text": "Title − Enter the title name for your form." }, { "code": null, "e": 90099, "s": 90055, "text": "Title − Enter the title name for your form." }, { "code": null, "e": 90165, "s": 90099, "text": "Description − Enter description related to the title in that box." }, { "code": null, "e": 90231, "s": 90165, "text": "Description − Enter description related to the title in that box." }, { "code": null, "e": 90255, "s": 90231, "text": "Sample Select (Options)" }, { "code": null, "e": 90327, "s": 90255, "text": "Customize Keys − Enable this setting if you want to save any one value." }, { "code": null, "e": 90399, "s": 90327, "text": "Customize Keys − Enable this setting if you want to save any one value." }, { "code": null, "e": 90481, "s": 90399, "text": "Allow Multiple values − This will help users choose multiple items in your lists." }, { "code": null, "e": 90563, "s": 90481, "text": "Allow Multiple values − This will help users choose multiple items in your lists." }, { "code": null, "e": 90764, "s": 90563, "text": "In this chapter, we will study how to create a Poll module in Drupal. This module helps you create polls for your website. You can ask questions, give any number of answers and your visitors can vote." }, { "code": null, "e": 90813, "s": 90764, "text": "Following are the steps to create a Poll Module." }, { "code": null, "e": 90854, "s": 90813, "text": "Step 1 − Click Module from the menu bar." }, { "code": null, "e": 90921, "s": 90854, "text": "Step 2 − Enable the Poll module and then click Save Configuration." }, { "code": null, "e": 91004, "s": 90921, "text": "Step 3 − Click Content → Add Content. Click Poll as shown in the following screen." }, { "code": null, "e": 91076, "s": 91004, "text": "Step 4 − A Create Poll page gets displayed where you can create a Poll." }, { "code": null, "e": 91110, "s": 91076, "text": "It contains the following fields." }, { "code": null, "e": 91165, "s": 91110, "text": "Question − Add a question you want to add in the poll." }, { "code": null, "e": 91220, "s": 91165, "text": "Question − Add a question you want to add in the poll." }, { "code": null, "e": 91341, "s": 91220, "text": "Poll Status − If you click Closed, then visitors cannot vote. And if you click Active then visitors are enabled to vote." }, { "code": null, "e": 91462, "s": 91341, "text": "Poll Status − If you click Closed, then visitors cannot vote. And if you click Active then visitors are enabled to vote." }, { "code": null, "e": 91606, "s": 91462, "text": "Poll Duration − Select a particular time period till you want your poll to exist. After the time period is completed the Poll closes by itself." }, { "code": null, "e": 91750, "s": 91606, "text": "Poll Duration − Select a particular time period till you want your poll to exist. After the time period is completed the Poll closes by itself." }, { "code": null, "e": 91811, "s": 91750, "text": "After you complete updating settings, click the Save button." }, { "code": null, "e": 92008, "s": 91811, "text": "In this chapter, we will study how to secure the Drupal site. This chapter specifies security configuration suggestions for site administrators and alerts the administrator how to secure the site." }, { "code": null, "e": 92180, "s": 92008, "text": "There are many contributed modules which help you with security configuration in which Security Review module automates testing the mistakes that makes your site insecure." }, { "code": null, "e": 92392, "s": 92180, "text": "You can report a security issue directly with Drupal core, contrib or Drupal.org by sending an e-mail regarding the issue. The security team will help in resolving your issue with the help of project maintainer." }, { "code": null, "e": 92604, "s": 92392, "text": "You can report a security issue directly with Drupal core, contrib or Drupal.org by sending an e-mail regarding the issue. The security team will help in resolving your issue with the help of project maintainer." }, { "code": null, "e": 92826, "s": 92604, "text": "Secure your file permissions and ownership by configuring the server file system, as the web server (e.g. Apache) should not have access to edit or write the files. It should be read only files, which gets executed later." }, { "code": null, "e": 93048, "s": 92826, "text": "Secure your file permissions and ownership by configuring the server file system, as the web server (e.g. Apache) should not have access to edit or write the files. It should be read only files, which gets executed later." }, { "code": null, "e": 93445, "s": 93048, "text": "The security risk levels are based on NIST Common Misuse Scoring System (NISTIR 7864), so that the organization can verify how to manage the problem. Below are the points that will help you understand the security risk level by assigning the number between 0 to 25 −\n\n0 to 4 − Not Critical.\n5 to 9 − Less Critical.\n10 to 14 − Moderately Critical.\n15 to 19 − Critical\n20 to 25 − Highly Critical.\n\n" }, { "code": null, "e": 93712, "s": 93445, "text": "The security risk levels are based on NIST Common Misuse Scoring System (NISTIR 7864), so that the organization can verify how to manage the problem. Below are the points that will help you understand the security risk level by assigning the number between 0 to 25 −" }, { "code": null, "e": 93735, "s": 93712, "text": "0 to 4 − Not Critical." }, { "code": null, "e": 93758, "s": 93735, "text": "0 to 4 − Not Critical." }, { "code": null, "e": 93782, "s": 93758, "text": "5 to 9 − Less Critical." }, { "code": null, "e": 93806, "s": 93782, "text": "5 to 9 − Less Critical." }, { "code": null, "e": 93838, "s": 93806, "text": "10 to 14 − Moderately Critical." }, { "code": null, "e": 93870, "s": 93838, "text": "10 to 14 − Moderately Critical." }, { "code": null, "e": 93890, "s": 93870, "text": "15 to 19 − Critical" }, { "code": null, "e": 93910, "s": 93890, "text": "15 to 19 − Critical" }, { "code": null, "e": 93938, "s": 93910, "text": "20 to 25 − Highly Critical." }, { "code": null, "e": 93966, "s": 93938, "text": "20 to 25 − Highly Critical." }, { "code": null, "e": 94303, "s": 93966, "text": "While accepting the sensitive information like credit card number, the PCI (Payment Card Industry) defines a number of Data Security Standards. Though this is not Drupal specific, it is important for each Drupal developer to be aware of this. To know more about the PCI issues, you can refer this link Drupal PCI Compliance White Paper." }, { "code": null, "e": 94640, "s": 94303, "text": "While accepting the sensitive information like credit card number, the PCI (Payment Card Industry) defines a number of Data Security Standards. Though this is not Drupal specific, it is important for each Drupal developer to be aware of this. To know more about the PCI issues, you can refer this link Drupal PCI Compliance White Paper." }, { "code": null, "e": 94787, "s": 94640, "text": "The users are allowed to be deleted or even for the users to delete themselves in Drupal site which can lead to an unexpected situation sometimes." }, { "code": null, "e": 94934, "s": 94787, "text": "The users are allowed to be deleted or even for the users to delete themselves in Drupal site which can lead to an unexpected situation sometimes." }, { "code": null, "e": 95200, "s": 94934, "text": "Enable HTTPS, which is more secure to send sensitive information to a website such as−\n\nCredit cards\nSensitive cookies such as PHP session cookies\nPasswords and Usernames\nIdentifiable information (Social Security number, State ID numbers, etc)\nConfidential content\n" }, { "code": null, "e": 95287, "s": 95200, "text": "Enable HTTPS, which is more secure to send sensitive information to a website such as−" }, { "code": null, "e": 95300, "s": 95287, "text": "Credit cards" }, { "code": null, "e": 95313, "s": 95300, "text": "Credit cards" }, { "code": null, "e": 95359, "s": 95313, "text": "Sensitive cookies such as PHP session cookies" }, { "code": null, "e": 95405, "s": 95359, "text": "Sensitive cookies such as PHP session cookies" }, { "code": null, "e": 95429, "s": 95405, "text": "Passwords and Usernames" }, { "code": null, "e": 95453, "s": 95429, "text": "Passwords and Usernames" }, { "code": null, "e": 95526, "s": 95453, "text": "Identifiable information (Social Security number, State ID numbers, etc)" }, { "code": null, "e": 95599, "s": 95526, "text": "Identifiable information (Social Security number, State ID numbers, etc)" }, { "code": null, "e": 95620, "s": 95599, "text": "Confidential content" }, { "code": null, "e": 95641, "s": 95620, "text": "Confidential content" }, { "code": null, "e": 95728, "s": 95641, "text": "Enhance your security using contributed modules. Some standard module categories are −" }, { "code": null, "e": 95815, "s": 95728, "text": "Enhance your security using contributed modules. Some standard module categories are −" }, { "code": null, "e": 95833, "s": 95815, "text": "Security category" }, { "code": null, "e": 95851, "s": 95833, "text": "Security category" }, { "code": null, "e": 95880, "s": 95851, "text": "User access / authentication" }, { "code": null, "e": 95909, "s": 95880, "text": "User access / authentication" }, { "code": null, "e": 95933, "s": 95909, "text": "Spam prevention modules" }, { "code": null, "e": 95957, "s": 95933, "text": "Spam prevention modules" }, { "code": null, "e": 96055, "s": 95957, "text": "You can disable the roles and permissions of the user by installing the Secure Permission module." }, { "code": null, "e": 96153, "s": 96055, "text": "You can disable the roles and permissions of the user by installing the Secure Permission module." }, { "code": null, "e": 96256, "s": 96153, "text": "The security operation can be improved in the login operation by installing the Login Security module." }, { "code": null, "e": 96359, "s": 96256, "text": "The security operation can be improved in the login operation by installing the Login Security module." }, { "code": null, "e": 96623, "s": 96359, "text": "The site administrator can secure its site by making it private and by restricting the site to limited access for the users by the role. Due to this process, your site will not be reachable to search engines and other crawlers (to create an index of data in www)." }, { "code": null, "e": 96887, "s": 96623, "text": "The site administrator can secure its site by making it private and by restricting the site to limited access for the users by the role. Due to this process, your site will not be reachable to search engines and other crawlers (to create an index of data in www)." }, { "code": null, "e": 97096, "s": 96887, "text": "Basically cart is a process of collecting items or services and uses checkout to collect payment. In this article, we will see how to set up a shopping cart for Drupal site by using Commerce Kickstart module." }, { "code": null, "e": 97342, "s": 97096, "text": "Commerce Kickstart is a good way to work with Drupal - E-Commerce which comes with different types of features to create user-friendly web store making it easier to launch and administer. You can download the Drupal Commerce Kickstart from here." }, { "code": null, "e": 97520, "s": 97342, "text": "Step 1 − Download the latest file of Commerce Kickstart module from the above link and install it on your system. After installing the module, you will get the following screen." }, { "code": null, "e": 97646, "s": 97520, "text": "Step 2 − Before adding products in your cart, you need to create products in the store. Click Add Product --> Create Product." }, { "code": null, "e": 97712, "s": 97646, "text": "Step 3 − You can create product as shown in the following screen." }, { "code": null, "e": 97773, "s": 97712, "text": "Following are the details of the fields present on the page." }, { "code": null, "e": 97836, "s": 97773, "text": "Product SKU − Unique identifier for the product is given here." }, { "code": null, "e": 97899, "s": 97836, "text": "Product SKU − Unique identifier for the product is given here." }, { "code": null, "e": 97948, "s": 97899, "text": "Title − This specifies the title of the product." }, { "code": null, "e": 97997, "s": 97948, "text": "Title − This specifies the title of the product." }, { "code": null, "e": 98159, "s": 97997, "text": "Image − Here you can upload image and give alternate text for your product which will be used by screen readers, search engines, when the image cannot be loaded." }, { "code": null, "e": 98321, "s": 98159, "text": "Image − Here you can upload image and give alternate text for your product which will be used by screen readers, search engines, when the image cannot be loaded." }, { "code": null, "e": 98364, "s": 98321, "text": "Price − It contains price of the product.\n" }, { "code": null, "e": 98406, "s": 98364, "text": "Price − It contains price of the product." }, { "code": null, "e": 98617, "s": 98406, "text": "Status − Set this field to Active option, so that it can be added to shopping cart. If it is set to Disabled option, products cannot be added to shopping carts and may be hidden in administrative product lists." }, { "code": null, "e": 98828, "s": 98617, "text": "Status − Set this field to Active option, so that it can be added to shopping cart. If it is set to Disabled option, products cannot be added to shopping carts and may be hidden in administrative product lists." }, { "code": null, "e": 98898, "s": 98828, "text": "Change History − It provides history of changes made to the product.\n" }, { "code": null, "e": 98967, "s": 98898, "text": "Change History − It provides history of changes made to the product." }, { "code": null, "e": 99036, "s": 98967, "text": "After you are done with all settings, click the Save product button." }, { "code": null, "e": 99092, "s": 99036, "text": "Step 4 − You will see the created product in the table." }, { "code": null, "e": 99165, "s": 99092, "text": "Step 5 − To display your product in the cart, click Add product display." }, { "code": null, "e": 99396, "s": 99165, "text": "In this window, Title field contains title of the product, you can add summary for the product in the Body field. Product field uses product SKU to display for the sale. After you are done with the settings, click the Save button." }, { "code": null, "e": 99491, "s": 99396, "text": "Step 6 − You will see the product displayed on the home page as shown in the following screen." }, { "code": null, "e": 99569, "s": 99491, "text": "Step 7 − Click the Add to cart button to add the created product in the cart." }, { "code": null, "e": 99716, "s": 99569, "text": "It will display the successful message after adding product to the cart. You can see the product name along with price in the Shopping cart block." }, { "code": null, "e": 99801, "s": 99716, "text": "Step 8 − Now click the View cart link to see the added product in the shopping cart." }, { "code": null, "e": 99905, "s": 99801, "text": "Step 9 − You will see the shopping cart table along with the products as shown in the following screen." }, { "code": null, "e": 100024, "s": 99905, "text": "In this chapter, we'll study about Creating Products in Drupal site. Products are the items that are offered for sale." }, { "code": null, "e": 100082, "s": 100024, "text": "Following are the simple steps used for Creating Product." }, { "code": null, "e": 100110, "s": 100082, "text": "Step 1 − Click Add Product." }, { "code": null, "e": 100144, "s": 100110, "text": "Step 2 − Click on Create Product." }, { "code": null, "e": 100255, "s": 100144, "text": "Step 3 − Now you have to create a product by filling the product information as shown in the following screen." }, { "code": null, "e": 100290, "s": 100255, "text": "It contains the following fields −" }, { "code": null, "e": 100357, "s": 100290, "text": "Product SKU − Enter the unique identifying number for the product." }, { "code": null, "e": 100424, "s": 100357, "text": "Product SKU − Enter the unique identifying number for the product." }, { "code": null, "e": 100464, "s": 100424, "text": "Title − Enter the title of the product." }, { "code": null, "e": 100504, "s": 100464, "text": "Title − Enter the title of the product." }, { "code": null, "e": 100656, "s": 100504, "text": "Image − Upload image and give alternate text for your product which will be used by screen readers, search engines, or when the image cannot be loaded." }, { "code": null, "e": 100808, "s": 100656, "text": "Image − Upload image and give alternate text for your product which will be used by screen readers, search engines, or when the image cannot be loaded." }, { "code": null, "e": 100848, "s": 100808, "text": "Price − Enter the price of the product." }, { "code": null, "e": 100888, "s": 100848, "text": "Price − Enter the price of the product." }, { "code": null, "e": 101099, "s": 100888, "text": "Status − Set this field to Active option, so that it can be added to shopping cart. If it is set to Disabled option, products cannot be added to shopping carts and may be hidden in administrative product lists." }, { "code": null, "e": 101310, "s": 101099, "text": "Status − Set this field to Active option, so that it can be added to shopping cart. If it is set to Disabled option, products cannot be added to shopping carts and may be hidden in administrative product lists." }, { "code": null, "e": 101379, "s": 101310, "text": "Change History − It provides history of changes made to the product." }, { "code": null, "e": 101448, "s": 101379, "text": "Change History − It provides history of changes made to the product." }, { "code": null, "e": 101500, "s": 101448, "text": "After filling the fields, click Save Configuration." }, { "code": null, "e": 101614, "s": 101500, "text": "Step(4) − Now you can see that your product is added, click Add product display as shown in the following screen." }, { "code": null, "e": 101709, "s": 101614, "text": "Step(5) − The Create Product display page will get displayed as shown in the following screen." }, { "code": null, "e": 101736, "s": 101709, "text": "It contains below fields −" }, { "code": null, "e": 101770, "s": 101736, "text": "Title − Add title of the product." }, { "code": null, "e": 101804, "s": 101770, "text": "Title − Add title of the product." }, { "code": null, "e": 101853, "s": 101804, "text": "Body − Here you can add summary for the product." }, { "code": null, "e": 101902, "s": 101853, "text": "Body − Here you can add summary for the product." }, { "code": null, "e": 102037, "s": 101902, "text": "Product − Choose the products to display for sale on this node by SKU. You can also enter multiple SKU's using a comma separated list." }, { "code": null, "e": 102172, "s": 102037, "text": "Product − Choose the products to display for sale on this node by SKU. You can also enter multiple SKU's using a comma separated list." }, { "code": null, "e": 102236, "s": 102172, "text": "Step(6) − You can see your product displayed on the front page." }, { "code": null, "e": 102487, "s": 102236, "text": "In this chapter, we will study how to Create Categories in Drupal. Taxonomy can be considered as categories or tags. Drupal taxonomy is built up of vocabularies and terms. A vocabulary is a set of terms and terms are just another word for categories." }, { "code": null, "e": 102550, "s": 102487, "text": "Following are the simple steps to create categories in Drupal." }, { "code": null, "e": 102644, "s": 102550, "text": "Step 1 − Go to Structure and click Taxonomy in the category as shown in the following screen." }, { "code": null, "e": 102683, "s": 102644, "text": "Step 2 − Click on Add vocabulary link." }, { "code": null, "e": 102784, "s": 102683, "text": "Step 3 − Enter your new vocabulary (category) Name and Description as shown in the following screen." }, { "code": null, "e": 102836, "s": 102784, "text": "Click the Save button and your category is created." }, { "code": null, "e": 102960, "s": 102836, "text": "Step 4 − You will see your new category is added to the list. Further you can click add terms link to add some terms to it." }, { "code": null, "e": 103095, "s": 102960, "text": "Step 5 − You can add some sub categories to it. Enter the required details and click the Save button as shown in the following screen." }, { "code": null, "e": 103206, "s": 103095, "text": "Step 6 − Choose your parent category from the list and click list terms link to view your sub categories list." }, { "code": null, "e": 103282, "s": 103206, "text": "Following are the details about the fields present in the preceding screen." }, { "code": null, "e": 103349, "s": 103282, "text": "Edit vocabulary − You can edit your category name and description." }, { "code": null, "e": 103416, "s": 103349, "text": "Edit vocabulary − You can edit your category name and description." }, { "code": null, "e": 103464, "s": 103416, "text": "List terms − It displays your subcategory list." }, { "code": null, "e": 103512, "s": 103464, "text": "List terms − It displays your subcategory list." }, { "code": null, "e": 103574, "s": 103512, "text": "Add terms − You can add your subcategories through this link." }, { "code": null, "e": 103636, "s": 103574, "text": "Add terms − You can add your subcategories through this link." }, { "code": null, "e": 103781, "s": 103636, "text": "Step 7 − You will see the subcategories list. Here, you can edit your subcategory by clicking on the edit link as shown in the following screen." }, { "code": null, "e": 103916, "s": 103781, "text": "Step 8 − Next, you can also rearrange your subcategories by dragging them as per the demand. After rearranging, click the Save button." }, { "code": null, "e": 104087, "s": 103916, "text": "In general, tax is a financial charge upon a taxpayer or is a source of public revenue. Sales tax is a basic type of tax levied on the sale of certain goods and services." }, { "code": null, "e": 104169, "s": 104087, "text": "You can specify the tax rate for the products as defined in the following steps −" }, { "code": null, "e": 104215, "s": 104169, "text": "Step 1 − Go to Store and click Configuration." }, { "code": null, "e": 104283, "s": 104215, "text": "Step 2 − Click on the Taxes link which manages tax rates and types." }, { "code": null, "e": 104346, "s": 104283, "text": "Step 3 − Click Add a tax rate link to add tax for the product." }, { "code": null, "e": 104454, "s": 104346, "text": "Step 4 − It will open the taxes window for adding tax rate to the product as shown in the following screen." }, { "code": null, "e": 104488, "s": 104454, "text": "It contains some fields such as −" }, { "code": null, "e": 104525, "s": 104488, "text": "Title − It is title of the tax rate." }, { "code": null, "e": 104562, "s": 104525, "text": "Title − It is title of the tax rate." }, { "code": null, "e": 104648, "s": 104562, "text": "Display title − It is the front-end display title of the tax rate shown to customers." }, { "code": null, "e": 104734, "s": 104648, "text": "Display title − It is the front-end display title of the tax rate shown to customers." }, { "code": null, "e": 104785, "s": 104734, "text": "Description − It is used to describe the tax rate." }, { "code": null, "e": 104836, "s": 104785, "text": "Description − It is used to describe the tax rate." }, { "code": null, "e": 104921, "s": 104836, "text": "Rate − It is a percentage used to calculate the tax which is expressed as a decimal." }, { "code": null, "e": 105006, "s": 104921, "text": "Rate − It is a percentage used to calculate the tax which is expressed as a decimal." }, { "code": null, "e": 105076, "s": 105006, "text": "Type − It selects the tax type for the tax rate using drop-down menu." }, { "code": null, "e": 105146, "s": 105076, "text": "Type − It selects the tax type for the tax rate using drop-down menu." }, { "code": null, "e": 105208, "s": 105146, "text": "After filling all the fields, click the Save tax rate button." }, { "code": null, "e": 105320, "s": 105208, "text": "Step 5 − You will see the created tax rate name which is used for the product as shown in the following screen." }, { "code": null, "e": 105412, "s": 105320, "text": "Step 6 − Go to Home page and click the View cart link to see the products in shopping cart." }, { "code": null, "e": 105491, "s": 105412, "text": "Step 7 − Click the Checkout button to see the tax rate added for the products." }, { "code": null, "e": 105589, "s": 105491, "text": "Step 8 − You can see the tax rate added along with the Subtotal as shown in the following screen." }, { "code": null, "e": 105762, "s": 105589, "text": "In general, discount is a amount or percentage deducted from the normal selling price of the product. It is the way of offering products for sale at a low or reduced price." }, { "code": null, "e": 105839, "s": 105762, "text": "You can specify the discount for the products as defined in the below steps−" }, { "code": null, "e": 105885, "s": 105839, "text": "Step 1 − Go to Store and click Configuration." }, { "code": null, "e": 105953, "s": 105885, "text": "Step 2 − Click on the Taxes link which manages tax rates and types." }, { "code": null, "e": 106017, "s": 105953, "text": "Step 3 − Go to TAX TYPES tab and click the Add a tax type link." }, { "code": null, "e": 106152, "s": 106017, "text": "Step 4 − Tax types categorize tax rates and specify whether or not the calculated tax should be included in product prices on display." }, { "code": null, "e": 106186, "s": 106152, "text": "It contains some fields such as −" }, { "code": null, "e": 106230, "s": 106186, "text": "Title − It specifies the title of tax type." }, { "code": null, "e": 106274, "s": 106230, "text": "Title − It specifies the title of tax type." }, { "code": null, "e": 106363, "s": 106274, "text": "Display title − It is the front-end display of the title of tax type shown to customers." }, { "code": null, "e": 106452, "s": 106363, "text": "Display title − It is the front-end display of the title of tax type shown to customers." }, { "code": null, "e": 106506, "s": 106452, "text": "Description − It describes the tax type if necessary." }, { "code": null, "e": 106560, "s": 106506, "text": "Description − It describes the tax type if necessary." }, { "code": null, "e": 106709, "s": 106560, "text": "Tax amount rounding mode − Specifies what type of rounding should occur when tax rates of tax type are calculated for the unit price of a line item." }, { "code": null, "e": 106858, "s": 106709, "text": "Tax amount rounding mode − Specifies what type of rounding should occur when tax rates of tax type are calculated for the unit price of a line item." }, { "code": null, "e": 106921, "s": 106858, "text": "After filling all the details, click the Save tax type button." }, { "code": null, "e": 106985, "s": 106921, "text": "Step 5 − Go to TAX RATES tab and click the Add a tax rate link." }, { "code": null, "e": 107093, "s": 106985, "text": "Step 6 − It will open the taxes window for adding tax rate to the product as shown in the following screen." }, { "code": null, "e": 107127, "s": 107093, "text": "It contains some fields such as −" }, { "code": null, "e": 107168, "s": 107127, "text": "Title − It is the title of the tax rate." }, { "code": null, "e": 107209, "s": 107168, "text": "Title − It is the title of the tax rate." }, { "code": null, "e": 107295, "s": 107209, "text": "Display title − It is the front-end display title of the tax rate shown to customers." }, { "code": null, "e": 107381, "s": 107295, "text": "Display title − It is the front-end display title of the tax rate shown to customers." }, { "code": null, "e": 107432, "s": 107381, "text": "Description − It is used to describe the tax rate." }, { "code": null, "e": 107483, "s": 107432, "text": "Description − It is used to describe the tax rate." }, { "code": null, "e": 107568, "s": 107483, "text": "Rate − It is a percentage used to calculate the tax which is expressed as a decimal." }, { "code": null, "e": 107653, "s": 107568, "text": "Rate − It is a percentage used to calculate the tax which is expressed as a decimal." }, { "code": null, "e": 107723, "s": 107653, "text": "Type − It selects the tax type for the tax rate using drop-down menu." }, { "code": null, "e": 107793, "s": 107723, "text": "Type − It selects the tax type for the tax rate using drop-down menu." }, { "code": null, "e": 107852, "s": 107793, "text": "After filling the details, click the Save tax rate button." }, { "code": null, "e": 107906, "s": 107852, "text": "Step 7 − Once tax rate is saved, click the Home link." }, { "code": null, "e": 107992, "s": 107906, "text": "Step 8 − On the home page, click the Checkout link to see the shopping cart contents." }, { "code": null, "e": 108101, "s": 107992, "text": "Step 9 − On the checkout page, you will see the discount for the product which is included in product price." }, { "code": null, "e": 108290, "s": 108101, "text": "In this chapter, we will learn how to Receive Donation in Drupal. Donation is some amount of gift given by an organization or individual to a non-profit organization or private foundation." }, { "code": null, "e": 108345, "s": 108290, "text": "Following are the steps to receive donation in Drupal." }, { "code": null, "e": 108449, "s": 108345, "text": "Step 1 − Download the latest file of Commerce Custom Line Items module and install in your Drupal site." }, { "code": null, "e": 108548, "s": 108449, "text": "Step 2 − Enable the Commerce Custom Line Items and Others in Modules and click Save configuration." }, { "code": null, "e": 108593, "s": 108548, "text": "Step 3 − Next, go to Store --> Configuration" }, { "code": null, "e": 108628, "s": 108593, "text": "Step 4 − Click on Line item types." }, { "code": null, "e": 108683, "s": 108628, "text": "Step 5 − Then, click Add line item types to add items." }, { "code": null, "e": 108774, "s": 108683, "text": "Step 6 − Now, Add line item type page will get displayed as shown in the following screen." }, { "code": null, "e": 108803, "s": 108774, "text": "It contains fields such as −" }, { "code": null, "e": 108863, "s": 108803, "text": "Line item type name − Enter the name of the line item type." }, { "code": null, "e": 108923, "s": 108863, "text": "Line item type name − Enter the name of the line item type." }, { "code": null, "e": 108989, "s": 108923, "text": "Description − Enter a brief description about the line item type." }, { "code": null, "e": 109055, "s": 108989, "text": "Description − Enter a brief description about the line item type." }, { "code": null, "e": 109158, "s": 109055, "text": "Add form submit value − Enter the text of the button on the order page which allows adding line items." }, { "code": null, "e": 109261, "s": 109158, "text": "Add form submit value − Enter the text of the button on the order page which allows adding line items." }, { "code": null, "e": 109343, "s": 109261, "text": "Step 7 − You can view the created donation item in the list. Click manage fields." }, { "code": null, "e": 109439, "s": 109343, "text": "Step 8 − Add a new field as Donation Amount, Select Integer for type of data from the dropdown." }, { "code": null, "e": 109462, "s": 109439, "text": "Click the Save button." }, { "code": null, "e": 109617, "s": 109462, "text": "Step 9 − Now, after clicking on save, the page redirects to the field setting page as shown in the following screen. Click the Save field settings button." }, { "code": null, "e": 109679, "s": 109617, "text": "Step 10 − The page is redirected to the Donation Amount page." }, { "code": null, "e": 109708, "s": 109679, "text": "It contains fields such as −" }, { "code": null, "e": 109742, "s": 109708, "text": "Label − Donation type identifier." }, { "code": null, "e": 109776, "s": 109742, "text": "Label − Donation type identifier." }, { "code": null, "e": 109831, "s": 109776, "text": "Help text − Enter instructions to present to the user." }, { "code": null, "e": 109886, "s": 109831, "text": "Help text − Enter instructions to present to the user." }, { "code": null, "e": 109944, "s": 109886, "text": "Minimum − Enter the minimum value that should be allowed." }, { "code": null, "e": 110002, "s": 109944, "text": "Minimum − Enter the minimum value that should be allowed." }, { "code": null, "e": 110060, "s": 110002, "text": "Maximum − Enter the maximum value that should be allowed." }, { "code": null, "e": 110118, "s": 110060, "text": "Maximum − Enter the maximum value that should be allowed." }, { "code": null, "e": 110182, "s": 110118, "text": "Prefix − Enter the string that should be prefixed to the value." }, { "code": null, "e": 110246, "s": 110182, "text": "Prefix − Enter the string that should be prefixed to the value." }, { "code": null, "e": 110310, "s": 110246, "text": "Suffix − Enter the string that should be suffixed to the value." }, { "code": null, "e": 110374, "s": 110310, "text": "Suffix − Enter the string that should be suffixed to the value." }, { "code": null, "e": 110425, "s": 110374, "text": "Default Value − Enter the default donation amount." }, { "code": null, "e": 110476, "s": 110425, "text": "Default Value − Enter the default donation amount." }, { "code": null, "e": 110591, "s": 110476, "text": "Add to Cart Form Settings − Includes the product line item types in the ‘add to cart form’ to collect information." }, { "code": null, "e": 110706, "s": 110591, "text": "Add to Cart Form Settings − Includes the product line item types in the ‘add to cart form’ to collect information." }, { "code": null, "e": 110787, "s": 110706, "text": "Donation Amount Field settings − Number of values user can enter for this field." }, { "code": null, "e": 110868, "s": 110787, "text": "Donation Amount Field settings − Number of values user can enter for this field." }, { "code": null, "e": 110924, "s": 110868, "text": "After filling the page, click the Save settings button." }, { "code": null, "e": 111000, "s": 110924, "text": "Step 11 − Next, you can view the created Donation Amount field in the list." }, { "code": null, "e": 111056, "s": 111000, "text": "Following are the steps to create product for donation." }, { "code": null, "e": 111095, "s": 111058, "text": "Step 1 − Click on Store --> Products" }, { "code": null, "e": 111140, "s": 111095, "text": "Step 2 − Click Add a product to add product." }, { "code": null, "e": 111226, "s": 111140, "text": "Step 3 − Next, it will open a Create Product screen as shown in the following screen." }, { "code": null, "e": 111254, "s": 111226, "text": "It contain fields such as −" }, { "code": null, "e": 111311, "s": 111254, "text": "Product SKU − It is a unique identifier for the product." }, { "code": null, "e": 111368, "s": 111311, "text": "Product SKU − It is a unique identifier for the product." }, { "code": null, "e": 111415, "s": 111368, "text": "Title − It is title for the specified product." }, { "code": null, "e": 111462, "s": 111415, "text": "Title − It is title for the specified product." }, { "code": null, "e": 111497, "s": 111462, "text": "Image − Add image for the product." }, { "code": null, "e": 111532, "s": 111497, "text": "Image − Add image for the product." }, { "code": null, "e": 111573, "s": 111532, "text": "Price − Enter the amount of the product." }, { "code": null, "e": 111614, "s": 111573, "text": "Price − Enter the amount of the product." }, { "code": null, "e": 111822, "s": 111614, "text": "Status − Set this field to Active option, so that it can be added to shopping cart. If it set to Disabled option, products cannot be added to shopping carts and may be hidden in administrative product lists." }, { "code": null, "e": 112030, "s": 111822, "text": "Status − Set this field to Active option, so that it can be added to shopping cart. If it set to Disabled option, products cannot be added to shopping carts and may be hidden in administrative product lists." }, { "code": null, "e": 112092, "s": 112030, "text": "After filling all the details, click the Save product button." }, { "code": null, "e": 112177, "s": 112092, "text": "Step 4 − Now you can see the newly created product as shown in the following screen." }, { "code": null, "e": 112284, "s": 112177, "text": "Step 5 − Go to Structure --> Content Types. The following page will get displayed, click Add content type." }, { "code": null, "e": 112347, "s": 112284, "text": "Step 6 − Add a name as Donation and click Save and add fields." }, { "code": null, "e": 112425, "s": 112347, "text": "Step 7 − It will open the Manage Fields tab as shown in the following screen." }, { "code": null, "e": 112553, "s": 112425, "text": "Add fields into Add existing field section as Product and select Product reference from the dropdown and click the Save button." }, { "code": null, "e": 112632, "s": 112553, "text": "Step 8 − Now, Product page will get displayed, click the Save settings button." }, { "code": null, "e": 112693, "s": 112632, "text": "Step 9 − You can view the created Product field in the list." }, { "code": null, "e": 112848, "s": 112693, "text": "Step 10 − Now, click the Manage Display tab. Click the symbol present on the right side of the field Product, and the following screen will get displayed." }, { "code": null, "e": 112977, "s": 112848, "text": "Here, Select as Donation from the dropdown in Add to Cart line item type. Later click the Update button and then on Save button." }, { "code": null, "e": 113052, "s": 112977, "text": "Step 11 − Next, click Content --> Add Content to add donation information." }, { "code": null, "e": 113081, "s": 113052, "text": "Step 12 − Click on Donation." }, { "code": null, "e": 113150, "s": 113081, "text": "Step 13 − Enter your Donation information and click the Save button." }, { "code": null, "e": 113234, "s": 113150, "text": "Step 14 − The page of donation will get displayed as shown in the following screen." }, { "code": null, "e": 113321, "s": 113234, "text": "Here, you can fill the amount according to your wish and click the Add to cart button." }, { "code": null, "e": 113439, "s": 113321, "text": "Step 15 − Now, you can view the donation amounts in the block present on the right side of the page. Click View Cart." }, { "code": null, "e": 113527, "s": 113439, "text": "Step 16 − You can view the Shopping cart donation amount and click the Checkout button." }, { "code": null, "e": 113616, "s": 113527, "text": "Step 17 − Now, you can enter the information of billing and click Continue to next step." }, { "code": null, "e": 113742, "s": 113616, "text": "Step 18 − The next step is the review order page, where you can review the order information and click Continue to next step." }, { "code": null, "e": 113836, "s": 113742, "text": "Step 19 − A message will get displayed as Checkout complete as shown in the following screen." }, { "code": null, "e": 114208, "s": 113836, "text": "In this chapter, let us study about setting up Shipping options in Drupal. In general, Shipping refers to transport of goods from one location to another. In order to set up Shipping you have to install Commerce Flat Rate and Commerce Shipping modules. In this chapter, let us create Free Shipping for orders greater than $100 and Paid Shipping for orders less than $100." }, { "code": null, "e": 114259, "s": 114208, "text": "Following are the simple steps to set up Shipping." }, { "code": null, "e": 114338, "s": 114259, "text": "Step 1 − Go to Store and click Configuration as shown in the following screen." }, { "code": null, "e": 114366, "s": 114338, "text": "Step 2 − Click on Shipping." }, { "code": null, "e": 114439, "s": 114366, "text": "Step 3 − Click Add a flat rate service as shown in the following screen." }, { "code": null, "e": 114519, "s": 114439, "text": "Step 4 − The Shipping page will get displayed as shown in the following screen." }, { "code": null, "e": 114554, "s": 114519, "text": "It contains the following fields −" }, { "code": null, "e": 114636, "s": 114554, "text": "Title − Provide a title which will be the administrative title of this flat rate." }, { "code": null, "e": 114718, "s": 114636, "text": "Title − Provide a title which will be the administrative title of this flat rate." }, { "code": null, "e": 114819, "s": 114718, "text": "Display title − Enter title that will be displayed on front-end of the flat rate shown to customers." }, { "code": null, "e": 114920, "s": 114819, "text": "Display title − Enter title that will be displayed on front-end of the flat rate shown to customers." }, { "code": null, "e": 114979, "s": 114920, "text": "Description − Enter brief description about the flat rate." }, { "code": null, "e": 115038, "s": 114979, "text": "Description − Enter brief description about the flat rate." }, { "code": null, "e": 115085, "s": 115038, "text": "Base rate − Provide a value for the flat rate." }, { "code": null, "e": 115132, "s": 115085, "text": "Base rate − Provide a value for the flat rate." }, { "code": null, "e": 115162, "s": 115132, "text": "Later, click the Save button." }, { "code": null, "e": 115279, "s": 115162, "text": "Step 5 − Next, you have to configure the component by clicking configure component as shown in the following screen." }, { "code": null, "e": 115309, "s": 115279, "text": "Step 6 − Click Add condition." }, { "code": null, "e": 115375, "s": 115309, "text": "Step 7 − Choose Data comparison from dropdown and click Continue." }, { "code": null, "e": 115493, "s": 115375, "text": "Step 8 − For Data selector field, choose commerce-order...(Order) from the dropdown as shown in the following screen." }, { "code": null, "e": 115621, "s": 115493, "text": "Step 9 − Then, choose commerce-order:commerce-order-total:... (Order total) from the dropdown as shown in the following screen." }, { "code": null, "e": 115761, "s": 115621, "text": "Step 10 − Choose commerce-order:commerce-order-total:amount (Amount) from the dropdown and click Continue as shown in the following screen." }, { "code": null, "e": 115916, "s": 115761, "text": "Step 11 − Next, under OPERATOR section, you have to select is lower than value from the dropdown and click Switch to the direct input mode as shown below." }, { "code": null, "e": 116070, "s": 115916, "text": "Step 12 − Under DATA VALUE section, provide the value (usually the value given here is in cents (i.e. $100 = 10000 cents)). Later, click the Save button." }, { "code": null, "e": 116133, "s": 116070, "text": "Step 13 − Click Save changes as shown in the following screen." }, { "code": null, "e": 116303, "s": 116133, "text": "Step 14 − For Free Shipping you have to create another Flat rate service (as we did in Step(3 and 4)) and provide zero(0) for Base rate as shown in the following screen." }, { "code": null, "e": 116547, "s": 116303, "text": "Step 15 − Configure the component for Free Shipping (follow the same steps from 5 to 10 for free shipping as well), choose ‘is greater than’ and provide 10000 (i.e. 10000 cents) value as shown in the following screen and click the Save button." }, { "code": null, "e": 116636, "s": 116547, "text": "Step 16 − Add a product to the cart which is less than $100 and click the Check out tab." }, { "code": null, "e": 116768, "s": 116636, "text": "Step 17 − Next, fill up Shipping information, Billing information and click Continue to next step as shown in the following screen." }, { "code": null, "e": 116863, "s": 116768, "text": "Step 18 − Now you can see the Paid Shipping option displayed as shown in the following screen." }, { "code": null, "e": 116939, "s": 116863, "text": "Step 19 − You can add some more products, so that Order total exceeds $100." }, { "code": null, "e": 117036, "s": 116939, "text": "Step 20 − Finally, you can see that Free Shipping option is displayed after it exceeds the $100." }, { "code": null, "e": 117203, "s": 117036, "text": "In this chapter, we will study how to set up Payments in Drupal. Payment is a process of paying money in exchange of goods, services or both to a company or a person." }, { "code": null, "e": 117257, "s": 117203, "text": "Following are the steps to set up payments in Drupal." }, { "code": null, "e": 117388, "s": 117257, "text": "Step 1 − Download the latest file of Basic Payment module and PayPal Payment module from the link and install in your Drupal site." }, { "code": null, "e": 117488, "s": 117388, "text": "Step 2 − Next, Enable the Basic Payment and PayPal Payment in Modules and click Save configuration." }, { "code": null, "e": 117563, "s": 117488, "text": "Step 3 − Click Configuration --> Payment as shown in the following screen." }, { "code": null, "e": 117595, "s": 117563, "text": "Step 4 − Click Payment methods." }, { "code": null, "e": 117636, "s": 117595, "text": "Step 5 − Then, click Add payment method." }, { "code": null, "e": 117677, "s": 117636, "text": "Step 6 − Click PayPal Payments Standard." }, { "code": null, "e": 117733, "s": 117677, "text": "Step 7 − You have to fill the form for PayPal payments." }, { "code": null, "e": 117768, "s": 117733, "text": "It contains the following fields −" }, { "code": null, "e": 117817, "s": 117768, "text": "Title(specific) − Enter the specific title name." }, { "code": null, "e": 117866, "s": 117817, "text": "Title(specific) − Enter the specific title name." }, { "code": null, "e": 117913, "s": 117866, "text": "Title(generic) − Enter the generic title name." }, { "code": null, "e": 117960, "s": 117913, "text": "Title(generic) − Enter the generic title name." }, { "code": null, "e": 117997, "s": 117960, "text": "Owner − Enter the name of the owner." }, { "code": null, "e": 118034, "s": 117997, "text": "Owner − Enter the name of the owner." }, { "code": null, "e": 118091, "s": 118034, "text": "PayPal account email address − Enter your email address." }, { "code": null, "e": 118148, "s": 118091, "text": "PayPal account email address − Enter your email address." }, { "code": null, "e": 118226, "s": 118148, "text": "Server − Select the server from either of the one i.e. Production or Sandbox." }, { "code": null, "e": 118304, "s": 118226, "text": "Server − Select the server from either of the one i.e. Production or Sandbox." }, { "code": null, "e": 118380, "s": 118304, "text": "Capture − Select either of the one capture method i.e. Manual or Automatic." }, { "code": null, "e": 118456, "s": 118380, "text": "Capture − Select either of the one capture method i.e. Manual or Automatic." }, { "code": null, "e": 118526, "s": 118456, "text": "Step 8 − You can view the above created PayPal in the following list." }, { "code": null, "e": 118639, "s": 118526, "text": "Step 9 − Next, go to Structure --> Content Types. The following page will get displayed, click Add content type." }, { "code": null, "e": 118701, "s": 118639, "text": "Step 10 − Create a content type name as Products and save it." }, { "code": null, "e": 118787, "s": 118701, "text": "Step 11 − You can view the created Products content in the list. Click manage fields." }, { "code": null, "e": 118881, "s": 118787, "text": "Step 12 − Add a new field as Buy Now, Select Payment form for type of data from the dropdown." }, { "code": null, "e": 118904, "s": 118881, "text": "Click the Save button." }, { "code": null, "e": 118971, "s": 118904, "text": "Step 13 − Now, you can view the created Buy Now field in the list." }, { "code": null, "e": 119015, "s": 118971, "text": "Step 14 − Go to Content, click Add content." }, { "code": null, "e": 119041, "s": 119015, "text": "Step 15 − Click Products." }, { "code": null, "e": 119160, "s": 119041, "text": "Step 16 − Enter your product information inside the fields as shown in the following screen and click the Save button." }, { "code": null, "e": 119265, "s": 119160, "text": "Step 17 − You can now view your content on your site as shown in the following screen. Click Pay button." }, { "code": null, "e": 119354, "s": 119265, "text": "Step 18 − You will be redirected to the offsite payment server to authorize the payment." }, { "code": null, "e": 119428, "s": 119354, "text": "Later, it will direct you to the PayPal site for future payments process." }, { "code": null, "e": 119550, "s": 119428, "text": "Step 19 − Once the payment process is complete, you can view the details of the payment as shown in the following screen." }, { "code": null, "e": 119647, "s": 119550, "text": "Step 20 − Go to Content --> Payments tab. Here, you can view the payment status of your product." }, { "code": null, "e": 119813, "s": 119647, "text": "In this chapter, we'll study how to generate invoice in Drupal. Invoice is a document with a statement of amount and cost, unique invoice number and tax information." }, { "code": null, "e": 119868, "s": 119813, "text": "Following are the steps to generate invoice in Drupal." }, { "code": null, "e": 119953, "s": 119868, "text": "Step 1 − Download the latest file of Invoice module and install in your Drupal site." }, { "code": null, "e": 120022, "s": 119953, "text": "Step 2 − Enable the Invoice in Modules and click Save configuration." }, { "code": null, "e": 120057, "s": 120022, "text": "Step 3 − Go to Store --> Invoices." }, { "code": null, "e": 120085, "s": 120057, "text": "Step 4 − Click Add Invoice." }, { "code": null, "e": 120129, "s": 120085, "text": "Step 5 − You can view the Add Invoice page." }, { "code": null, "e": 120191, "s": 120129, "text": "Invoice # − Enter the invoice id number sent to the customer." }, { "code": null, "e": 120253, "s": 120191, "text": "Invoice # − Enter the invoice id number sent to the customer." }, { "code": null, "e": 120319, "s": 120253, "text": "Company Name − Enter the company name who should pay the invoice." }, { "code": null, "e": 120385, "s": 120319, "text": "Company Name − Enter the company name who should pay the invoice." }, { "code": null, "e": 120452, "s": 120385, "text": "Invoice Amount in USD − Enter the amount that customer has to pay." }, { "code": null, "e": 120519, "s": 120452, "text": "Invoice Amount in USD − Enter the amount that customer has to pay." }, { "code": null, "e": 120573, "s": 120519, "text": "After filling the invoice details, click Add Invoice." }, { "code": null, "e": 120678, "s": 120573, "text": "Step 6 − Go to Store --> Invoice --> Manage Invoices. Here, you can view your pending and paid invoices." }, { "code": null, "e": 120764, "s": 120678, "text": "Copy the link given in the detail column and it'll redirect you to the checkout page." }, { "code": null, "e": 120939, "s": 120764, "text": "Step 7 − You can also pay by navigating to the given link localhost<Your Site Name>user/invoices/pay, it'll redirect you to Pay Invoice page as shown in the following screen." }, { "code": null, "e": 121175, "s": 120939, "text": "Here, you have to enter the invoice number and click Pay Invoice button. It will then redirect you to the Checkout page as shown in the following screen. You can enter the information for billing and click Continue to next step button." }, { "code": null, "e": 121308, "s": 121175, "text": "Step 8 − You can review the product information and also the invoice number and company name. Click on Continue to next step button." }, { "code": null, "e": 121407, "s": 121308, "text": "Step 9 − A final message will get displayed as Checkout complete as shown in the following screen." }, { "code": null, "e": 121619, "s": 121407, "text": "In this chapter, we will learn how to send E-mail Notifications to the owner or creator, when a new comment is posted to the article. E-mail Notification is an alert that a new mail has arrived in your mail box." }, { "code": null, "e": 121691, "s": 121619, "text": "Following are the simple steps to set up e-mail notification in Drupal." }, { "code": null, "e": 121736, "s": 121691, "text": "Step 1 − Click Configuration menu on Drupal." }, { "code": null, "e": 121826, "s": 121736, "text": "Step 2 − Next, click Rules link in the WORKFLOW section as shown in the following screen." }, { "code": null, "e": 121860, "s": 121826, "text": "Step 3 − Click Add new rule link." }, { "code": null, "e": 121943, "s": 121860, "text": "Step 4 − Next, the Rules page will get displayed as shown in the following screen." }, { "code": null, "e": 121978, "s": 121943, "text": "It contains the following fields −" }, { "code": null, "e": 122001, "s": 121978, "text": "Name − Enter the name." }, { "code": null, "e": 122024, "s": 122001, "text": "Name − Enter the name." }, { "code": null, "e": 122046, "s": 122024, "text": "Tags − Enter the tags" }, { "code": null, "e": 122068, "s": 122046, "text": "Tags − Enter the tags" }, { "code": null, "e": 122140, "s": 122068, "text": "React on Event − Select the event where the notification should arrive." }, { "code": null, "e": 122212, "s": 122140, "text": "React on Event − Select the event where the notification should arrive." }, { "code": null, "e": 122294, "s": 122212, "text": "Restrict by Type − Select the type where you need to filter the values or events." }, { "code": null, "e": 122376, "s": 122294, "text": "Restrict by Type − Select the type where you need to filter the values or events." }, { "code": null, "e": 122446, "s": 122376, "text": "After filling all the fields, click the Save button to save the rule." }, { "code": null, "e": 122601, "s": 122446, "text": "Step 5 − Now, Editing reaction rule \"Comment Notification\" page gets displayed. Click Add action link in Actions section as shown in the following screen." }, { "code": null, "e": 122714, "s": 122601, "text": "Step 6 − Add a new action page gets displayed. Select Send mail option in System section from the dropdown menu." }, { "code": null, "e": 122789, "s": 122714, "text": "Step 7 − Next, a page will get displayed as shown in the following screen." }, { "code": null, "e": 122865, "s": 122789, "text": "Following are the details about the fields present in the preceding screen." }, { "code": null, "e": 122937, "s": 122865, "text": "Data selector − Select comment→node→author→mail from the dropdown menu." }, { "code": null, "e": 123009, "s": 122937, "text": "Data selector − Select comment→node→author→mail from the dropdown menu." }, { "code": null, "e": 123065, "s": 123009, "text": "Subject − Enter the mail subject in the Value text box." }, { "code": null, "e": 123121, "s": 123065, "text": "Subject − Enter the mail subject in the Value text box." }, { "code": null, "e": 123288, "s": 123121, "text": "REPLACEMENT PATTERNS − This data selection input mode may help you find more complex replacement patterns. You can select the TOKEN type and replace it as per demand." }, { "code": null, "e": 123455, "s": 123288, "text": "REPLACEMENT PATTERNS − This data selection input mode may help you find more complex replacement patterns. You can select the TOKEN type and replace it as per demand." }, { "code": null, "e": 123530, "s": 123455, "text": "MESSAGE − Enter mail's message body content in the message Value text box." }, { "code": null, "e": 123605, "s": 123530, "text": "MESSAGE − Enter mail's message body content in the message Value text box." }, { "code": null, "e": 123688, "s": 123605, "text": "FROM − It displays the mail address from which mails will be sent to the receiver." }, { "code": null, "e": 123771, "s": 123688, "text": "FROM − It displays the mail address from which mails will be sent to the receiver." }, { "code": null, "e": 123907, "s": 123771, "text": "LANGUAGE − It specifies the language used for getting the mail message and subject. You can choose the language from the dropdown menu." }, { "code": null, "e": 124043, "s": 123907, "text": "LANGUAGE − It specifies the language used for getting the mail message and subject. You can choose the language from the dropdown menu." }, { "code": null, "e": 124091, "s": 124043, "text": "Click the Save button to save the notification." }, { "code": null, "e": 124169, "s": 124091, "text": "Step 8 − You will see the following screen, after you save your notification." }, { "code": null, "e": 124341, "s": 124169, "text": "Order history is dependent on the ordered products by the user after checkout. It includes history of the product which includes order number, user name, order status etc." }, { "code": null, "e": 124418, "s": 124341, "text": "You can view the order history of the product by using the following steps −" }, { "code": null, "e": 124466, "s": 124418, "text": "Step 1 − Go to Store and click the Orders link." }, { "code": null, "e": 124529, "s": 124466, "text": "Step 2 − You will get the screen of the ordered products list." }, { "code": null, "e": 124558, "s": 124529, "text": "It contains fields such as −" }, { "code": null, "e": 124608, "s": 124558, "text": "Order Number − It is the order number of product." }, { "code": null, "e": 124658, "s": 124608, "text": "Order Number − It is the order number of product." }, { "code": null, "e": 124721, "s": 124658, "text": "Updated − It specifies when the product has been updated last." }, { "code": null, "e": 124784, "s": 124721, "text": "Updated − It specifies when the product has been updated last." }, { "code": null, "e": 124847, "s": 124784, "text": "Name − It is the name of the user who has ordered the product." }, { "code": null, "e": 124910, "s": 124847, "text": "Name − It is the name of the user who has ordered the product." }, { "code": null, "e": 124995, "s": 124910, "text": "User − It is the account name of the user. It may be authenticated by user or admin." }, { "code": null, "e": 125080, "s": 124995, "text": "User − It is the account name of the user. It may be authenticated by user or admin." }, { "code": null, "e": 125138, "s": 125080, "text": "Total − It specifies total amount of the ordered product." }, { "code": null, "e": 125196, "s": 125138, "text": "Total − It specifies total amount of the ordered product." }, { "code": null, "e": 125293, "s": 125196, "text": "Order Status − Defines the order status such as processing or pending or completed or cancelled." }, { "code": null, "e": 125390, "s": 125293, "text": "Order Status − Defines the order status such as processing or pending or completed or cancelled." }, { "code": null, "e": 125465, "s": 125390, "text": "Operations − Here you can perform some operations on the product such as −" }, { "code": null, "e": 125540, "s": 125465, "text": "Operations − Here you can perform some operations on the product such as −" }, { "code": null, "e": 125611, "s": 125540, "text": "View option displays the billing information and shipping information." }, { "code": null, "e": 125682, "s": 125611, "text": "View option displays the billing information and shipping information." }, { "code": null, "e": 125767, "s": 125682, "text": "Edit option allows to edit the price, shipping information, billing information etc." }, { "code": null, "e": 125852, "s": 125767, "text": "Edit option allows to edit the price, shipping information, billing information etc." }, { "code": null, "e": 125972, "s": 125852, "text": "Delete option deletes the product order and payment option specifies paid amount for the product, date of expiry, etc.." }, { "code": null, "e": 126092, "s": 125972, "text": "Delete option deletes the product order and payment option specifies paid amount for the product, date of expiry, etc.." }, { "code": null, "e": 126127, "s": 126092, "text": "\n 61 Lectures \n 3.5 hours \n" }, { "code": null, "e": 126139, "s": 126127, "text": " Amit Diwan" }, { "code": null, "e": 126146, "s": 126139, "text": " Print" }, { "code": null, "e": 126157, "s": 126146, "text": " Add Notes" } ]
Background Removal with Python. Using OpenCV to Detect the Foreground | by Andrew Udell | Towards Data Science
We live in the era of video calls. Conducted over the internet and using whatever camera that comes with your laptop or computer, we broadcast our lives to our classmates, coworkers, and families. Sometimes, though, we don’t want to broadcast our space. My office, like many others, has a few perennial pieces of clutter. I also have a guitar on the wall behind me, which doesn’t always scream professionalism. As a result, Zoom and other video calling software includes a feature to hide your background, usually behind an image of your choice. While most don’t think of it much, the actual task of determining what determines the foreground and the background in an image is hardly trivial. Foreground detection is one of the most prominent applications in computer vision. Aside from the example of video calls, foreground detection may be used in finding and reading text in an image, determining where obstacles are in autonomous vehicles, and many other applications. As a result, many sophisticated methods have been developed to distinguish the foreground from the background. OpenCV provides a couple of “out-of-the-box” solutions; however, without any other context, these are black boxes that don’t present much opportunity to learn. Instead, I’ll use a custom-built algorithm that takes advantage of several OpenCV modules to achieve a similar result. The method I’ll demonstrate is foundational on two concepts: edge detection and contours. Edge detection, like the name implies, attempts to find the lines of contrast, or edges, in an image. This key first step pre-processes the image to help differentiate any objects. Several methods of edge detection exist, but the Canny method is both immensely popular and comes packaged with OpenCV. Once the edges are found, finding contours become much easier and more accurate. In computer vision, contours are simply the continuous boundary lines between areas of contrasting color or intensity. Unlike edge detection, finding contours will find prominent shapes within the image. As previously mentioned, the pre-packaged background removers in OpenCV will not be used. Instead, the below flow-chart outlines the method I’ll use: First, we’ll take the image and convert it to black and white. Next, edge detection will be applied and the contours in the image will be found. Any contours that are too either too big or too small to be the foreground will be removed. The remaining contours will be considered the foreground. This makes some intuitive sense, as especially small details in a busy background will generate very small contours. By contrast, very large contours which take up most the screen probably aren’t the foreground, but some visual artefact of the background. Finally a mask is generated from the remaining contours and is blended into the original image. import numpy as npimport cv2 Before doing much, two libraries need to be imported. NumPy works to make some the number-crunching more efficient. OpenCV handles the image manipulation. # Parametersblur = 21canny_low = 15canny_high = 150min_area = 0.0005max_area = 0.95dilate_iter = 10erode_iter = 10mask_color = (0.0,0.0,0.0) Next, a set of variables are assigned that will influence how the background is removed. Each variable has a unique effect, which may need to be fine tuned based on the subject of the video. In short: blur: affects the “smoothness” of the dividing line between the background and foreground canny_low: the minimum intensity value along which edges will be drawn canny_high: the maximum intensity value along which edges will be drawn min_area: the minimum area a contour in the foreground may occupy. Taken as a value between 0 and 1. max_area: the maximum area a contour in the foreground may occupy. Taken as a value between 0 and 1. dilate_iter: the number of iterations of dilation will take place on the mask. erode_iter: the number of iterations of erosion will take place on the mask. mask_color: the color of the background once it is removed. Some of these explanations may not make sense, yet, but they’ll be explained further as they appear in the code. In the meantime, feel free to take the values provided as defaults to get started. # initialize video from the webcamvideo = cv2.VideoCapture(0) Next, the web camera is initialized, if available. The 0 may be substituted for the path of video file if you don’t have one. while True: ret, frame = video.read() An infinite loop is started by reading the frames from the camera. The read method returns 2 values: A boolean to tell if the camera worked properly, stored in the ret variableAn actual frame from the video feed, recorded in the frame variable. A boolean to tell if the camera worked properly, stored in the ret variable An actual frame from the video feed, recorded in the frame variable. if ret == True: # Convert image to grayscale image_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Apply Canny Edge Dection edges = cv2.Canny(image_gray, canny_low, canny_high) The if-clause allows the code to proceed only if the camera correctly captured video. The frame is rendered into grayscale so the next step, edge detection, may take place. Setting the intensity value minimum (the canny_low variable) dictates how sensitive contrast must be to be detected. Adjusting it too low may result in more edges detected than necessary. Setting the intensity value maximum (the canny_high variable) dictates that any contrast above its value will be immediately classified as an edge. Adjusting it too high may affect performance, but pushing it too low may miss out on important edges. edges = cv2.dilate(edges, None) edges = cv2.erode(edges, None) This step is strictly optional, but dilating and eroding the edges make them more pronounced and returns a nicer final product. # get the contours and their areas contour_info = [(c, cv2.contourArea(c),) for c in cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)[1]] There’s a lot going on in this line, but it’s written this way for performance. Essentially, the OpenCV function findContours returns an array of information. Of this information, we only care about the the contours, which are indexed at 1. For all the contours found, a tuple of the actual contour itself and its area are stored in a list. # Get the area of the image as a comparison image_area = frame.shape[0] * frame.shape[1] # calculate max and min areas in terms of pixels max_area = max_area * image_area min_area = min_area * image_area The area of the image is calculated and then maximum and minimum areas are determined. Ideally, this step would be taken outside of the loop, since it hinders performance. Taking an initial frame before streaming or simply knowing your camera’s dimensions beforehand would be more performant. With that said, to keep the code a little simpler for demonstration, this is sufficient. # Set up mask with a matrix of 0's mask = np.zeros(edges.shape, dtype = np.uint8) Next, a mask is created, which at this point is a matrix of 0's. # Go through and find relevant contours and apply to mask for contour in contour_info: # Instead of worrying about all the smaller contours, if the area is smaller than the min, the loop will break if contour[1] > min_area and contour[1] < max_area: # Add contour to mask mask = cv2.fillConvexPoly(mask, contour[0], (255)) For all the contours found, the area of the contours is compared against the minimum and maximum values. If a contours is bigger than the minimum and smaller than the maximum, the contour is added to the mask. If the contour is either smaller than the minimum or bigger than the maximum, it is not considered part of the foreground. # use dilate, erode, and blur to smooth out the mask mask = cv2.dilate(mask, None, iterations=mask_dilate_iter) mask = cv2.erode(mask, None, iterations=mask_erode_iter) mask = cv2.GaussianBlur(mask, (blur, blur), 0) Like before, dilating and eroding the mask are technically optional, but creates a more aesthetically pleasing effect. The same principle applies to the Gaussian blur. # Ensures data types match up mask_stack = mask_stack.astype('float32') / 255.0 frame = frame.astype('float32') / 255.0 These lines convert both the mask and the frame to the required data types they need to be to blend together. It’s a mundane, but important pre-processing step. # Blend the image and the mask masked = (mask_stack * frame) + ((1-mask_stack) * mask_color) masked = (masked * 255).astype('uint8') cv2.imshow("Foreground", masked) Finally, the mask and the frame are blended together so that the background is blacked out. The last line then displays the result. # Use the q button to quit the operation if cv2.waitKey(60) & 0xff == ord('q'): break else: breakcv2.destroyAllWindows()video.release() As some last minute clean up, the first few lines create an exist condition. If the “q” is pressed on the keyboard, it will break the loop and terminate the program. The else connects back to the if-statement made earlier about the camera correctly capturing a frame. If the camera fails, it will also break the loop. At last, once the loop is broken, the window displaying the resulting image is closed and the camera is shut down. If all goes well, an output window should be created displaying real-time background removal. While the algorithm here works well enough for very simple background, it may have more trouble distinguishing more complex backgrounds that are “busy” or cluttered. Overall, however, it works well enough to demonstrate the concept. The below gives the ideal case, where I stand against a plain white wall: The algorithm is easily able to distinguish myself from the wall. There’s some stuttering which may need to be smoothed, but for a first attempt, it does well. Conversely, here’s the result for a worst case scenario where I leaned up against a bookcase: Very busy backgrounds, such as bookcases filled with books and other accessories, will confuse the algorithm and lead to less than perfect results. It struggles to distinguish the foreground from background as large swaths of my arm and face flicker into the background. I did exaggerate this result a little. I put my back against the bookcase, which amplifies the effect. If I stood further in front of the bookcase, the results wouldn’t have been so bad; however, it illustrates the difficulty of background subtraction under less than ideal circumstances. In reality, most attempts will produce something in between the best and worst case scenarios. The intertwined concepts of foreground detection and background subtraction are among some of the most studied aspects of computer vision. While many methods exists, a simple application of edge detection and finding contours within an image provides a good basis. Using OpenCV’s built-in functions, the approach used was able to render background removal in real-time. Under ideal conditions, the algorithm worked near flawlessly, but some additional tweaking may be needed for complex or busy backgrounds.
[ { "code": null, "e": 369, "s": 172, "text": "We live in the era of video calls. Conducted over the internet and using whatever camera that comes with your laptop or computer, we broadcast our lives to our classmates, coworkers, and families." }, { "code": null, "e": 583, "s": 369, "text": "Sometimes, though, we don’t want to broadcast our space. My office, like many others, has a few perennial pieces of clutter. I also have a guitar on the wall behind me, which doesn’t always scream professionalism." }, { "code": null, "e": 865, "s": 583, "text": "As a result, Zoom and other video calling software includes a feature to hide your background, usually behind an image of your choice. While most don’t think of it much, the actual task of determining what determines the foreground and the background in an image is hardly trivial." }, { "code": null, "e": 1146, "s": 865, "text": "Foreground detection is one of the most prominent applications in computer vision. Aside from the example of video calls, foreground detection may be used in finding and reading text in an image, determining where obstacles are in autonomous vehicles, and many other applications." }, { "code": null, "e": 1257, "s": 1146, "text": "As a result, many sophisticated methods have been developed to distinguish the foreground from the background." }, { "code": null, "e": 1536, "s": 1257, "text": "OpenCV provides a couple of “out-of-the-box” solutions; however, without any other context, these are black boxes that don’t present much opportunity to learn. Instead, I’ll use a custom-built algorithm that takes advantage of several OpenCV modules to achieve a similar result." }, { "code": null, "e": 1626, "s": 1536, "text": "The method I’ll demonstrate is foundational on two concepts: edge detection and contours." }, { "code": null, "e": 1927, "s": 1626, "text": "Edge detection, like the name implies, attempts to find the lines of contrast, or edges, in an image. This key first step pre-processes the image to help differentiate any objects. Several methods of edge detection exist, but the Canny method is both immensely popular and comes packaged with OpenCV." }, { "code": null, "e": 2212, "s": 1927, "text": "Once the edges are found, finding contours become much easier and more accurate. In computer vision, contours are simply the continuous boundary lines between areas of contrasting color or intensity. Unlike edge detection, finding contours will find prominent shapes within the image." }, { "code": null, "e": 2362, "s": 2212, "text": "As previously mentioned, the pre-packaged background removers in OpenCV will not be used. Instead, the below flow-chart outlines the method I’ll use:" }, { "code": null, "e": 2599, "s": 2362, "text": "First, we’ll take the image and convert it to black and white. Next, edge detection will be applied and the contours in the image will be found. Any contours that are too either too big or too small to be the foreground will be removed." }, { "code": null, "e": 2913, "s": 2599, "text": "The remaining contours will be considered the foreground. This makes some intuitive sense, as especially small details in a busy background will generate very small contours. By contrast, very large contours which take up most the screen probably aren’t the foreground, but some visual artefact of the background." }, { "code": null, "e": 3009, "s": 2913, "text": "Finally a mask is generated from the remaining contours and is blended into the original image." }, { "code": null, "e": 3038, "s": 3009, "text": "import numpy as npimport cv2" }, { "code": null, "e": 3193, "s": 3038, "text": "Before doing much, two libraries need to be imported. NumPy works to make some the number-crunching more efficient. OpenCV handles the image manipulation." }, { "code": null, "e": 3334, "s": 3193, "text": "# Parametersblur = 21canny_low = 15canny_high = 150min_area = 0.0005max_area = 0.95dilate_iter = 10erode_iter = 10mask_color = (0.0,0.0,0.0)" }, { "code": null, "e": 3535, "s": 3334, "text": "Next, a set of variables are assigned that will influence how the background is removed. Each variable has a unique effect, which may need to be fine tuned based on the subject of the video. In short:" }, { "code": null, "e": 3625, "s": 3535, "text": "blur: affects the “smoothness” of the dividing line between the background and foreground" }, { "code": null, "e": 3696, "s": 3625, "text": "canny_low: the minimum intensity value along which edges will be drawn" }, { "code": null, "e": 3768, "s": 3696, "text": "canny_high: the maximum intensity value along which edges will be drawn" }, { "code": null, "e": 3869, "s": 3768, "text": "min_area: the minimum area a contour in the foreground may occupy. Taken as a value between 0 and 1." }, { "code": null, "e": 3970, "s": 3869, "text": "max_area: the maximum area a contour in the foreground may occupy. Taken as a value between 0 and 1." }, { "code": null, "e": 4049, "s": 3970, "text": "dilate_iter: the number of iterations of dilation will take place on the mask." }, { "code": null, "e": 4126, "s": 4049, "text": "erode_iter: the number of iterations of erosion will take place on the mask." }, { "code": null, "e": 4186, "s": 4126, "text": "mask_color: the color of the background once it is removed." }, { "code": null, "e": 4382, "s": 4186, "text": "Some of these explanations may not make sense, yet, but they’ll be explained further as they appear in the code. In the meantime, feel free to take the values provided as defaults to get started." }, { "code": null, "e": 4444, "s": 4382, "text": "# initialize video from the webcamvideo = cv2.VideoCapture(0)" }, { "code": null, "e": 4570, "s": 4444, "text": "Next, the web camera is initialized, if available. The 0 may be substituted for the path of video file if you don’t have one." }, { "code": null, "e": 4611, "s": 4570, "text": "while True: ret, frame = video.read()" }, { "code": null, "e": 4712, "s": 4611, "text": "An infinite loop is started by reading the frames from the camera. The read method returns 2 values:" }, { "code": null, "e": 4856, "s": 4712, "text": "A boolean to tell if the camera worked properly, stored in the ret variableAn actual frame from the video feed, recorded in the frame variable." }, { "code": null, "e": 4932, "s": 4856, "text": "A boolean to tell if the camera worked properly, stored in the ret variable" }, { "code": null, "e": 5001, "s": 4932, "text": "An actual frame from the video feed, recorded in the frame variable." }, { "code": null, "e": 5219, "s": 5001, "text": " if ret == True: # Convert image to grayscale image_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Apply Canny Edge Dection edges = cv2.Canny(image_gray, canny_low, canny_high)" }, { "code": null, "e": 5392, "s": 5219, "text": "The if-clause allows the code to proceed only if the camera correctly captured video. The frame is rendered into grayscale so the next step, edge detection, may take place." }, { "code": null, "e": 5580, "s": 5392, "text": "Setting the intensity value minimum (the canny_low variable) dictates how sensitive contrast must be to be detected. Adjusting it too low may result in more edges detected than necessary." }, { "code": null, "e": 5830, "s": 5580, "text": "Setting the intensity value maximum (the canny_high variable) dictates that any contrast above its value will be immediately classified as an edge. Adjusting it too high may affect performance, but pushing it too low may miss out on important edges." }, { "code": null, "e": 5908, "s": 5830, "text": " edges = cv2.dilate(edges, None) edges = cv2.erode(edges, None)" }, { "code": null, "e": 6036, "s": 5908, "text": "This step is strictly optional, but dilating and eroding the edges make them more pronounced and returns a nicer final product." }, { "code": null, "e": 6202, "s": 6036, "text": " # get the contours and their areas contour_info = [(c, cv2.contourArea(c),) for c in cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)[1]]" }, { "code": null, "e": 6443, "s": 6202, "text": "There’s a lot going on in this line, but it’s written this way for performance. Essentially, the OpenCV function findContours returns an array of information. Of this information, we only care about the the contours, which are indexed at 1." }, { "code": null, "e": 6543, "s": 6443, "text": "For all the contours found, a tuple of the actual contour itself and its area are stored in a list." }, { "code": null, "e": 6791, "s": 6543, "text": " # Get the area of the image as a comparison image_area = frame.shape[0] * frame.shape[1] # calculate max and min areas in terms of pixels max_area = max_area * image_area min_area = min_area * image_area" }, { "code": null, "e": 6878, "s": 6791, "text": "The area of the image is calculated and then maximum and minimum areas are determined." }, { "code": null, "e": 7173, "s": 6878, "text": "Ideally, this step would be taken outside of the loop, since it hinders performance. Taking an initial frame before streaming or simply knowing your camera’s dimensions beforehand would be more performant. With that said, to keep the code a little simpler for demonstration, this is sufficient." }, { "code": null, "e": 7270, "s": 7173, "text": " # Set up mask with a matrix of 0's mask = np.zeros(edges.shape, dtype = np.uint8)" }, { "code": null, "e": 7335, "s": 7270, "text": "Next, a mask is created, which at this point is a matrix of 0's." }, { "code": null, "e": 7725, "s": 7335, "text": " # Go through and find relevant contours and apply to mask for contour in contour_info: # Instead of worrying about all the smaller contours, if the area is smaller than the min, the loop will break if contour[1] > min_area and contour[1] < max_area: # Add contour to mask mask = cv2.fillConvexPoly(mask, contour[0], (255))" }, { "code": null, "e": 7935, "s": 7725, "text": "For all the contours found, the area of the contours is compared against the minimum and maximum values. If a contours is bigger than the minimum and smaller than the maximum, the contour is added to the mask." }, { "code": null, "e": 8058, "s": 7935, "text": "If the contour is either smaller than the minimum or bigger than the maximum, it is not considered part of the foreground." }, { "code": null, "e": 8303, "s": 8058, "text": " # use dilate, erode, and blur to smooth out the mask mask = cv2.dilate(mask, None, iterations=mask_dilate_iter) mask = cv2.erode(mask, None, iterations=mask_erode_iter) mask = cv2.GaussianBlur(mask, (blur, blur), 0)" }, { "code": null, "e": 8471, "s": 8303, "text": "Like before, dilating and eroding the mask are technically optional, but creates a more aesthetically pleasing effect. The same principle applies to the Gaussian blur." }, { "code": null, "e": 8624, "s": 8471, "text": " # Ensures data types match up mask_stack = mask_stack.astype('float32') / 255.0 frame = frame.astype('float32') / 255.0" }, { "code": null, "e": 8785, "s": 8624, "text": "These lines convert both the mask and the frame to the required data types they need to be to blend together. It’s a mundane, but important pre-processing step." }, { "code": null, "e": 8980, "s": 8785, "text": " # Blend the image and the mask masked = (mask_stack * frame) + ((1-mask_stack) * mask_color) masked = (masked * 255).astype('uint8') cv2.imshow(\"Foreground\", masked)" }, { "code": null, "e": 9112, "s": 8980, "text": "Finally, the mask and the frame are blended together so that the background is blacked out. The last line then displays the result." }, { "code": null, "e": 9284, "s": 9112, "text": " # Use the q button to quit the operation if cv2.waitKey(60) & 0xff == ord('q'): break else: breakcv2.destroyAllWindows()video.release()" }, { "code": null, "e": 9450, "s": 9284, "text": "As some last minute clean up, the first few lines create an exist condition. If the “q” is pressed on the keyboard, it will break the loop and terminate the program." }, { "code": null, "e": 9602, "s": 9450, "text": "The else connects back to the if-statement made earlier about the camera correctly capturing a frame. If the camera fails, it will also break the loop." }, { "code": null, "e": 9717, "s": 9602, "text": "At last, once the loop is broken, the window displaying the resulting image is closed and the camera is shut down." }, { "code": null, "e": 10044, "s": 9717, "text": "If all goes well, an output window should be created displaying real-time background removal. While the algorithm here works well enough for very simple background, it may have more trouble distinguishing more complex backgrounds that are “busy” or cluttered. Overall, however, it works well enough to demonstrate the concept." }, { "code": null, "e": 10118, "s": 10044, "text": "The below gives the ideal case, where I stand against a plain white wall:" }, { "code": null, "e": 10278, "s": 10118, "text": "The algorithm is easily able to distinguish myself from the wall. There’s some stuttering which may need to be smoothed, but for a first attempt, it does well." }, { "code": null, "e": 10372, "s": 10278, "text": "Conversely, here’s the result for a worst case scenario where I leaned up against a bookcase:" }, { "code": null, "e": 10643, "s": 10372, "text": "Very busy backgrounds, such as bookcases filled with books and other accessories, will confuse the algorithm and lead to less than perfect results. It struggles to distinguish the foreground from background as large swaths of my arm and face flicker into the background." }, { "code": null, "e": 10932, "s": 10643, "text": "I did exaggerate this result a little. I put my back against the bookcase, which amplifies the effect. If I stood further in front of the bookcase, the results wouldn’t have been so bad; however, it illustrates the difficulty of background subtraction under less than ideal circumstances." }, { "code": null, "e": 11027, "s": 10932, "text": "In reality, most attempts will produce something in between the best and worst case scenarios." }, { "code": null, "e": 11292, "s": 11027, "text": "The intertwined concepts of foreground detection and background subtraction are among some of the most studied aspects of computer vision. While many methods exists, a simple application of edge detection and finding contours within an image provides a good basis." } ]