title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Java – Lambda Expressions Parameters
24 Jun, 2022 Lambda Expressions are anonymous functions. These functions do not need a name or a class to be used. Lambda expressions are added in Java 8. Lambda expressions basically express instances of functional interfaces An interface with a single abstract method is called a functional interface. One example is java.lang.Runnable. Lambda expressions implement only one abstract function and therefore implement functional interfaces. Predicate interface is an example of a functional interface that has only one abstract method called test(). Illustration: interface Predicate { ...... abstract boolean test(T t) } The above is a functional interface that has one abstract method test receiving only one parameter of type T and returns a boolean value. This method is a generic method that takes a type parameter. This interface can be implemented anywhere in a program using a lambda expression instead of creating classes with multiple functions. For eg, to implement a runnable interface used only for multithreading one needs to implement only a run() method. Then there is the comparable interface which can be implemented using compare() method. Important points: The body of a lambda expression can contain zero, one, or more statements. When there is a single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression. When there is more than one statement, then these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned. These are for single–line lambda expressions having void return type. Type 1: No Parameter. Syntax: () -> System.out.println("Hello"); It takes interface of the following form: interface Test1 { void print() } Type 2: Single Parameter. Syntax: (p) -> System.out.println(p); It is not mandatory to use parentheses if the type of that variable can be inferred from the context It takes interface of the following form: interface Test2 { void print(Integer p) } The type and return type of the lambdas are automatically inferred. Type 3: Multi parameters (p1, p2) -> System.out.println(p1 + " " + p2); It is not mandatory to use parentheses if the type of that variable can be inferred from the context It takes interface of the following form: interface Test3 { void print(Integer p1, Integer p2) } The type and return type of the lambdas are automatically inferred. Now, we are done with discussing out the theoretical concept, now let us come up with the implementation part. So here primarily we will be discussing out the codes for the above three types as discussed above: Note: forEach() method is of Iterable interface that is used to iterate through a collection. Here it takes an argument of Consumer type interface. This is a functional interface having only one abstract method called accept(). Since it is a functional interface, a lambda expression can be passed. Hence, if we do conclude out the above Example 1: Lambda expression with no parameters Java // Java code to illustrate lambda expression// without parameters // functional interface// without parametersinterface Test1 { void print();} class GfG { // functional interface parameter is passed static void fun(Test1 t) { t.print(); } public static void main(String[] args) { // lambda expression is passed // without parameter to functional interface t fun(() -> System.out.println("Hello")); }} Hello Example 2: Type 2 Lambda expression with a single parameter Java // Java code to illustrate lambda expression// with single parameter // functional interface// with one parameter of Integer typeinterface Test2 { // The void type and the Integer type // is automatically inferred from here // and assigned to the lambda expression void print(Integer p);} class GfG { // takes lambda expression and a variable of // Integer type as arguments static void fun(Test2 t, Integer p) { // calls the print function t.print(p); } public static void main(String[] args) { // lambda expression is passed // with a single parameter // lambda expression is mapped to the // single argument abstract function in the // functional interface Test2 fun(p -> System.out.println(p), 10); }} 10 Example 3: Type 3 Lambda expression with multi parameters Java // Java code to illustrate lambda expression// with multi parameters // functional interface Test3// with 2 parameter of Integer typeinterface Test3 { // The void type and the Integer type // is automatically inferred from here // and assigned to the lambda expression void print(Integer p1, Integer p2);} class GfG { // takes parameter of Test3 type followed // by 2 integer parameters p1 and p2 static void fun(Test3 t, Integer p1, Integer p2) { // calls the print function t.print(p1, p2); } public static void main(String[] args) { // lambda expression is passed // with two parameters // lambda expression is mapped to the // double argument abstract function in the // functional interface Test3 fun((p1, p2) -> System.out.println(p1 + " " + p2), 10, 20); }} 10 20 Example 4:Lambda expression with two parameters Java // Demonstrate a lambda expression that takes two parameters interface NumericTest2{ boolean test(int n, int d);} class GFG{public static void main(String args[]){ // The labda expression here determines if one number is the factor of another NumericTest2 isFactor= (n,d) -> (n%d)==0; if(isFactor.test(10,2)) System.out.println("2 is the factor of 10"); if(!isFactor.test(10,3)) System.out.println("3 is not a factor of 10"); }} 2 is the factor of 10 3 is not a factor of 10 rkbhola5 singhankitasingh066 java-lambda Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Jun, 2022" }, { "code": null, "e": 379, "s": 53, "text": "Lambda Expressions are anonymous functions. These functions do not need a name or a class to be used. Lambda expressions are added in Java 8. Lambda expressions basically express instances of functional interfaces An interface with a single abstract method is called a functional interface. One example is java.lang.Runnable." }, { "code": null, "e": 591, "s": 379, "text": "Lambda expressions implement only one abstract function and therefore implement functional interfaces. Predicate interface is an example of a functional interface that has only one abstract method called test()." }, { "code": null, "e": 605, "s": 591, "text": "Illustration:" }, { "code": null, "e": 671, "s": 605, "text": "interface Predicate\n{\n ......\n abstract boolean test(T t)\n}" }, { "code": null, "e": 1208, "s": 671, "text": "The above is a functional interface that has one abstract method test receiving only one parameter of type T and returns a boolean value. This method is a generic method that takes a type parameter. This interface can be implemented anywhere in a program using a lambda expression instead of creating classes with multiple functions. For eg, to implement a runnable interface used only for multithreading one needs to implement only a run() method. Then there is the comparable interface which can be implemented using compare() method." }, { "code": null, "e": 1226, "s": 1208, "text": "Important points:" }, { "code": null, "e": 1301, "s": 1226, "text": "The body of a lambda expression can contain zero, one, or more statements." }, { "code": null, "e": 1457, "s": 1301, "text": "When there is a single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression." }, { "code": null, "e": 1704, "s": 1457, "text": "When there is more than one statement, then these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned." }, { "code": null, "e": 1774, "s": 1704, "text": "These are for single–line lambda expressions having void return type." }, { "code": null, "e": 1796, "s": 1774, "text": "Type 1: No Parameter." }, { "code": null, "e": 1804, "s": 1796, "text": "Syntax:" }, { "code": null, "e": 1839, "s": 1804, "text": "() -> System.out.println(\"Hello\");" }, { "code": null, "e": 1881, "s": 1839, "text": "It takes interface of the following form:" }, { "code": null, "e": 1918, "s": 1881, "text": "interface Test1\n{\n void print()\n}" }, { "code": null, "e": 1944, "s": 1918, "text": "Type 2: Single Parameter." }, { "code": null, "e": 1952, "s": 1944, "text": "Syntax:" }, { "code": null, "e": 1982, "s": 1952, "text": "(p) -> System.out.println(p);" }, { "code": null, "e": 2083, "s": 1982, "text": "It is not mandatory to use parentheses if the type of that variable can be inferred from the context" }, { "code": null, "e": 2125, "s": 2083, "text": "It takes interface of the following form:" }, { "code": null, "e": 2171, "s": 2125, "text": "interface Test2\n{\n void print(Integer p)\n}" }, { "code": null, "e": 2239, "s": 2171, "text": "The type and return type of the lambdas are automatically inferred." }, { "code": null, "e": 2264, "s": 2239, "text": "Type 3: Multi parameters" }, { "code": null, "e": 2311, "s": 2264, "text": "(p1, p2) -> System.out.println(p1 + \" \" + p2);" }, { "code": null, "e": 2412, "s": 2311, "text": "It is not mandatory to use parentheses if the type of that variable can be inferred from the context" }, { "code": null, "e": 2454, "s": 2412, "text": "It takes interface of the following form:" }, { "code": null, "e": 2513, "s": 2454, "text": "interface Test3\n{\n void print(Integer p1, Integer p2)\n}" }, { "code": null, "e": 2581, "s": 2513, "text": "The type and return type of the lambdas are automatically inferred." }, { "code": null, "e": 2792, "s": 2581, "text": "Now, we are done with discussing out the theoretical concept, now let us come up with the implementation part. So here primarily we will be discussing out the codes for the above three types as discussed above:" }, { "code": null, "e": 3091, "s": 2792, "text": "Note: forEach() method is of Iterable interface that is used to iterate through a collection. Here it takes an argument of Consumer type interface. This is a functional interface having only one abstract method called accept(). Since it is a functional interface, a lambda expression can be passed." }, { "code": null, "e": 3131, "s": 3091, "text": "Hence, if we do conclude out the above " }, { "code": null, "e": 3179, "s": 3131, "text": "Example 1: Lambda expression with no parameters" }, { "code": null, "e": 3184, "s": 3179, "text": "Java" }, { "code": "// Java code to illustrate lambda expression// without parameters // functional interface// without parametersinterface Test1 { void print();} class GfG { // functional interface parameter is passed static void fun(Test1 t) { t.print(); } public static void main(String[] args) { // lambda expression is passed // without parameter to functional interface t fun(() -> System.out.println(\"Hello\")); }}", "e": 3624, "s": 3184, "text": null }, { "code": null, "e": 3630, "s": 3624, "text": "Hello" }, { "code": null, "e": 3690, "s": 3630, "text": "Example 2: Type 2 Lambda expression with a single parameter" }, { "code": null, "e": 3695, "s": 3690, "text": "Java" }, { "code": "// Java code to illustrate lambda expression// with single parameter // functional interface// with one parameter of Integer typeinterface Test2 { // The void type and the Integer type // is automatically inferred from here // and assigned to the lambda expression void print(Integer p);} class GfG { // takes lambda expression and a variable of // Integer type as arguments static void fun(Test2 t, Integer p) { // calls the print function t.print(p); } public static void main(String[] args) { // lambda expression is passed // with a single parameter // lambda expression is mapped to the // single argument abstract function in the // functional interface Test2 fun(p -> System.out.println(p), 10); }}", "e": 4493, "s": 3695, "text": null }, { "code": null, "e": 4496, "s": 4493, "text": "10" }, { "code": null, "e": 4554, "s": 4496, "text": "Example 3: Type 3 Lambda expression with multi parameters" }, { "code": null, "e": 4559, "s": 4554, "text": "Java" }, { "code": "// Java code to illustrate lambda expression// with multi parameters // functional interface Test3// with 2 parameter of Integer typeinterface Test3 { // The void type and the Integer type // is automatically inferred from here // and assigned to the lambda expression void print(Integer p1, Integer p2);} class GfG { // takes parameter of Test3 type followed // by 2 integer parameters p1 and p2 static void fun(Test3 t, Integer p1, Integer p2) { // calls the print function t.print(p1, p2); } public static void main(String[] args) { // lambda expression is passed // with two parameters // lambda expression is mapped to the // double argument abstract function in the // functional interface Test3 fun((p1, p2) -> System.out.println(p1 + \" \" + p2), 10, 20); }}", "e": 5442, "s": 4559, "text": null }, { "code": null, "e": 5448, "s": 5442, "text": "10 20" }, { "code": null, "e": 5496, "s": 5448, "text": "Example 4:Lambda expression with two parameters" }, { "code": null, "e": 5501, "s": 5496, "text": "Java" }, { "code": "// Demonstrate a lambda expression that takes two parameters interface NumericTest2{ boolean test(int n, int d);} class GFG{public static void main(String args[]){ // The labda expression here determines if one number is the factor of another NumericTest2 isFactor= (n,d) -> (n%d)==0; if(isFactor.test(10,2)) System.out.println(\"2 is the factor of 10\"); if(!isFactor.test(10,3)) System.out.println(\"3 is not a factor of 10\"); }}", "e": 5948, "s": 5501, "text": null }, { "code": null, "e": 5994, "s": 5948, "text": "2 is the factor of 10\n3 is not a factor of 10" }, { "code": null, "e": 6003, "s": 5994, "text": "rkbhola5" }, { "code": null, "e": 6023, "s": 6003, "text": "singhankitasingh066" }, { "code": null, "e": 6035, "s": 6023, "text": "java-lambda" }, { "code": null, "e": 6040, "s": 6035, "text": "Java" }, { "code": null, "e": 6045, "s": 6040, "text": "Java" } ]
Python datetime module
17 Nov, 2021 In Python, date and time are not a data type of their own, but a module named datetime can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. Python Datetime module supplies classes to work with date and time. These classes provide a number of functions to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps. The DateTime module is categorized into 6 main classes – date – An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Its attributes are year, month and day. time – An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds. Its attributes are hour, minute, second, microsecond, and tzinfo. datetime – Its a combination of date and time along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo. timedelta – A duration expressing the difference between two date, time, or datetime instances to microsecond resolution. tzinfo – It provides time zone information objects. timezone – A class that implements the tzinfo abstract base class as a fixed offset from the UTC (New in version 3.2). The date class is used to instantiate date objects in Python. When an object of this class is instantiated, it represents a date in the format YYYY-MM-DD. Constructor of this class needs three mandatory arguments year, month and date. Constructor syntax: class datetime.date(year, month, day) The arguments must be in the following range – MINYEAR <= year <= MAXYEAR 1 <= month <= 12 1 <= day <= number of days in the given month and year Note – If the argument is not an integer it will raise a TypeError and if it is outside the range a ValueError will be raised. Python3 # Python program to# demonstrate date class # import the date classfrom datetime import date # initializing constructor# and passing arguments in the# format year, month, datemy_date = date(1996, 12, 11) print("Date passed as argument is", my_date) # Uncommenting my_date = date(1996, 12, 39)# will raise an ValueError as it is# outside range # uncommenting my_date = date('1996', 12, 11)# will raise a TypeError as a string is# passed instead of integer Output: Date passed as argument is 1996-12-11 Traceback (most recent call last): File "/home/ccabfb570d9bd1dcd11dc4fe55fd6ba2.py", line 14, in my_date = date(1996, 12, 39) ValueError: day is out of range for month Traceback (most recent call last): File "/home/53b974e10651f1853eee3c004b48c481.py", line 18, in my_date = date('1996', 12, 11) TypeError: an integer is required (got type str) To return the current local date today() function of date class is used. today() function comes with several attributes (year, month and day). These can be printed individually. Python3 # Python program to# print current date from datetime import date # calling the today# function of date classtoday = date.today() print("Today's date is", today) Today's date is 2021-08-19 We can get the year, month, and date attributes from the date object using the year, month and date attribute of the date class. Python3 from datetime import date # date object of today's datetoday = date.today() print("Current year:", today.year)print("Current month:", today.month)print("Current day:", today.day) Current year: 2021 Current month: 8 Current day: 19 We can create date objects from timestamps y=using the fromtimestamp() method. The timestamp is the number of seconds from 1st January 1970 at UTC to a particular date. Python3 from datetime import datetime # Getting Datetime from timestampdate_time = datetime.fromtimestamp(1887639468)print("Datetime from timestamp:", date_time) Datetime from timestamp: 2029-10-25 16:17:48 We can convert date object to a string representation using two functions isoformat() and strftime(). Python3 from datetime import date # calling the today# function of date classtoday = date.today() # Converting the date to the stringStr = date.isoformat(today)print("String Representation", Str)print(type(Str)) String Representation 2021-08-19 <class 'str'> The time class creates the time object which represents local time, independent of any day. Constructor Syntax: class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) All the arguments are optional. tzinfo can be None otherwise all the attributes must be integer in the following range – 0 <= hour < 24 0 <= minute < 60 0 <= second < 60 0 <= microsecond < 1000000 fold in [0, 1] Python3 # Python program to# demonstrate time class from datetime import time # calling the constructormy_time = time(13, 24, 56) print("Entered time", my_time) # calling constructor with 1# argumentmy_time = time(minute=12)print("\nTime with one argument", my_time) # Calling constructor with# 0 argumentmy_time = time()print("\nTime without argument", my_time) # Uncommenting time(hour = 26)# will rase an ValueError as# it is out of range # uncommenting time(hour ='23')# will raise TypeError as# string is passed instead of int Output: Entered time 13:24:56 Time with one argument 00:12:00 Time without argument 00:00:00 Traceback (most recent call last): File "/home/95ff83138a1b3e67731e57ec6dddef25.py", line 21, in print(time(hour=26)) ValueError: hour must be in 0..23 Traceback (most recent call last): File "/home/fcee9ba5615b0b74fc3ba39ec9a789fd.py", line 21, in print(time(hour='23')) TypeError: an integer is required (got type str) After creating a time object, its attributes can also be printed separately. Python3 from datetime import time Time = time(11, 34, 56) print("hour =", Time.hour)print("minute =", Time.minute)print("second =", Time.second)print("microsecond =", Time.microsecond) Output: hour = 11 minute = 34 second = 56 microsecond = 0 We can convert time object to string using the isoformat() method. Python3 from datetime import time # Creating Time objectTime = time(12,24,36,1212) # Converting Time object to stringStr = Time.isoformat()print("String Representation:", Str)print(type(Str)) String Representation: 12:24:36.001212 <class 'str'> The DateTime class contains information on both date and time. Like a date object, datetime assumes the current Gregorian calendar extended in both directions; like a time object, datetime assumes there are exactly 3600*24 seconds in every day. Constructor Syntax: class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) The year, month and day arguments are mandatory. tzinfo can be None, rest all the attributes must be an integer in the following range – MINYEAR <= year <= MAXYEAR 1 <= month <= 12 1 <= day <= number of days in the given month and year 0 <= hour < 24 0 <= minute < 60 0 <= second < 60 0 <= microsecond < 1000000 fold in [0, 1] Note – Passing an argument other than integer will raise a TypeError and passing arguments outside the range will raise ValueError. Python3 # Python program to# demonstrate datetime object from datetime import datetime # Initializing constructora = datetime(1999, 12, 12)print(a) # Initializing constructor# with time parameters as wella = datetime(1999, 12, 12, 12, 12, 12, 342380)print(a) Output: 1999-12-12 00:00:00 1999-12-12 12:12:12.342380 After creating a DateTime object, its attributes can also be printed separately. Python3 from datetime import datetime a = datetime(1999, 12, 12, 12, 12, 12) print("year =", a.year)print("month =", a.month)print("hour =", a.hour)print("minute =", a.minute)print("timestamp =", a.timestamp()) Output: year = 1999 month = 12 hour = 12 minute = 12 timestamp = 945000732.0 You can print the current date and time using the Datetime.now() function. now() function returns the current local date and time. Python3 from datetime import datetime # Calling now() functiontoday = datetime.now() print("Current date and time is", today) Output: Current date and time is 2019-10-25 11:12:11.289834 We can convert Datetime to string in Python using the datetime.strftime and datetime.isoformat methods. Python3 from datetime import datetime as dt # Getting current date and timenow = dt.now() string = dt.isoformat(now)print(string)print(type(string)) 2021-08-19T18:13:25.346259 <class 'str'> Python timedelta class is used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations. Constructor syntax: class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)Returns : Date Python3 # Timedelta function demonstration from datetime import datetime, timedelta # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint("initial_date", str(ini_time_for_now)) # Calculating future dates# for two yearsfuture_date_after_2yrs = ini_time_for_now + timedelta(days=730) future_date_after_2days = ini_time_for_now + timedelta(days=2) # printing calculated future_datesprint('future_date_after_2yrs:', str(future_date_after_2yrs))print('future_date_after_2days:', str(future_date_after_2days)) Output: initial_date 2019-10-25 12:01:01.227848 future_date_after_2yrs: 2021-10-24 12:01:01.227848 future_date_after_2days: 2019-10-27 12:01:01.227848 Date and Time difference can also be found using this class. Python3 # Timedelta function demonstrationfrom datetime import datetime, timedelta # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint("initial_date", str(ini_time_for_now)) # Some another datetimenew_final_time = ini_time_for_now + \ timedelta(days=2) # printing new final_dateprint("new_final_time", str(new_final_time)) # printing calculated past_datesprint('Time difference:', str(new_final_time - ini_time_for_now)) Output: initial_date 2019-10-25 12:02:32.799814 new_final_time 2019-10-27 12:02:32.799814 Time difference: 2 days, 0:00:00 Formatting Datetime can be very necessary as the date representation may differe from place to place. Like in some countries it can be yyyy-mm-dd and in other country it can be dd-mm-yyyy. To format Python Datetime strptime and strftime functions can be used. strftime() method converts the given date, time or datetime object to the a string representation of the given format. Python3 # Python program to demonstrate# strftime() function from datetime import datetime as dt # Getting current date and timenow = dt.now()print("Without formatting", now) # Example 1s = now.strftime("%A %m %-Y")print('\nExample 1:', s) # Example 2s = now.strftime("%a %-m %y")print('\nExample 2:', s) # Example 3s = now.strftime("%-I %p %S")print('\nExample 3:', s) # Example 4s = now.strftime("%H:%M:%S")print('\nExample 4:', s) Without formatting 2021-08-19 18:16:25.881661 Example 1: Thursday 08 2021 Example 2: Thu 8 21 Example 3: 6 PM 25 Example 4: 18:16:25 Note: For more information, refer to strftime() method. strptime() creates a datetime object from the given string. Python3 # import datetime module from datetimefrom datetime import datetime # consider the time stamps from a list in string# format DD/MM/YY H:M:S.microstime_data = ["25/05/99 02:35:8.023", "26/05/99 12:45:0.003", "27/05/99 07:35:5.523", "28/05/99 05:15:55.523"] # format the string in the given format : day/month/year # hours/minutes/seconds-micro secondsformat_data = "%d/%m/%y %H:%M:%S.%f" # Using strptime with datetime we will format string# into datetimefor i in time_data: print(datetime.strptime(i, format_data)) 1999-05-25 02:35:08.023000 1999-05-26 12:45:00.003000 1999-05-27 07:35:05.523000 1999-05-28 05:15:55.523000 Timezones in DateTime can be used in the case where one might want to display time according to the timezone of a specific region. This can be done using the pytz module of Python. This module serves the date-time conversion functionalities and helps users serving international client bases. Python3 from datetime import datetimefrom pytz import timezone format = "%Y-%m-%d %H:%M:%S %Z%z" # Current time in UTCnow_utc = datetime.now(timezone('UTC'))print(now_utc.strftime(format)) timezones = ['Asia/Kolkata', 'Europe/Kiev', 'America/New_York'] for tzone in timezones: # Convert to Asia/Kolkata time zone now_asia = now_utc.astimezone(timezone(tzone)) print(now_asia.strftime(format)) 2021-08-19 18:27:28 UTC+0000 2021-08-19 23:57:28 IST+0530 2021-08-19 21:27:28 EEST+0300 2021-08-19 14:27:28 EDT-0400 arorakashish0911 simranarora5sos nikhilaggarwal3 sweetyty kalrap615 python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Nov, 2021" }, { "code": null, "e": 291, "s": 54, "text": "In Python, date and time are not a data type of their own, but a module named datetime can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. " }, { "code": null, "e": 590, "s": 291, "text": "Python Datetime module supplies classes to work with date and time. These classes provide a number of functions to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps. " }, { "code": null, "e": 648, "s": 590, "text": "The DateTime module is categorized into 6 main classes – " }, { "code": null, "e": 803, "s": 648, "text": "date – An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Its attributes are year, month and day." }, { "code": null, "e": 984, "s": 803, "text": "time – An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds. Its attributes are hour, minute, second, microsecond, and tzinfo." }, { "code": null, "e": 1121, "s": 984, "text": "datetime – Its a combination of date and time along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo." }, { "code": null, "e": 1243, "s": 1121, "text": "timedelta – A duration expressing the difference between two date, time, or datetime instances to microsecond resolution." }, { "code": null, "e": 1295, "s": 1243, "text": "tzinfo – It provides time zone information objects." }, { "code": null, "e": 1414, "s": 1295, "text": "timezone – A class that implements the tzinfo abstract base class as a fixed offset from the UTC (New in version 3.2)." }, { "code": null, "e": 1649, "s": 1414, "text": "The date class is used to instantiate date objects in Python. When an object of this class is instantiated, it represents a date in the format YYYY-MM-DD. Constructor of this class needs three mandatory arguments year, month and date." }, { "code": null, "e": 1671, "s": 1649, "text": "Constructor syntax: " }, { "code": null, "e": 1709, "s": 1671, "text": "class datetime.date(year, month, day)" }, { "code": null, "e": 1758, "s": 1709, "text": "The arguments must be in the following range – " }, { "code": null, "e": 1785, "s": 1758, "text": "MINYEAR <= year <= MAXYEAR" }, { "code": null, "e": 1802, "s": 1785, "text": "1 <= month <= 12" }, { "code": null, "e": 1857, "s": 1802, "text": "1 <= day <= number of days in the given month and year" }, { "code": null, "e": 1985, "s": 1857, "text": "Note – If the argument is not an integer it will raise a TypeError and if it is outside the range a ValueError will be raised. " }, { "code": null, "e": 1993, "s": 1985, "text": "Python3" }, { "code": "# Python program to# demonstrate date class # import the date classfrom datetime import date # initializing constructor# and passing arguments in the# format year, month, datemy_date = date(1996, 12, 11) print(\"Date passed as argument is\", my_date) # Uncommenting my_date = date(1996, 12, 39)# will raise an ValueError as it is# outside range # uncommenting my_date = date('1996', 12, 11)# will raise a TypeError as a string is# passed instead of integer", "e": 2448, "s": 1993, "text": null }, { "code": null, "e": 2457, "s": 2448, "text": "Output: " }, { "code": null, "e": 2495, "s": 2457, "text": "Date passed as argument is 1996-12-11" }, { "code": null, "e": 2856, "s": 2495, "text": "Traceback (most recent call last):\n File \"/home/ccabfb570d9bd1dcd11dc4fe55fd6ba2.py\", line 14, in \n my_date = date(1996, 12, 39)\nValueError: day is out of range for month\n\nTraceback (most recent call last):\n File \"/home/53b974e10651f1853eee3c004b48c481.py\", line 18, in \n my_date = date('1996', 12, 11)\nTypeError: an integer is required (got type str) " }, { "code": null, "e": 3035, "s": 2856, "text": "To return the current local date today() function of date class is used. today() function comes with several attributes (year, month and day). These can be printed individually. " }, { "code": null, "e": 3043, "s": 3035, "text": "Python3" }, { "code": "# Python program to# print current date from datetime import date # calling the today# function of date classtoday = date.today() print(\"Today's date is\", today)", "e": 3205, "s": 3043, "text": null }, { "code": null, "e": 3232, "s": 3205, "text": "Today's date is 2021-08-19" }, { "code": null, "e": 3361, "s": 3232, "text": "We can get the year, month, and date attributes from the date object using the year, month and date attribute of the date class." }, { "code": null, "e": 3369, "s": 3361, "text": "Python3" }, { "code": "from datetime import date # date object of today's datetoday = date.today() print(\"Current year:\", today.year)print(\"Current month:\", today.month)print(\"Current day:\", today.day)", "e": 3548, "s": 3369, "text": null }, { "code": null, "e": 3600, "s": 3548, "text": "Current year: 2021\nCurrent month: 8\nCurrent day: 19" }, { "code": null, "e": 3769, "s": 3600, "text": "We can create date objects from timestamps y=using the fromtimestamp() method. The timestamp is the number of seconds from 1st January 1970 at UTC to a particular date." }, { "code": null, "e": 3777, "s": 3769, "text": "Python3" }, { "code": "from datetime import datetime # Getting Datetime from timestampdate_time = datetime.fromtimestamp(1887639468)print(\"Datetime from timestamp:\", date_time)", "e": 3931, "s": 3777, "text": null }, { "code": null, "e": 3976, "s": 3931, "text": "Datetime from timestamp: 2029-10-25 16:17:48" }, { "code": null, "e": 4078, "s": 3976, "text": "We can convert date object to a string representation using two functions isoformat() and strftime()." }, { "code": null, "e": 4086, "s": 4078, "text": "Python3" }, { "code": "from datetime import date # calling the today# function of date classtoday = date.today() # Converting the date to the stringStr = date.isoformat(today)print(\"String Representation\", Str)print(type(Str))", "e": 4294, "s": 4086, "text": null }, { "code": null, "e": 4341, "s": 4294, "text": "String Representation 2021-08-19\n<class 'str'>" }, { "code": null, "e": 4434, "s": 4341, "text": "The time class creates the time object which represents local time, independent of any day. " }, { "code": null, "e": 4455, "s": 4434, "text": "Constructor Syntax: " }, { "code": null, "e": 4542, "s": 4455, "text": "class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)" }, { "code": null, "e": 4664, "s": 4542, "text": "All the arguments are optional. tzinfo can be None otherwise all the attributes must be integer in the following range – " }, { "code": null, "e": 4679, "s": 4664, "text": "0 <= hour < 24" }, { "code": null, "e": 4696, "s": 4679, "text": "0 <= minute < 60" }, { "code": null, "e": 4713, "s": 4696, "text": "0 <= second < 60" }, { "code": null, "e": 4740, "s": 4713, "text": "0 <= microsecond < 1000000" }, { "code": null, "e": 4755, "s": 4740, "text": "fold in [0, 1]" }, { "code": null, "e": 4763, "s": 4755, "text": "Python3" }, { "code": "# Python program to# demonstrate time class from datetime import time # calling the constructormy_time = time(13, 24, 56) print(\"Entered time\", my_time) # calling constructor with 1# argumentmy_time = time(minute=12)print(\"\\nTime with one argument\", my_time) # Calling constructor with# 0 argumentmy_time = time()print(\"\\nTime without argument\", my_time) # Uncommenting time(hour = 26)# will rase an ValueError as# it is out of range # uncommenting time(hour ='23')# will raise TypeError as# string is passed instead of int", "e": 5287, "s": 4763, "text": null }, { "code": null, "e": 5296, "s": 5287, "text": "Output: " }, { "code": null, "e": 5383, "s": 5296, "text": "Entered time 13:24:56\n\nTime with one argument 00:12:00\n\nTime without argument 00:00:00" }, { "code": null, "e": 5719, "s": 5383, "text": "Traceback (most recent call last):\n File \"/home/95ff83138a1b3e67731e57ec6dddef25.py\", line 21, in \n print(time(hour=26))\nValueError: hour must be in 0..23\n\nTraceback (most recent call last):\n File \"/home/fcee9ba5615b0b74fc3ba39ec9a789fd.py\", line 21, in \n print(time(hour='23'))\nTypeError: an integer is required (got type str)" }, { "code": null, "e": 5797, "s": 5719, "text": "After creating a time object, its attributes can also be printed separately. " }, { "code": null, "e": 5805, "s": 5797, "text": "Python3" }, { "code": "from datetime import time Time = time(11, 34, 56) print(\"hour =\", Time.hour)print(\"minute =\", Time.minute)print(\"second =\", Time.second)print(\"microsecond =\", Time.microsecond)", "e": 5982, "s": 5805, "text": null }, { "code": null, "e": 5991, "s": 5982, "text": "Output: " }, { "code": null, "e": 6041, "s": 5991, "text": "hour = 11\nminute = 34\nsecond = 56\nmicrosecond = 0" }, { "code": null, "e": 6108, "s": 6041, "text": "We can convert time object to string using the isoformat() method." }, { "code": null, "e": 6116, "s": 6108, "text": "Python3" }, { "code": "from datetime import time # Creating Time objectTime = time(12,24,36,1212) # Converting Time object to stringStr = Time.isoformat()print(\"String Representation:\", Str)print(type(Str))", "e": 6300, "s": 6116, "text": null }, { "code": null, "e": 6353, "s": 6300, "text": "String Representation: 12:24:36.001212\n<class 'str'>" }, { "code": null, "e": 6598, "s": 6353, "text": "The DateTime class contains information on both date and time. Like a date object, datetime assumes the current Gregorian calendar extended in both directions; like a time object, datetime assumes there are exactly 3600*24 seconds in every day." }, { "code": null, "e": 6619, "s": 6598, "text": "Constructor Syntax: " }, { "code": null, "e": 6730, "s": 6619, "text": "class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) " }, { "code": null, "e": 6869, "s": 6730, "text": "The year, month and day arguments are mandatory. tzinfo can be None, rest all the attributes must be an integer in the following range – " }, { "code": null, "e": 6896, "s": 6869, "text": "MINYEAR <= year <= MAXYEAR" }, { "code": null, "e": 6913, "s": 6896, "text": "1 <= month <= 12" }, { "code": null, "e": 6968, "s": 6913, "text": "1 <= day <= number of days in the given month and year" }, { "code": null, "e": 6983, "s": 6968, "text": "0 <= hour < 24" }, { "code": null, "e": 7000, "s": 6983, "text": "0 <= minute < 60" }, { "code": null, "e": 7017, "s": 7000, "text": "0 <= second < 60" }, { "code": null, "e": 7044, "s": 7017, "text": "0 <= microsecond < 1000000" }, { "code": null, "e": 7059, "s": 7044, "text": "fold in [0, 1]" }, { "code": null, "e": 7191, "s": 7059, "text": "Note – Passing an argument other than integer will raise a TypeError and passing arguments outside the range will raise ValueError." }, { "code": null, "e": 7199, "s": 7191, "text": "Python3" }, { "code": "# Python program to# demonstrate datetime object from datetime import datetime # Initializing constructora = datetime(1999, 12, 12)print(a) # Initializing constructor# with time parameters as wella = datetime(1999, 12, 12, 12, 12, 12, 342380)print(a)", "e": 7450, "s": 7199, "text": null }, { "code": null, "e": 7459, "s": 7450, "text": "Output: " }, { "code": null, "e": 7506, "s": 7459, "text": "1999-12-12 00:00:00\n1999-12-12 12:12:12.342380" }, { "code": null, "e": 7587, "s": 7506, "text": "After creating a DateTime object, its attributes can also be printed separately." }, { "code": null, "e": 7595, "s": 7587, "text": "Python3" }, { "code": "from datetime import datetime a = datetime(1999, 12, 12, 12, 12, 12) print(\"year =\", a.year)print(\"month =\", a.month)print(\"hour =\", a.hour)print(\"minute =\", a.minute)print(\"timestamp =\", a.timestamp())", "e": 7798, "s": 7595, "text": null }, { "code": null, "e": 7807, "s": 7798, "text": "Output: " }, { "code": null, "e": 7876, "s": 7807, "text": "year = 1999\nmonth = 12\nhour = 12\nminute = 12\ntimestamp = 945000732.0" }, { "code": null, "e": 8008, "s": 7876, "text": "You can print the current date and time using the Datetime.now() function. now() function returns the current local date and time. " }, { "code": null, "e": 8016, "s": 8008, "text": "Python3" }, { "code": "from datetime import datetime # Calling now() functiontoday = datetime.now() print(\"Current date and time is\", today)", "e": 8134, "s": 8016, "text": null }, { "code": null, "e": 8143, "s": 8134, "text": "Output: " }, { "code": null, "e": 8195, "s": 8143, "text": "Current date and time is 2019-10-25 11:12:11.289834" }, { "code": null, "e": 8300, "s": 8195, "text": "We can convert Datetime to string in Python using the datetime.strftime and datetime.isoformat methods. " }, { "code": null, "e": 8308, "s": 8300, "text": "Python3" }, { "code": "from datetime import datetime as dt # Getting current date and timenow = dt.now() string = dt.isoformat(now)print(string)print(type(string))", "e": 8449, "s": 8308, "text": null }, { "code": null, "e": 8490, "s": 8449, "text": "2021-08-19T18:13:25.346259\n<class 'str'>" }, { "code": null, "e": 8674, "s": 8490, "text": "Python timedelta class is used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations." }, { "code": null, "e": 8696, "s": 8674, "text": "Constructor syntax: " }, { "code": null, "e": 8816, "s": 8696, "text": "class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)Returns : Date " }, { "code": null, "e": 8824, "s": 8816, "text": "Python3" }, { "code": "# Timedelta function demonstration from datetime import datetime, timedelta # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint(\"initial_date\", str(ini_time_for_now)) # Calculating future dates# for two yearsfuture_date_after_2yrs = ini_time_for_now + timedelta(days=730) future_date_after_2days = ini_time_for_now + timedelta(days=2) # printing calculated future_datesprint('future_date_after_2yrs:', str(future_date_after_2yrs))print('future_date_after_2days:', str(future_date_after_2days))", "e": 9350, "s": 8824, "text": null }, { "code": null, "e": 9359, "s": 9350, "text": "Output: " }, { "code": null, "e": 9502, "s": 9359, "text": "initial_date 2019-10-25 12:01:01.227848\nfuture_date_after_2yrs: 2021-10-24 12:01:01.227848\nfuture_date_after_2days: 2019-10-27 12:01:01.227848" }, { "code": null, "e": 9563, "s": 9502, "text": "Date and Time difference can also be found using this class." }, { "code": null, "e": 9571, "s": 9563, "text": "Python3" }, { "code": "# Timedelta function demonstrationfrom datetime import datetime, timedelta # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint(\"initial_date\", str(ini_time_for_now)) # Some another datetimenew_final_time = ini_time_for_now + \\ timedelta(days=2) # printing new final_dateprint(\"new_final_time\", str(new_final_time)) # printing calculated past_datesprint('Time difference:', str(new_final_time - ini_time_for_now))", "e": 10048, "s": 9571, "text": null }, { "code": null, "e": 10057, "s": 10048, "text": "Output: " }, { "code": null, "e": 10172, "s": 10057, "text": "initial_date 2019-10-25 12:02:32.799814\nnew_final_time 2019-10-27 12:02:32.799814\nTime difference: 2 days, 0:00:00" }, { "code": null, "e": 10432, "s": 10172, "text": "Formatting Datetime can be very necessary as the date representation may differe from place to place. Like in some countries it can be yyyy-mm-dd and in other country it can be dd-mm-yyyy. To format Python Datetime strptime and strftime functions can be used." }, { "code": null, "e": 10551, "s": 10432, "text": "strftime() method converts the given date, time or datetime object to the a string representation of the given format." }, { "code": null, "e": 10559, "s": 10551, "text": "Python3" }, { "code": "# Python program to demonstrate# strftime() function from datetime import datetime as dt # Getting current date and timenow = dt.now()print(\"Without formatting\", now) # Example 1s = now.strftime(\"%A %m %-Y\")print('\\nExample 1:', s) # Example 2s = now.strftime(\"%a %-m %y\")print('\\nExample 2:', s) # Example 3s = now.strftime(\"%-I %p %S\")print('\\nExample 3:', s) # Example 4s = now.strftime(\"%H:%M:%S\")print('\\nExample 4:', s)", "e": 10986, "s": 10559, "text": null }, { "code": null, "e": 11123, "s": 10986, "text": "Without formatting 2021-08-19 18:16:25.881661\n\nExample 1: Thursday 08 2021\n\nExample 2: Thu 8 21\n\nExample 3: 6 PM 25\n\nExample 4: 18:16:25" }, { "code": null, "e": 11179, "s": 11123, "text": "Note: For more information, refer to strftime() method." }, { "code": null, "e": 11239, "s": 11179, "text": "strptime() creates a datetime object from the given string." }, { "code": null, "e": 11247, "s": 11239, "text": "Python3" }, { "code": "# import datetime module from datetimefrom datetime import datetime # consider the time stamps from a list in string# format DD/MM/YY H:M:S.microstime_data = [\"25/05/99 02:35:8.023\", \"26/05/99 12:45:0.003\", \"27/05/99 07:35:5.523\", \"28/05/99 05:15:55.523\"] # format the string in the given format : day/month/year # hours/minutes/seconds-micro secondsformat_data = \"%d/%m/%y %H:%M:%S.%f\" # Using strptime with datetime we will format string# into datetimefor i in time_data: print(datetime.strptime(i, format_data))", "e": 11781, "s": 11247, "text": null }, { "code": null, "e": 11889, "s": 11781, "text": "1999-05-25 02:35:08.023000\n1999-05-26 12:45:00.003000\n1999-05-27 07:35:05.523000\n1999-05-28 05:15:55.523000" }, { "code": null, "e": 12182, "s": 11889, "text": "Timezones in DateTime can be used in the case where one might want to display time according to the timezone of a specific region. This can be done using the pytz module of Python. This module serves the date-time conversion functionalities and helps users serving international client bases." }, { "code": null, "e": 12190, "s": 12182, "text": "Python3" }, { "code": "from datetime import datetimefrom pytz import timezone format = \"%Y-%m-%d %H:%M:%S %Z%z\" # Current time in UTCnow_utc = datetime.now(timezone('UTC'))print(now_utc.strftime(format)) timezones = ['Asia/Kolkata', 'Europe/Kiev', 'America/New_York'] for tzone in timezones: # Convert to Asia/Kolkata time zone now_asia = now_utc.astimezone(timezone(tzone)) print(now_asia.strftime(format))", "e": 12585, "s": 12190, "text": null }, { "code": null, "e": 12702, "s": 12585, "text": "2021-08-19 18:27:28 UTC+0000\n2021-08-19 23:57:28 IST+0530\n2021-08-19 21:27:28 EEST+0300\n2021-08-19 14:27:28 EDT-0400" }, { "code": null, "e": 12719, "s": 12702, "text": "arorakashish0911" }, { "code": null, "e": 12735, "s": 12719, "text": "simranarora5sos" }, { "code": null, "e": 12751, "s": 12735, "text": "nikhilaggarwal3" }, { "code": null, "e": 12760, "s": 12751, "text": "sweetyty" }, { "code": null, "e": 12770, "s": 12760, "text": "kalrap615" }, { "code": null, "e": 12785, "s": 12770, "text": "python-modules" }, { "code": null, "e": 12800, "s": 12785, "text": "python-utility" }, { "code": null, "e": 12807, "s": 12800, "text": "Python" }, { "code": null, "e": 12905, "s": 12807, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12923, "s": 12905, "text": "Python Dictionary" }, { "code": null, "e": 12965, "s": 12923, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 12987, "s": 12965, "text": "Enumerate() in Python" }, { "code": null, "e": 13022, "s": 12987, "text": "Read a file line by line in Python" }, { "code": null, "e": 13048, "s": 13022, "text": "Python String | replace()" }, { "code": null, "e": 13080, "s": 13048, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 13109, "s": 13080, "text": "*args and **kwargs in Python" }, { "code": null, "e": 13136, "s": 13109, "text": "Python Classes and Objects" }, { "code": null, "e": 13166, "s": 13136, "text": "Iterate over a list in Python" } ]
How to access the JSON fields, arrays and nested objects of JsonNode in Java?
A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class. We can return a valid string representation using the asText() method and convert the value of the node to a Java int using the asInt() method of JsonNode class. In the below example, we can access JSON fields, arrays and nested objects of JsonNode. import com.fasterxml.jackson.databind.*; import java.io.*; public class ParseJSONNodeTest { public static void main(String args[]) { String jsonStr = "{ \"name\" : \"Raja\", \"age\" : 30," + " \"technologies\" : [\"Java\", \"Scala\", \"Python\"]," + " \"nestedObject\" : { \"field\" : \"value\" } }"; ObjectMapper objectMapper = new ObjectMapper(); try { JsonNode node = objectMapper.readValue(jsonStr, JsonNode.class); JsonNode nameNode = node.get("name"); String name = nameNode.asText(); System.out.println(name); JsonNode ageNode = node.get("age"); int age = ageNode.asInt(); System.out.println(age); JsonNode array = node.get("technologies"); JsonNode jsonNode = array.get(1); String techStr = jsonNode.asText(); System.out.println(techStr); JsonNode child = node.get("nestedObject"); JsonNode childField = child.get("field"); String field = childField.asText(); System.out.println(field); } catch (IOException e) { e.printStackTrace(); } } } Raja 30 Scala value
[ { "code": null, "e": 1670, "s": 1187, "text": "A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class. We can return a valid string representation using the asText() method and convert the value of the node to a Java int using the asInt() method of JsonNode class." }, { "code": null, "e": 1758, "s": 1670, "text": "In the below example, we can access JSON fields, arrays and nested objects of JsonNode." }, { "code": null, "e": 2932, "s": 1758, "text": "import com.fasterxml.jackson.databind.*;\nimport java.io.*;\npublic class ParseJSONNodeTest {\n public static void main(String args[]) {\n String jsonStr = \"{ \\\"name\\\" : \\\"Raja\\\", \\\"age\\\" : 30,\" +\n \" \\\"technologies\\\" : [\\\"Java\\\", \\\"Scala\\\", \\\"Python\\\"],\" +\n \" \\\"nestedObject\\\" : { \\\"field\\\" : \\\"value\\\" } }\";\n ObjectMapper objectMapper = new ObjectMapper();\n try {\n JsonNode node = objectMapper.readValue(jsonStr, JsonNode.class);\n JsonNode nameNode = node.get(\"name\");\n String name = nameNode.asText();\n System.out.println(name);\n JsonNode ageNode = node.get(\"age\");\n int age = ageNode.asInt();\n System.out.println(age);\n JsonNode array = node.get(\"technologies\");\n JsonNode jsonNode = array.get(1);\n String techStr = jsonNode.asText();\n System.out.println(techStr);\n JsonNode child = node.get(\"nestedObject\");\n JsonNode childField = child.get(\"field\");\n String field = childField.asText();\n System.out.println(field);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2952, "s": 2932, "text": "Raja\n30\nScala\nvalue" } ]
Python String Concatenation
24 Aug, 2021 In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets [] can be used to access elements of the string.Example: Python3 # Python program to demonstrate# strings # Assign Welcome string to the variable var1var1 = "Welcome" # Assign statistics string to the variable var2var2 = "statistics" # print the resultprint(var1)print(var2) Welcome statistics String Concatenation is the technique of combining two strings. String Concatenation can be done using many ways.We can perform string concatenation using following ways: Using + operator Using join() method Using % operator Using format() function Using , (comma) Using + operator Using join() method Using % operator Using format() function Using , (comma) It’s very easy to use + operator for string concatenation. This operator can be used to add multiple strings together. However, the arguments must be a string. Note: Strings are immutable, therefore, whenever it is concatenated, it is assigned to a new variable.Example: Python3 # Python program to demonstrate# string concatenation # Defining stringsvar1 = "Hello "var2 = "World" # + Operator is used to combine stringsvar3 = var1 + var2print(var3) Hello World Here, the variable var1 stores the string “Hello ” and variable var2 stores the string “World”. The + Operator combines the string that is stored in the var1 and var2 and stores in another variable var3. The join() method is a string method and returns a string in which the elements of sequence have been joined by str separator.Example: Python3 # Python program to demonstrate# string concatenation var1 = "Hello"var2 = "World" # join() method is used to combine the stringsprint("".join([var1, var2])) # join() method is used here to combine# the string with a separator Space(" ")var3 = " ".join([var1, var2]) print(var3) HelloWorld Hello World In the above example, the variable var1 stores the string “Hello” and variable var2 stores the string “World”. The join() method combines the string that is stored in the var1 and var2. The join method accepts only the list as it’s argument and list size can be anything. We can store the combined string in another variable var3 which is separated by space.Note: To know more about join() method click here. We can use % operator for string formatting, it can also be used for string concatenation. It’s useful when we want to concatenate strings and perform simple formatting.Example: Python3 # Python program to demonstrate# string concatenation var1 = "Hello"var2 = "World" # % Operator is used here to combine the stringprint("% s % s" % (var1, var2)) Hello World Here, the % Operator combine the string that is stored in the var1 and var2. The %s denotes string data type. The value in both the variable is passed to the string %s and becomes “Hello World”. str.format() is one of the string formatting methods in Python, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting.Example: Python3 # Python program to demonstrate# string concatenation var1 = "Hello"var2 = "World" # format function is used here to# combine the stringprint("{} {}".format(var1, var2)) # store the result in another variablevar3 = "{} {}".format(var1, var2) print(var3) Hello World Hello World Here, the format() function combines the string that is stored in the var1 and var2 and stores in another variable var3. The curly braces {} are used to set the position of strings. The first variable stores in the first curly braces and second variable stores in the second curly braces. Finally it prints the value “Hello World”.Note: To know more about format() function click here. “,” is a great alternative to string concatenation using “+”. when you want to include a single whitespace.Example: Python3 # Python program to demonstrate# string concatenation var1 = "Hello"var2 = "World" # , to combine data types with a single whitespace.print(var1, var2) Hello World Use , when you want to combine data types with a single whitespace in between. srijanarya04 python-string Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Aug, 2021" }, { "code": null, "e": 310, "s": 52, "text": "In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets [] can be used to access elements of the string.Example: " }, { "code": null, "e": 318, "s": 310, "text": "Python3" }, { "code": "# Python program to demonstrate# strings # Assign Welcome string to the variable var1var1 = \"Welcome\" # Assign statistics string to the variable var2var2 = \"statistics\" # print the resultprint(var1)print(var2)", "e": 529, "s": 318, "text": null }, { "code": null, "e": 548, "s": 529, "text": "Welcome\nstatistics" }, { "code": null, "e": 722, "s": 550, "text": "String Concatenation is the technique of combining two strings. String Concatenation can be done using many ways.We can perform string concatenation using following ways: " }, { "code": null, "e": 821, "s": 722, "text": "Using + operator Using join() method Using % operator Using format() function Using , (comma) " }, { "code": null, "e": 840, "s": 821, "text": "Using + operator " }, { "code": null, "e": 862, "s": 840, "text": "Using join() method " }, { "code": null, "e": 881, "s": 862, "text": "Using % operator " }, { "code": null, "e": 907, "s": 881, "text": "Using format() function " }, { "code": null, "e": 924, "s": 907, "text": "Using , (comma) " }, { "code": null, "e": 1198, "s": 926, "text": "It’s very easy to use + operator for string concatenation. This operator can be used to add multiple strings together. However, the arguments must be a string. Note: Strings are immutable, therefore, whenever it is concatenated, it is assigned to a new variable.Example: " }, { "code": null, "e": 1206, "s": 1198, "text": "Python3" }, { "code": "# Python program to demonstrate# string concatenation # Defining stringsvar1 = \"Hello \"var2 = \"World\" # + Operator is used to combine stringsvar3 = var1 + var2print(var3)", "e": 1378, "s": 1206, "text": null }, { "code": null, "e": 1390, "s": 1378, "text": "Hello World" }, { "code": null, "e": 1595, "s": 1390, "text": "Here, the variable var1 stores the string “Hello ” and variable var2 stores the string “World”. The + Operator combines the string that is stored in the var1 and var2 and stores in another variable var3. " }, { "code": null, "e": 1731, "s": 1595, "text": "The join() method is a string method and returns a string in which the elements of sequence have been joined by str separator.Example: " }, { "code": null, "e": 1739, "s": 1731, "text": "Python3" }, { "code": "# Python program to demonstrate# string concatenation var1 = \"Hello\"var2 = \"World\" # join() method is used to combine the stringsprint(\"\".join([var1, var2])) # join() method is used here to combine# the string with a separator Space(\" \")var3 = \" \".join([var1, var2]) print(var3)", "e": 2019, "s": 1739, "text": null }, { "code": null, "e": 2042, "s": 2019, "text": "HelloWorld\nHello World" }, { "code": null, "e": 2452, "s": 2042, "text": "In the above example, the variable var1 stores the string “Hello” and variable var2 stores the string “World”. The join() method combines the string that is stored in the var1 and var2. The join method accepts only the list as it’s argument and list size can be anything. We can store the combined string in another variable var3 which is separated by space.Note: To know more about join() method click here. " }, { "code": null, "e": 2631, "s": 2452, "text": "We can use % operator for string formatting, it can also be used for string concatenation. It’s useful when we want to concatenate strings and perform simple formatting.Example: " }, { "code": null, "e": 2639, "s": 2631, "text": "Python3" }, { "code": "# Python program to demonstrate# string concatenation var1 = \"Hello\"var2 = \"World\" # % Operator is used here to combine the stringprint(\"% s % s\" % (var1, var2))", "e": 2802, "s": 2639, "text": null }, { "code": null, "e": 2814, "s": 2802, "text": "Hello World" }, { "code": null, "e": 3010, "s": 2814, "text": "Here, the % Operator combine the string that is stored in the var1 and var2. The %s denotes string data type. The value in both the variable is passed to the string %s and becomes “Hello World”. " }, { "code": null, "e": 3229, "s": 3010, "text": "str.format() is one of the string formatting methods in Python, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting.Example: " }, { "code": null, "e": 3237, "s": 3229, "text": "Python3" }, { "code": "# Python program to demonstrate# string concatenation var1 = \"Hello\"var2 = \"World\" # format function is used here to# combine the stringprint(\"{} {}\".format(var1, var2)) # store the result in another variablevar3 = \"{} {}\".format(var1, var2) print(var3)", "e": 3492, "s": 3237, "text": null }, { "code": null, "e": 3516, "s": 3492, "text": "Hello World\nHello World" }, { "code": null, "e": 3902, "s": 3516, "text": "Here, the format() function combines the string that is stored in the var1 and var2 and stores in another variable var3. The curly braces {} are used to set the position of strings. The first variable stores in the first curly braces and second variable stores in the second curly braces. Finally it prints the value “Hello World”.Note: To know more about format() function click here." }, { "code": null, "e": 4019, "s": 3902, "text": "“,” is a great alternative to string concatenation using “+”. when you want to include a single whitespace.Example: " }, { "code": null, "e": 4027, "s": 4019, "text": "Python3" }, { "code": "# Python program to demonstrate# string concatenation var1 = \"Hello\"var2 = \"World\" # , to combine data types with a single whitespace.print(var1, var2)", "e": 4179, "s": 4027, "text": null }, { "code": null, "e": 4191, "s": 4179, "text": "Hello World" }, { "code": null, "e": 4270, "s": 4191, "text": "Use , when you want to combine data types with a single whitespace in between." }, { "code": null, "e": 4283, "s": 4270, "text": "srijanarya04" }, { "code": null, "e": 4297, "s": 4283, "text": "python-string" }, { "code": null, "e": 4304, "s": 4297, "text": "Python" }, { "code": null, "e": 4323, "s": 4304, "text": "Technical Scripter" } ]
Java Program to check if two dates are equal
Let us first declare objects of LocalDate − LocalDate dateOne = LocalDate.now(); LocalDate dateTwo = LocalDate.of(dateOne.getYear(), dateOne.getMonth(), dateOne.getDayOfMonth()); Let us now use the equals () method to check if both the dates are same or not − if (dateOne.equals(dateTwo)) { System.out.printf("\nBoth the dates are same!", dateOne, dateTwo); } import java.time.LocalDate; public class Demo { public static void main(String[] argv) { LocalDate dateOne = LocalDate.now(); LocalDate dateTwo = LocalDate.of(dateOne.getYear(), dateOne.getMonth(), dateOne.getDayOfMonth()); System.out.printf("Date One = "+dateOne); System.out.printf("\nDate Two = "+dateTwo); if (dateOne.equals(dateTwo)) { System.out.printf("\nBoth the dates are same!", dateOne, dateTwo); } } } Date One = 2019-04-12 Date Two = 2019-04-12 Both the dates are same!
[ { "code": null, "e": 1106, "s": 1062, "text": "Let us first declare objects of LocalDate −" }, { "code": null, "e": 1143, "s": 1106, "text": "LocalDate dateOne = LocalDate.now();" }, { "code": null, "e": 1241, "s": 1143, "text": "LocalDate dateTwo = LocalDate.of(dateOne.getYear(), dateOne.getMonth(), dateOne.getDayOfMonth());" }, { "code": null, "e": 1322, "s": 1241, "text": "Let us now use the equals () method to check if both the dates are same or not −" }, { "code": null, "e": 1425, "s": 1322, "text": "if (dateOne.equals(dateTwo)) {\n System.out.printf(\"\\nBoth the dates are same!\", dateOne, dateTwo);\n}" }, { "code": null, "e": 1890, "s": 1425, "text": "import java.time.LocalDate;\npublic class Demo {\n public static void main(String[] argv) {\n LocalDate dateOne = LocalDate.now();\n LocalDate dateTwo = LocalDate.of(dateOne.getYear(), dateOne.getMonth(), dateOne.getDayOfMonth());\n System.out.printf(\"Date One = \"+dateOne);\n System.out.printf(\"\\nDate Two = \"+dateTwo);\n if (dateOne.equals(dateTwo)) {\n System.out.printf(\"\\nBoth the dates are same!\", dateOne, dateTwo);\n }\n }\n}" }, { "code": null, "e": 1959, "s": 1890, "text": "Date One = 2019-04-12\nDate Two = 2019-04-12\nBoth the dates are same!" } ]
How to find the longest word within the string in JavaScript ? - GeeksforGeeks
07 Apr, 2021 Given a string and the task is to find the largest word from the string using JavaScript. Example: Input: "This is a demo String find the largest word from it" Output: "largest" Input: "Hello guys this is geeksforgeeks where students learn programming" Output: "geeksforgeeks" To achieve this we use the following approaches: Using regex and for..loopUsing split and sort() methodUsing split and reduce() method Using regex and for..loop Using split and sort() method Using split and reduce() method Approach 1: Using regex and for...loop. In this approach, we use regex to split the string into an array of words by using the regex /[a-zA-Z0-9]+/gi and then using for loop iterate the array and search the largest string. Example 1: index.html <script>// Javascript program to search largest word from a string function longest(str){ // Split the string using regex str = str.match(/[a-zA-Z0-9]+/gi); // Creating a empty string to store largest word let largest = ""; // Creating a for...loop to iterate over the array for(let i = 0; i < str.length; i++){ // If the i'th item is greater than largest string // then overwrite the largest string with the i'th value if(str[i].length > largest.length){ largest = str[i] } } return largest;} console.log(longest("Hello guys this is geeksforgeeks where"+ " students learn programming"))</script> Output: "geeksforgeeks" Approach 2: By using the split() and sort() method. In this approach we split the string using the String.split() method and sort the array using the Array.sort() method. Example 2: index.js <script>function longest(str){ // Split the string into array str = str.split(" ") // Return the first sorted item of the Array return str.sort((a, b) => b.length - a.length)[0]} console.log(longest("Hello guys this is geeksforgeeks"+ " where students learn programming"))</script> Output: "geeksforgeeks" Approach 3 : Using split() and reduce() method. In this approach, we split the string using the String.split() method, and by using the reduce method we search the largest element of the array, which is your largest string. index.js <script>function longest(str){ // Split the string into array str = str.split(" "); // Get the index of largest item of the array let index = str.reduce((acc, curr, i)=>{ if(curr.length > str[acc].length){ return i } return acc; }, 0) return str[index];} console.log(longest("Hello guys this is geeksforgeeks"+ " where students learn programming"))</script> Output: "geeksforgeeks" JavaScript-Methods JavaScript-Questions javascript-string Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript How to calculate the number of days between two dates in javascript? Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 37970, "s": 37942, "text": "\n07 Apr, 2021" }, { "code": null, "e": 38060, "s": 37970, "text": "Given a string and the task is to find the largest word from the string using JavaScript." }, { "code": null, "e": 38069, "s": 38060, "text": "Example:" }, { "code": null, "e": 38249, "s": 38069, "text": "Input: \"This is a demo String find the largest word from it\"\nOutput: \"largest\"\n\nInput: \"Hello guys this is geeksforgeeks where students learn programming\"\nOutput: \"geeksforgeeks\"" }, { "code": null, "e": 38298, "s": 38249, "text": "To achieve this we use the following approaches:" }, { "code": null, "e": 38384, "s": 38298, "text": "Using regex and for..loopUsing split and sort() methodUsing split and reduce() method" }, { "code": null, "e": 38410, "s": 38384, "text": "Using regex and for..loop" }, { "code": null, "e": 38440, "s": 38410, "text": "Using split and sort() method" }, { "code": null, "e": 38472, "s": 38440, "text": "Using split and reduce() method" }, { "code": null, "e": 38695, "s": 38472, "text": "Approach 1: Using regex and for...loop. In this approach, we use regex to split the string into an array of words by using the regex /[a-zA-Z0-9]+/gi and then using for loop iterate the array and search the largest string." }, { "code": null, "e": 38706, "s": 38695, "text": "Example 1:" }, { "code": null, "e": 38717, "s": 38706, "text": "index.html" }, { "code": "<script>// Javascript program to search largest word from a string function longest(str){ // Split the string using regex str = str.match(/[a-zA-Z0-9]+/gi); // Creating a empty string to store largest word let largest = \"\"; // Creating a for...loop to iterate over the array for(let i = 0; i < str.length; i++){ // If the i'th item is greater than largest string // then overwrite the largest string with the i'th value if(str[i].length > largest.length){ largest = str[i] } } return largest;} console.log(longest(\"Hello guys this is geeksforgeeks where\"+ \" students learn programming\"))</script>", "e": 39365, "s": 38717, "text": null }, { "code": null, "e": 39373, "s": 39365, "text": "Output:" }, { "code": null, "e": 39389, "s": 39373, "text": "\"geeksforgeeks\"" }, { "code": null, "e": 39561, "s": 39389, "text": "Approach 2: By using the split() and sort() method. In this approach we split the string using the String.split() method and sort the array using the Array.sort() method. " }, { "code": null, "e": 39572, "s": 39561, "text": "Example 2:" }, { "code": null, "e": 39581, "s": 39572, "text": "index.js" }, { "code": "<script>function longest(str){ // Split the string into array str = str.split(\" \") // Return the first sorted item of the Array return str.sort((a, b) => b.length - a.length)[0]} console.log(longest(\"Hello guys this is geeksforgeeks\"+ \" where students learn programming\"))</script>", "e": 39889, "s": 39581, "text": null }, { "code": null, "e": 39897, "s": 39889, "text": "Output:" }, { "code": null, "e": 39913, "s": 39897, "text": "\"geeksforgeeks\"" }, { "code": null, "e": 40137, "s": 39913, "text": "Approach 3 : Using split() and reduce() method. In this approach, we split the string using the String.split() method, and by using the reduce method we search the largest element of the array, which is your largest string." }, { "code": null, "e": 40146, "s": 40137, "text": "index.js" }, { "code": "<script>function longest(str){ // Split the string into array str = str.split(\" \"); // Get the index of largest item of the array let index = str.reduce((acc, curr, i)=>{ if(curr.length > str[acc].length){ return i } return acc; }, 0) return str[index];} console.log(longest(\"Hello guys this is geeksforgeeks\"+ \" where students learn programming\"))</script>", "e": 40554, "s": 40146, "text": null }, { "code": null, "e": 40562, "s": 40554, "text": "Output:" }, { "code": null, "e": 40578, "s": 40562, "text": "\"geeksforgeeks\"" }, { "code": null, "e": 40597, "s": 40578, "text": "JavaScript-Methods" }, { "code": null, "e": 40618, "s": 40597, "text": "JavaScript-Questions" }, { "code": null, "e": 40636, "s": 40618, "text": "javascript-string" }, { "code": null, "e": 40643, "s": 40636, "text": "Picked" }, { "code": null, "e": 40654, "s": 40643, "text": "JavaScript" }, { "code": null, "e": 40671, "s": 40654, "text": "Web Technologies" }, { "code": null, "e": 40769, "s": 40671, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40814, "s": 40769, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40875, "s": 40814, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 40944, "s": 40875, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 41016, "s": 40944, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 41068, "s": 41016, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 41110, "s": 41068, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 41143, "s": 41110, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 41186, "s": 41143, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 41248, "s": 41186, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to set only numeric value for edittext in Android?
This example demonstrates how do I set only numeric value for editText in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:ems="10"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText" android:layout_centerHorizontal="true" android:layout_marginTop="26dp" android:text="Click Here to set numeric value for EditText"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.InputType; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { Button button; EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); editText = (EditText) findViewById(R.id.editText); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editText.setInputType(InputType.TYPE_CLASS_NUMBER); } }); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <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": 1145, "s": 1062, "text": "This example demonstrates how do I set only numeric value for editText in Android." }, { "code": null, "e": 1274, "s": 1145, "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": 1339, "s": 1274, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2208, "s": 1339, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_centerVertical=\"true\"\n android:ems=\"10\"/>\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/editText\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"26dp\"\n android:text=\"Click Here to set numeric value for\n EditText\"/>\n</RelativeLayout>" }, { "code": null, "e": 2265, "s": 2208, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3029, "s": 2265, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.InputType;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n Button button;\n EditText editText;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n button = (Button) findViewById(R.id.button);\n editText = (EditText) findViewById(R.id.editText);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n editText.setInputType(InputType.TYPE_CLASS_NUMBER);\n }\n });\n }\n}" }, { "code": null, "e": 3084, "s": 3029, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3754, "s": 3084, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4102, "s": 3754, "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": 4143, "s": 4102, "text": "Click here to download the project code." } ]
Marimekko Charts with Plotly Express | by Darío Weitz | Towards Data Science
Suppose you are involved in a business plan competition. You need to present a compelling business case because investors make their decisions based on your storytelling. You must include visually interesting graphics and images. But this is where we can make a double mistake: 1) that the audience will see our figures and immediately understand the idea we are showing; 2) that the audience, even in the professional environment, can receive an important sequence of complex visualizations and in the act grasp trends, patterns, correlations, proportions, distributions in the way we have selected to do it. Remember: data visualization is a tool for communication. So, we must always ask ourselves: am I communicating clearly? Am I using a type of figure that leaves no room for doubt? These questions are particularly important if we are using variable width bar charts. There are different types of variable width bar charts but two are the most popular: 1) Bar Mekko chart; 2) Marimekko chart (Marimekko is a Finnish textile brand that has large and varied shape patterns, as well as simple and bright colors and styles). They differ in the following: a Bar Mekko chart (BMc) is like a “standard” bar chart, but its bars are of variable width; a Marimekko chart (Mc) is like a 100% stacked bar chart but its bars are of variable width, it is a normalized column graph with variable bar widths. Both charts are used to show two numerical variables for each category present in the data set; the goal is to make a comparison between the categories, but not between the numerical variables. They are widely used in Dashboards or in Marketing, Sales, and Business Presentations. The vertical axis has a numerical scale (100% on a Marimekko Chart) and represents one of the quantitative variables. The horizontal axis can be either numerical or categorical. If it is numerical, each rectangle has a width proportional to the value of the second quantitative variable, a different color, and a legend that identifies it. If it is categorical, the width of each bar also indicates the value of the second quantitative variable. Unlike the standard bar chart, no space is left between the bars (Be careful not to confuse Mekko charts with Histograms.) In both, BMc and Mc, the entire width of the horizontal axis is occupied. The Mekko Bar chart is an alternative to classic bar charts allowing you to reduce the number of charts in a business presentation. To achieve this, the chart encodes one of the numerical variables by the height of the bars and the other quantitative variable by the width of the bars. The Marimekko Chart is an alternative to clustered bar charts (grouped bar charts) allowing to reduce their number in a business presentation: they show numerical information related to subgroups or subcategories within the main categories. Do not confuse Mcs with spineplots. In its most rigorous definition, a spineplot is a one-dimensional, horizontal stacked bar graph used to display frequencies, proportions, or percentages of two cross-classified categorical variables in contingency tables. The confusion arises because some spineplots visualization tools allow a vertical orientation, which they call mosaic plots. This term is also erroneously attributed to the Marimekko Charts but should be reserved for those charts that allow examining the relationship between two or more categorical variables through variable-width rectangles. Plotly, a computing company headquartered in Montreal, Canada, developed plotly.py, an interactive, open-source visualization tool for Python. In 2019, the company released Plotly 4.0 which includes Plotly Express, a high-level wrapper fully compatible with the rest of the Plotly ecosystem. Plotly provides a group of classes called graph objects that may be used to construct figures. The plotly.graph_objects module contains a hierarchy of Python classes. Figure is a primary class. Figure has a data attribute and a layout attribute. The data attribute has more than 40 objects, each one refers to a specific type of chart (trace) with its corresponding parameters. The layout attribute specifies the properties of the figure as a whole (axes, title, shapes, legends, etc.). We worked with a dataset downloaded from Kaggle. The dataset contains records related to Video Games Sales & Game Ratings Data Scraped from VzCharts. We particularly selected three csv files: 1) 1031 records about Video Games sales on the Playstation 4 platform by Sony [1]; 2) 422 records about Video Games sales on the Microsoft Xbox One console [2]; 3) 11563 records about Video Games sales from different publishers [3]. We would like to know how sales of the different platforms were distributed in several regions of the planet. First, we imported Plotly Express as px, the module plotly.graph_objects as go, and the libraries Numpy & Pandas as np and pd respectively. import plotly.graph_objects as goimport plotly.express as pximport numpy as npimport pandas as pd Then we used the read_csv function to read the comma-separated values (csv) files into their corresponding dataframes. df1 = pd.read_csv(path + 'XboxOne_GameSales2.csv', index_col =False, header = 0, sep = ';', engine='python')df2 = pd.read_csv(path + 'PS4_GamesSales2.csv', index_col = False, header = 0, sep = ';', engine='python')df3 = pd.read_csv(path + 'Video_Games_Sales.csv', index_col = False, header = 0, sep = ';', engine='python') The screenshot below shows the first ten records of the dataset named df1 (corresponding to XboxOne): The dataset named df2 has the same number and names of columns as df1, but df3 (Video_Games_Sales) has a very different layout: For our computations we only need the columns that store the sales in the four regions of interest (North America, Europe, Japan, & Rest of World). In df1 and df2 we simply select the corresponding four columns, but df3 requires pre-processing to equalize the data. The pre-processing task consists of only selecting the Nintendo sales and renaming the four selected columns: df1 = df1[['North America', 'Europe', 'Japan', 'Rest of World']]df2 = df2[['North America', 'Europe', 'Japan', 'Rest of World']]df3 = df3.drop(df3[(df3.Publisher != 'Nintendo')].index)df3 = df3[['NA_Sales', 'EU_Sales', 'JP_Sales', 'Other_Sales']]df3 = df3.rename(columns={'NA_Sales': 'North America', 'EU_Sales': 'Europe', 'JP_Sales': 'Japan', 'Other_Sales' :'Rest of World'}) Then we applied the function sum() to the three dataframes. Remember that the function sum() returns the sum of the values for the requested axis. Again, df3 requires a pre-processing because before applying the function sum(), we must convert column data stored as object into numbers using pd.to_numeric, errors=’coerce’. Option errors=’coerce’ converts non numeric values to NaN. Finally, we concatenated the three files and calculated the respective percentages in a new dataframe named df4. sum_1 = df1.sum(axis = 0, skipna = True)sum_2 = df2.sum(axis = 0, skipna = True)df3 = df3.apply(pd.to_numeric, errors='coerce')sum_3 = df3.sum(axis = 0, skipna = True)list_df = [sum_1, sum_2, sum_3]df4 = pd.concat(list_df , axis = 1).reset_index()df4.columns = ['region', 'xbox', 'ps4', 'nint']df4['perc_xbox'] = (df4['xbox'] / ( df4['xbox'] + df4['ps4'] + df4['nint'])) * 100df4['perc_ps4'] = (df4['ps4'] / ( df4['xbox'] + df4['ps4'] + df4['nint'])) * 100df4['perc_nint'] = (df4['nint'] / ( df4['xbox'] + df4['ps4'] + df4['nint'])) * 100 In order to draw a variable width bar chart, we used a dictionary named data for the stack ordering, another dictionary named colors for the bar colors and one Series (widths) and one variable (width_x) to assign the width of the bars on the horizontal axis: data = {"Nintendo": df4['perc_nint'], "Xbox" : df4['perc_xbox'], "PS4" : df4['perc_ps4'] }colors= {"Nintendo": 'blue', "Xbox" : 'green', "PS4" : 'darkred' }widths = sum_3x_width = sum_3.sum() The conceptual idea with plotly.graph_objects is to use .add_trace(go.Bar()) to create the figure and then add methods such as .update_layout(), .update_xaxes, .update_yaxes to manipulate the figure. Finally, we export the figure with .write_image() and render it with .show(). Note that add_trace(go.Bar()) is inside a for loop according to the order we decided in the dictionary named data. We updated the chart with update.layout: set the title text, title font, and legend font, and set the figure dimensions (width and height). barmode = ‘stack’ determines that bars are stacked on top of one another. Then we updated the x-axis and the y-axis (text, font, tickfont). Set the y-axis range between 0 and 100% and the x-axis range between 0 and x_width. fig = go.Figure()for key in data:fig.add_trace(go.Bar(name = key, y = data[key], x = np.cumsum(widths) - widths, width = widths, offset = 0, marker = {'color' : colors[key]}, customdata = data[key], texttemplate = "%{y:.2f}", textposition = "inside", textangle = 0,textfont_color = "white", textfont_size = 30))fig.update_layout(title_text ="Sales of Consoles per Region", barmode = "stack", title_font_size = 40,legend_font_size = 30, width = 1400, height = 1400)fig.update_xaxes(title_text= 'Width of each bar=Sales of Nintendo in MM', range = [0, x_width], title_font_size = 30, tickvals = np.cumsum(widths)-widths/2, ticktext =["%s<br>%d"% l, w)for l,w in zip(labels, widths)], tickfont = dict(family='Calibri', color='black', size=25))fig.update_yaxes(title_text = 'Percentage (%)', range = [0,100], title_font=dict(size=35, family='Verdana', color='darkred'))fig.write_image(path + "figmarimekko1.png")fig.show() Figure 1 describes in a single chart the accumulated sales of Nintendo video games separated into different regions and the percentages corresponding to the different consoles. The elements that characterize a Marimekko chart can be seen: a rectangular area divided into smaller rectangles of varying width; vertically stacked rectangles; a horizontal axis that occupies the entire width of the chart; a vertical axis with a percentage scale; total sales per specific brand (Nintendo) on the lower baseline; different bar widths that allow calculating the relative contributions of each region to the total sales. But the choice of the stacking order was completely arbitrary. So, what happens if we change that order? We just have to make a few simple changes to the code: data = {"Xbox" : df4['perc_xbox'], "PS4" : df4['perc_ps4'], "Nintendo": df4['perc_nint'] }widths = sum_1x_width = sum_1.sum() In Figure 2, the different widths of the rectangles are given by the different XboxOne sales in the regions of interest. Although the sales percentages remain unchanged between the different consoles, the audience receives a very different message, particularly in the case of Japan. The same is true if the horizontal axis is segmented by PS4 console sales: data = {"PS4" : df4['perc_ps4'], "Nintendo": df4['perc_nint'], "Xbox" : df4['perc_xbox'] }widths = sum_2x_width = sum_2.sum() This is the main drawback with Marimekko charts: not only are they difficult to read and interpret because they are based on audiences’ ability to decode numerical information by comparing areas, but they can also mislead the audience to wrong conclusions. As Alberto Cairo wisely pointed out [4]: “Just as we can lie with statistics, we can also lie with charts” If you find this article of interest, please read my previous (https://medium.com/@dar.wtz): “Scatter Plots with Plotly Express, Trendlines & Faceting” towardsdatascience.com “Histograms with Plotly Express, Themes & Templates”
[ { "code": null, "e": 218, "s": 47, "text": "Suppose you are involved in a business plan competition. You need to present a compelling business case because investors make their decisions based on your storytelling." }, { "code": null, "e": 657, "s": 218, "text": "You must include visually interesting graphics and images. But this is where we can make a double mistake: 1) that the audience will see our figures and immediately understand the idea we are showing; 2) that the audience, even in the professional environment, can receive an important sequence of complex visualizations and in the act grasp trends, patterns, correlations, proportions, distributions in the way we have selected to do it." }, { "code": null, "e": 922, "s": 657, "text": "Remember: data visualization is a tool for communication. So, we must always ask ourselves: am I communicating clearly? Am I using a type of figure that leaves no room for doubt? These questions are particularly important if we are using variable width bar charts." }, { "code": null, "e": 1175, "s": 922, "text": "There are different types of variable width bar charts but two are the most popular: 1) Bar Mekko chart; 2) Marimekko chart (Marimekko is a Finnish textile brand that has large and varied shape patterns, as well as simple and bright colors and styles)." }, { "code": null, "e": 1447, "s": 1175, "text": "They differ in the following: a Bar Mekko chart (BMc) is like a “standard” bar chart, but its bars are of variable width; a Marimekko chart (Mc) is like a 100% stacked bar chart but its bars are of variable width, it is a normalized column graph with variable bar widths." }, { "code": null, "e": 1728, "s": 1447, "text": "Both charts are used to show two numerical variables for each category present in the data set; the goal is to make a comparison between the categories, but not between the numerical variables. They are widely used in Dashboards or in Marketing, Sales, and Business Presentations." }, { "code": null, "e": 2174, "s": 1728, "text": "The vertical axis has a numerical scale (100% on a Marimekko Chart) and represents one of the quantitative variables. The horizontal axis can be either numerical or categorical. If it is numerical, each rectangle has a width proportional to the value of the second quantitative variable, a different color, and a legend that identifies it. If it is categorical, the width of each bar also indicates the value of the second quantitative variable." }, { "code": null, "e": 2371, "s": 2174, "text": "Unlike the standard bar chart, no space is left between the bars (Be careful not to confuse Mekko charts with Histograms.) In both, BMc and Mc, the entire width of the horizontal axis is occupied." }, { "code": null, "e": 2657, "s": 2371, "text": "The Mekko Bar chart is an alternative to classic bar charts allowing you to reduce the number of charts in a business presentation. To achieve this, the chart encodes one of the numerical variables by the height of the bars and the other quantitative variable by the width of the bars." }, { "code": null, "e": 2898, "s": 2657, "text": "The Marimekko Chart is an alternative to clustered bar charts (grouped bar charts) allowing to reduce their number in a business presentation: they show numerical information related to subgroups or subcategories within the main categories." }, { "code": null, "e": 3501, "s": 2898, "text": "Do not confuse Mcs with spineplots. In its most rigorous definition, a spineplot is a one-dimensional, horizontal stacked bar graph used to display frequencies, proportions, or percentages of two cross-classified categorical variables in contingency tables. The confusion arises because some spineplots visualization tools allow a vertical orientation, which they call mosaic plots. This term is also erroneously attributed to the Marimekko Charts but should be reserved for those charts that allow examining the relationship between two or more categorical variables through variable-width rectangles." }, { "code": null, "e": 3793, "s": 3501, "text": "Plotly, a computing company headquartered in Montreal, Canada, developed plotly.py, an interactive, open-source visualization tool for Python. In 2019, the company released Plotly 4.0 which includes Plotly Express, a high-level wrapper fully compatible with the rest of the Plotly ecosystem." }, { "code": null, "e": 4280, "s": 3793, "text": "Plotly provides a group of classes called graph objects that may be used to construct figures. The plotly.graph_objects module contains a hierarchy of Python classes. Figure is a primary class. Figure has a data attribute and a layout attribute. The data attribute has more than 40 objects, each one refers to a specific type of chart (trace) with its corresponding parameters. The layout attribute specifies the properties of the figure as a whole (axes, title, shapes, legends, etc.)." }, { "code": null, "e": 4815, "s": 4280, "text": "We worked with a dataset downloaded from Kaggle. The dataset contains records related to Video Games Sales & Game Ratings Data Scraped from VzCharts. We particularly selected three csv files: 1) 1031 records about Video Games sales on the Playstation 4 platform by Sony [1]; 2) 422 records about Video Games sales on the Microsoft Xbox One console [2]; 3) 11563 records about Video Games sales from different publishers [3]. We would like to know how sales of the different platforms were distributed in several regions of the planet." }, { "code": null, "e": 4955, "s": 4815, "text": "First, we imported Plotly Express as px, the module plotly.graph_objects as go, and the libraries Numpy & Pandas as np and pd respectively." }, { "code": null, "e": 5054, "s": 4955, "text": "import plotly.graph_objects as goimport plotly.express as pximport numpy as npimport pandas as pd" }, { "code": null, "e": 5173, "s": 5054, "text": "Then we used the read_csv function to read the comma-separated values (csv) files into their corresponding dataframes." }, { "code": null, "e": 5604, "s": 5173, "text": "df1 = pd.read_csv(path + 'XboxOne_GameSales2.csv', index_col =False, header = 0, sep = ';', engine='python')df2 = pd.read_csv(path + 'PS4_GamesSales2.csv', index_col = False, header = 0, sep = ';', engine='python')df3 = pd.read_csv(path + 'Video_Games_Sales.csv', index_col = False, header = 0, sep = ';', engine='python')" }, { "code": null, "e": 5706, "s": 5604, "text": "The screenshot below shows the first ten records of the dataset named df1 (corresponding to XboxOne):" }, { "code": null, "e": 5834, "s": 5706, "text": "The dataset named df2 has the same number and names of columns as df1, but df3 (Video_Games_Sales) has a very different layout:" }, { "code": null, "e": 6210, "s": 5834, "text": "For our computations we only need the columns that store the sales in the four regions of interest (North America, Europe, Japan, & Rest of World). In df1 and df2 we simply select the corresponding four columns, but df3 requires pre-processing to equalize the data. The pre-processing task consists of only selecting the Nintendo sales and renaming the four selected columns:" }, { "code": null, "e": 6663, "s": 6210, "text": "df1 = df1[['North America', 'Europe', 'Japan', 'Rest of World']]df2 = df2[['North America', 'Europe', 'Japan', 'Rest of World']]df3 = df3.drop(df3[(df3.Publisher != 'Nintendo')].index)df3 = df3[['NA_Sales', 'EU_Sales', 'JP_Sales', 'Other_Sales']]df3 = df3.rename(columns={'NA_Sales': 'North America', 'EU_Sales': 'Europe', 'JP_Sales': 'Japan', 'Other_Sales' :'Rest of World'})" }, { "code": null, "e": 6810, "s": 6663, "text": "Then we applied the function sum() to the three dataframes. Remember that the function sum() returns the sum of the values for the requested axis." }, { "code": null, "e": 7046, "s": 6810, "text": "Again, df3 requires a pre-processing because before applying the function sum(), we must convert column data stored as object into numbers using pd.to_numeric, errors=’coerce’. Option errors=’coerce’ converts non numeric values to NaN." }, { "code": null, "e": 7159, "s": 7046, "text": "Finally, we concatenated the three files and calculated the respective percentages in a new dataframe named df4." }, { "code": null, "e": 7760, "s": 7159, "text": "sum_1 = df1.sum(axis = 0, skipna = True)sum_2 = df2.sum(axis = 0, skipna = True)df3 = df3.apply(pd.to_numeric, errors='coerce')sum_3 = df3.sum(axis = 0, skipna = True)list_df = [sum_1, sum_2, sum_3]df4 = pd.concat(list_df , axis = 1).reset_index()df4.columns = ['region', 'xbox', 'ps4', 'nint']df4['perc_xbox'] = (df4['xbox'] / ( df4['xbox'] + df4['ps4'] + df4['nint'])) * 100df4['perc_ps4'] = (df4['ps4'] / ( df4['xbox'] + df4['ps4'] + df4['nint'])) * 100df4['perc_nint'] = (df4['nint'] / ( df4['xbox'] + df4['ps4'] + df4['nint'])) * 100" }, { "code": null, "e": 8019, "s": 7760, "text": "In order to draw a variable width bar chart, we used a dictionary named data for the stack ordering, another dictionary named colors for the bar colors and one Series (widths) and one variable (width_x) to assign the width of the bars on the horizontal axis:" }, { "code": null, "e": 8270, "s": 8019, "text": "data = {\"Nintendo\": df4['perc_nint'], \"Xbox\" : df4['perc_xbox'], \"PS4\" : df4['perc_ps4'] }colors= {\"Nintendo\": 'blue', \"Xbox\" : 'green', \"PS4\" : 'darkred' }widths = sum_3x_width = sum_3.sum()" }, { "code": null, "e": 8548, "s": 8270, "text": "The conceptual idea with plotly.graph_objects is to use .add_trace(go.Bar()) to create the figure and then add methods such as .update_layout(), .update_xaxes, .update_yaxes to manipulate the figure. Finally, we export the figure with .write_image() and render it with .show()." }, { "code": null, "e": 8663, "s": 8548, "text": "Note that add_trace(go.Bar()) is inside a for loop according to the order we decided in the dictionary named data." }, { "code": null, "e": 8877, "s": 8663, "text": "We updated the chart with update.layout: set the title text, title font, and legend font, and set the figure dimensions (width and height). barmode = ‘stack’ determines that bars are stacked on top of one another." }, { "code": null, "e": 9027, "s": 8877, "text": "Then we updated the x-axis and the y-axis (text, font, tickfont). Set the y-axis range between 0 and 100% and the x-axis range between 0 and x_width." }, { "code": null, "e": 10419, "s": 9027, "text": "fig = go.Figure()for key in data:fig.add_trace(go.Bar(name = key, y = data[key], x = np.cumsum(widths) - widths, width = widths, offset = 0, marker = {'color' : colors[key]}, customdata = data[key], texttemplate = \"%{y:.2f}\", textposition = \"inside\", textangle = 0,textfont_color = \"white\", textfont_size = 30))fig.update_layout(title_text =\"Sales of Consoles per Region\", barmode = \"stack\", title_font_size = 40,legend_font_size = 30, width = 1400, height = 1400)fig.update_xaxes(title_text= 'Width of each bar=Sales of Nintendo in MM', range = [0, x_width], title_font_size = 30, tickvals = np.cumsum(widths)-widths/2, ticktext =[\"%s<br>%d\"% l, w)for l,w in zip(labels, widths)], tickfont = dict(family='Calibri', color='black', size=25))fig.update_yaxes(title_text = 'Percentage (%)', range = [0,100], title_font=dict(size=35, family='Verdana', color='darkred'))fig.write_image(path + \"figmarimekko1.png\")fig.show()" }, { "code": null, "e": 11033, "s": 10419, "text": "Figure 1 describes in a single chart the accumulated sales of Nintendo video games separated into different regions and the percentages corresponding to the different consoles. The elements that characterize a Marimekko chart can be seen: a rectangular area divided into smaller rectangles of varying width; vertically stacked rectangles; a horizontal axis that occupies the entire width of the chart; a vertical axis with a percentage scale; total sales per specific brand (Nintendo) on the lower baseline; different bar widths that allow calculating the relative contributions of each region to the total sales." }, { "code": null, "e": 11193, "s": 11033, "text": "But the choice of the stacking order was completely arbitrary. So, what happens if we change that order? We just have to make a few simple changes to the code:" }, { "code": null, "e": 11348, "s": 11193, "text": "data = {\"Xbox\" : df4['perc_xbox'], \"PS4\" : df4['perc_ps4'], \"Nintendo\": df4['perc_nint'] }widths = sum_1x_width = sum_1.sum()" }, { "code": null, "e": 11632, "s": 11348, "text": "In Figure 2, the different widths of the rectangles are given by the different XboxOne sales in the regions of interest. Although the sales percentages remain unchanged between the different consoles, the audience receives a very different message, particularly in the case of Japan." }, { "code": null, "e": 11707, "s": 11632, "text": "The same is true if the horizontal axis is segmented by PS4 console sales:" }, { "code": null, "e": 11862, "s": 11707, "text": "data = {\"PS4\" : df4['perc_ps4'], \"Nintendo\": df4['perc_nint'], \"Xbox\" : df4['perc_xbox'] }widths = sum_2x_width = sum_2.sum()" }, { "code": null, "e": 12119, "s": 11862, "text": "This is the main drawback with Marimekko charts: not only are they difficult to read and interpret because they are based on audiences’ ability to decode numerical information by comparing areas, but they can also mislead the audience to wrong conclusions." }, { "code": null, "e": 12226, "s": 12119, "text": "As Alberto Cairo wisely pointed out [4]: “Just as we can lie with statistics, we can also lie with charts”" }, { "code": null, "e": 12319, "s": 12226, "text": "If you find this article of interest, please read my previous (https://medium.com/@dar.wtz):" }, { "code": null, "e": 12378, "s": 12319, "text": "“Scatter Plots with Plotly Express, Trendlines & Faceting”" }, { "code": null, "e": 12401, "s": 12378, "text": "towardsdatascience.com" } ]
Python 3 - os.mkfifo() Method
The method mkfifo() create a FIFO named path with numeric mode. The default mode is 0666 (octal).The current umask value is first masked out. FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted Following is the syntax for mkfifo() method − os.mkfifo(path[, mode]) path − This is the path, which needs to be created. path − This is the path, which needs to be created. mode − This is the mode of the named path to be given. mode − This is the mode of the named path to be given. This method does not return any value. The following example shows the usage of mkfifo() method. # !/usr/bin/python3 import os, sys # Path to be created path = "/tmp/hourly" os.mkfifo( path, 0644 ) print ("Path is created") When we run the above program, it produces the following result − Path is created 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2482, "s": 2340, "text": "The method mkfifo() create a FIFO named path with numeric mode. The default mode is 0666 (octal).The current umask value is first masked out." }, { "code": null, "e": 2574, "s": 2482, "text": "FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted" }, { "code": null, "e": 2620, "s": 2574, "text": "Following is the syntax for mkfifo() method −" }, { "code": null, "e": 2645, "s": 2620, "text": "os.mkfifo(path[, mode])\n" }, { "code": null, "e": 2697, "s": 2645, "text": "path − This is the path, which needs to be created." }, { "code": null, "e": 2749, "s": 2697, "text": "path − This is the path, which needs to be created." }, { "code": null, "e": 2804, "s": 2749, "text": "mode − This is the mode of the named path to be given." }, { "code": null, "e": 2859, "s": 2804, "text": "mode − This is the mode of the named path to be given." }, { "code": null, "e": 2898, "s": 2859, "text": "This method does not return any value." }, { "code": null, "e": 2956, "s": 2898, "text": "The following example shows the usage of mkfifo() method." }, { "code": null, "e": 3085, "s": 2956, "text": "# !/usr/bin/python3\nimport os, sys\n\n# Path to be created\npath = \"/tmp/hourly\"\nos.mkfifo( path, 0644 )\n\nprint (\"Path is created\")" }, { "code": null, "e": 3151, "s": 3085, "text": "When we run the above program, it produces the following result −" }, { "code": null, "e": 3168, "s": 3151, "text": "Path is created\n" }, { "code": null, "e": 3205, "s": 3168, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3221, "s": 3205, "text": " Malhar Lathkar" }, { "code": null, "e": 3254, "s": 3221, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3273, "s": 3254, "text": " Arnab Chakraborty" }, { "code": null, "e": 3308, "s": 3273, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3330, "s": 3308, "text": " In28Minutes Official" }, { "code": null, "e": 3364, "s": 3330, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3392, "s": 3364, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3427, "s": 3392, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3441, "s": 3427, "text": " Lets Kode It" }, { "code": null, "e": 3474, "s": 3441, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3491, "s": 3474, "text": " Abhilash Nelson" }, { "code": null, "e": 3498, "s": 3491, "text": " Print" }, { "code": null, "e": 3509, "s": 3498, "text": " Add Notes" } ]
What does Integer.parseInt() method do in Java?
This is a static method of the class named Integer it accepts an integer parameter and Parses it as a signed decimal integer. Live Demo public class IntegerDemo { public static void main(String[] args) { // parses the string argument int a = Integer.parseInt("12"); int b = Integer.parseInt("26"); int c = Integer.parseInt("54"); int m = a * b * c; System.out.print("Value after multiplying = " + m); } } Value after multiplying = 16848
[ { "code": null, "e": 1188, "s": 1062, "text": "This is a static method of the class named Integer it accepts an integer parameter and Parses it as a signed decimal integer." }, { "code": null, "e": 1199, "s": 1188, "text": " Live Demo" }, { "code": null, "e": 1517, "s": 1199, "text": "public class IntegerDemo {\n public static void main(String[] args) {\n // parses the string argument\n int a = Integer.parseInt(\"12\");\n int b = Integer.parseInt(\"26\");\n int c = Integer.parseInt(\"54\");\n int m = a * b * c;\n \n System.out.print(\"Value after multiplying = \" + m);\n }\n}" }, { "code": null, "e": 1550, "s": 1517, "text": "Value after multiplying = 16848\n" } ]
How to get Day, Month and Year from Date in Java - GeeksforGeeks
12 Jul, 2021 Given a date in the form of a string, the task is to write a Java Program to get the day, month, and year from the given date. Examples: Input: date = “2020-07-18”Output:Day: 18Month: JulyYear: 2020Explanation: The given date is ‘2020-07-18’, so the day is: 18, the month is: July, and the year is: 2020. Input: date = “2018-05-10”Output:Day: 10Month: MayYear: 2018Explanation: The given date is ‘2018-05-10’, so the day is: 10, the month is: May, and the year is: 2018. Method 1: Using LocalDate class in Java: The idea is to use methods of LocalDate class to get the day, month, and year from the date. The getDayOfMonth() method returns the day represented by the given date, getMonth() method returns the month represented by the given date, and getYear() method returns the year represented by the given date. Below is the implementation of the above approach: Java // Java program for the above approachimport java.util.Date;import java.time.Month;import java.time.LocalDate; class GFG { // Function to get day, month, and // year from date public static void getDayMonthYear(String date) { // Get an instance of LocalTime // from date LocalDate currentDate = LocalDate.parse(date); // Get day from date int day = currentDate.getDayOfMonth(); // Get month from date Month month = currentDate.getMonth(); // Get year from date int year = currentDate.getYear(); // Print the day, month, and year System.out.println("Day: " + day); System.out.println("Month: " + month); System.out.println("Year: " + year); } // Driver Code public static void main(String args[]) { // Given Date String date = "2020-07-18"; // Function Call getDayMonthYear(date); }} Day: 18 Month: JULY Year: 2020 Method 2: Using Calendar class in Java: The idea is to use get() method of Calendar class to get the day, month, and year from the date. The get() method takes one parameter of integer type and returns the value of the passed field from the given date. It returns the month index instead of the month name. Below is the implementation of the above approach: Java // Java program for the above approachimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { // Creating a calendar object Calendar cal = new GregorianCalendar( 2020, 07, 18); // Getting the values of day, // month, and year from calendar // object int day = cal.get(Calendar.DAY_OF_MONTH); int month = cal.get(Calendar.MONTH); int year = cal.get(Calendar.YEAR); // Printing the day, month, and year System.out.println("Day: " + day); System.out.println("Month: " + month); System.out.println("Year: " + year); }} Day: 18 Month: 7 Year: 2020 Method 3: Using String.split() in Java: The idea is to use the split() method of String class.It splits a string according to the pattern provided and returns an array of string. The idea is to use the split() method of String class. It splits a string according to the pattern provided and returns an array of string. Below is the implementation of the above approach: Java // Java program for the above approachclass GFG { // Function to get day, month, and // year from date public static void findDate(String date) { // Splitting the given date by '-' String dateParts[] = date.split("-"); // Getting day, month, and year // from date String day = dateParts[0]; String month = dateParts[1]; String year = dateParts[2]; // Printing the day, month, and year System.out.println("Day: " + day); System.out.println("Month: " + month); System.out.println("Year: " + year); } // Driver Code public static void main(String args[]) { // Given date String date = "18-07-2020"; findDate(date); }} Day: 18 Month: 07 Year: 2020 gabaa406 date-time-program Java-Date-Time Java-DateFormat Java-LocalDate Java-LocalDateTime strings Java Programs Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Iterate HashMap in Java? Iterate through List in Java Factory method design pattern in Java Min Heap in Java Java Program to Remove Duplicate Elements From the Array Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 24680, "s": 24652, "text": "\n12 Jul, 2021" }, { "code": null, "e": 24807, "s": 24680, "text": "Given a date in the form of a string, the task is to write a Java Program to get the day, month, and year from the given date." }, { "code": null, "e": 24817, "s": 24807, "text": "Examples:" }, { "code": null, "e": 24985, "s": 24817, "text": "Input: date = “2020-07-18”Output:Day: 18Month: JulyYear: 2020Explanation: The given date is ‘2020-07-18’, so the day is: 18, the month is: July, and the year is: 2020." }, { "code": null, "e": 25151, "s": 24985, "text": "Input: date = “2018-05-10”Output:Day: 10Month: MayYear: 2018Explanation: The given date is ‘2018-05-10’, so the day is: 10, the month is: May, and the year is: 2018." }, { "code": null, "e": 25192, "s": 25151, "text": "Method 1: Using LocalDate class in Java:" }, { "code": null, "e": 25285, "s": 25192, "text": "The idea is to use methods of LocalDate class to get the day, month, and year from the date." }, { "code": null, "e": 25495, "s": 25285, "text": "The getDayOfMonth() method returns the day represented by the given date, getMonth() method returns the month represented by the given date, and getYear() method returns the year represented by the given date." }, { "code": null, "e": 25546, "s": 25495, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25551, "s": 25546, "text": "Java" }, { "code": "// Java program for the above approachimport java.util.Date;import java.time.Month;import java.time.LocalDate; class GFG { // Function to get day, month, and // year from date public static void getDayMonthYear(String date) { // Get an instance of LocalTime // from date LocalDate currentDate = LocalDate.parse(date); // Get day from date int day = currentDate.getDayOfMonth(); // Get month from date Month month = currentDate.getMonth(); // Get year from date int year = currentDate.getYear(); // Print the day, month, and year System.out.println(\"Day: \" + day); System.out.println(\"Month: \" + month); System.out.println(\"Year: \" + year); } // Driver Code public static void main(String args[]) { // Given Date String date = \"2020-07-18\"; // Function Call getDayMonthYear(date); }}", "e": 26502, "s": 25551, "text": null }, { "code": null, "e": 26536, "s": 26505, "text": "Day: 18\nMonth: JULY\nYear: 2020" }, { "code": null, "e": 26580, "s": 26540, "text": "Method 2: Using Calendar class in Java:" }, { "code": null, "e": 26679, "s": 26582, "text": "The idea is to use get() method of Calendar class to get the day, month, and year from the date." }, { "code": null, "e": 26795, "s": 26679, "text": "The get() method takes one parameter of integer type and returns the value of the passed field from the given date." }, { "code": null, "e": 26849, "s": 26795, "text": "It returns the month index instead of the month name." }, { "code": null, "e": 26902, "s": 26851, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26909, "s": 26904, "text": "Java" }, { "code": "// Java program for the above approachimport java.util.*; class GFG { // Driver Code public static void main(String args[]) { // Creating a calendar object Calendar cal = new GregorianCalendar( 2020, 07, 18); // Getting the values of day, // month, and year from calendar // object int day = cal.get(Calendar.DAY_OF_MONTH); int month = cal.get(Calendar.MONTH); int year = cal.get(Calendar.YEAR); // Printing the day, month, and year System.out.println(\"Day: \" + day); System.out.println(\"Month: \" + month); System.out.println(\"Year: \" + year); }}", "e": 27581, "s": 26909, "text": null }, { "code": null, "e": 27612, "s": 27584, "text": "Day: 18\nMonth: 7\nYear: 2020" }, { "code": null, "e": 27656, "s": 27616, "text": "Method 3: Using String.split() in Java:" }, { "code": null, "e": 27797, "s": 27658, "text": "The idea is to use the split() method of String class.It splits a string according to the pattern provided and returns an array of string." }, { "code": null, "e": 27852, "s": 27797, "text": "The idea is to use the split() method of String class." }, { "code": null, "e": 27937, "s": 27852, "text": "It splits a string according to the pattern provided and returns an array of string." }, { "code": null, "e": 27990, "s": 27939, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27997, "s": 27992, "text": "Java" }, { "code": "// Java program for the above approachclass GFG { // Function to get day, month, and // year from date public static void findDate(String date) { // Splitting the given date by '-' String dateParts[] = date.split(\"-\"); // Getting day, month, and year // from date String day = dateParts[0]; String month = dateParts[1]; String year = dateParts[2]; // Printing the day, month, and year System.out.println(\"Day: \" + day); System.out.println(\"Month: \" + month); System.out.println(\"Year: \" + year); } // Driver Code public static void main(String args[]) { // Given date String date = \"18-07-2020\"; findDate(date); }}", "e": 28745, "s": 27997, "text": null }, { "code": null, "e": 28777, "s": 28748, "text": "Day: 18\nMonth: 07\nYear: 2020" }, { "code": null, "e": 28790, "s": 28781, "text": "gabaa406" }, { "code": null, "e": 28808, "s": 28790, "text": "date-time-program" }, { "code": null, "e": 28823, "s": 28808, "text": "Java-Date-Time" }, { "code": null, "e": 28839, "s": 28823, "text": "Java-DateFormat" }, { "code": null, "e": 28854, "s": 28839, "text": "Java-LocalDate" }, { "code": null, "e": 28873, "s": 28854, "text": "Java-LocalDateTime" }, { "code": null, "e": 28881, "s": 28873, "text": "strings" }, { "code": null, "e": 28895, "s": 28881, "text": "Java Programs" }, { "code": null, "e": 28903, "s": 28895, "text": "Strings" }, { "code": null, "e": 28911, "s": 28903, "text": "Strings" }, { "code": null, "e": 29009, "s": 28911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29041, "s": 29009, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 29070, "s": 29041, "text": "Iterate through List in Java" }, { "code": null, "e": 29108, "s": 29070, "text": "Factory method design pattern in Java" }, { "code": null, "e": 29125, "s": 29108, "text": "Min Heap in Java" }, { "code": null, "e": 29182, "s": 29125, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 29228, "s": 29182, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 29253, "s": 29228, "text": "Reverse a string in Java" }, { "code": null, "e": 29287, "s": 29253, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 29347, "s": 29287, "text": "Write a program to print all permutations of a given string" } ]
A Step by Step Guide to Web Scraping in Python | by Sara A. Metwalli | Towards Data Science
As data scientists, we are always on the look for new data and information to analyze and manipulate. One of the main approaches to find data right now is scraping the web for a particular inquiry. When we browse the internet, we come across a massive number of websites, these websites display various data on the browser. If we, for some reason want to use this data for a project or an ML algorithm, we can — but shouldn’t — gather this data manually. So, we will copy the sections we want and paste them in a doc or CSV file. towardsdatascience.com Needless to say, that will be quite a tedious task. That’s why most data scientists and developers go with web scraping using code. It’s easy to write code to extract data from a 100 webpage than do them by hand. Web Scraping is the technique used by programmers to automate the process of finding and extracting data from the internet within a relatively short time. The most important question when it comes to web scraping, is it legal? Short answer, yes. The more detailed answer, scraping publically available data for non-commercial purposes was announced to be completely legal in late January 2020. You might wonder, what does publically available mean? Publically available information is the information that anyone can see/ find on the internet without the need for special access. So, information on Wikipedia, social media or Google’s search results are examples of publically available data. Now, social media is somewhat complicated, because there are parts of it that are not publically available, such as when a user sets their information to be private. In this case, this information is illegal to be scraped. One last thing, there’s a difference between publically available and copyrighted. For example, you can scrap YouTube for video titles, but you can’t use the videos for commercial use because they are copyrighted. There are different programming languages that you can use to scrape the web, and within every programming language, there are different libraries to achieve the same goal. So, what to use? In this article, I will use Python, Requests, and BeautifulSoup to scrap some pages from Wikipedia. To scrap and extract any information from the internet, you’ll probably need to go through three stages: Fetching HTML, Obtaining HTML Tree, then Extracting information from the tree. We will use the Requests library to fetch the HTML code from a specific URL. Then, we will use BeautifulSoup to Parse and Extract the HTML tree, and finally, we will use pure Python to organize the data. Before we get scraping, let’s revise HTML basics quickly. Everything in HTML is defined within tags. The most important tag is <HTML> which means that the text to follow is HTML code. In HTML, each opened tag must be closed. So, at the end of the HTML file, we need a closure tag </HTML>. Different tags in HTML means different things. Using a combination of tags, a webpage is represented. Any text enclosed between an open and close tag is called inner HTML text. If we have multiple elements with the same tag, we might — actually, always — want to differentiate between them somehow. There are two ways to do that, either through using classes or ids. Ids are unique, which means we can’t have two elements with the same id. Classes, on the other hand, are not. More than one element can have the same class. Here are 10 HTML tags you will see a lot when scraping the web. Awesome, now that we know the basics, let’s start up small and then build up! Our first step is to install BeautifulSoup by typing the following in the command line. pip install bs4 To get familiar with scraping basics, we will consider an example HTML code and learn how to use BeautifulSoup to explore it. BeautifulSoup doesn’t fetch HTML from the web, it is, however, extremely good at extracting information from an HTML string. In order to use the above HTML in Python, we will set it up as a string and then use different BeautifulSoup to explore it. Note: if you’re using Jupyter Notebook to follow this article, you can type the following command to view HTML within the Notebook. from IPython.core.display import display, HTMLdisplay(HTML(some_html_str)) For example, the above HTML will look something like this: Next, we need to feed this HTML to BeautifulSoup in order to generate the HTML tree. HTML tree is a representation of the different levels of the HTML code, it shows the hierarchy of the code. The HTML tree of the above code is: To generate the tree, we write some_html_str = """<HTML> <HEAD> <TITLE>My cool title</TITLE> </HEAD><BODY> <H1>This is a Header</H1> <ul id="list" class="coolList"> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul></BODY></HTML>"""#Feed the HTML to BeautifulSoupsoup = bs(some_html_str) The variable soup now has the information extracted from the HTML string. We can use this variable to obtain information from the HTML tree. BeautifulSoup has many functions that can be used to extract specific aspects of the HTML string. However, two functions are used to most: find and find_all. The function find returns only the first occurrence of the search query, while find_all returns a list of all matches. Say, we are searching for all <h1> headers in the code. As you can see, the find function gave me the <h1> tag. With the tags and all. Often, we only want to extract the inner HTML text. To do that we use .text . That was simply because we only have one <h1> tag. But what if we want to look for list items — we have an unordered list with three items in our example — we can’t use find. If we do, we will only get the first item. To find all the list items, we need to use find_all. Okay, now that we have a list of items, let’s answer two questions: 1- How to get the inner HTML of the list items? To obtain the inner text only, we can’t use .text straight away, because now we have a list of elements and not just one. Hence, we need to iterate over the list and obtain the inner HTML of each list item. 2- What if we have multiple lists in the code? If we have more than one list in the code — which is usually the case — we can be precise when searching for elements. In our example, the list has id=’list’ and class=’coolList’. We can use this — both or just one — with the find_all or find functions to be precise and get the information we want. One thing to note here is the return of the find or find_all functions are BeautifulSoup objects and those can be traversed further. So, we can treat them just like the object obtained directly from the HTML string. Complete code for this section: We can traverse the HTML tree using other BeautifulSoup functions, like children, parent, next, etc. Let’s consider a more realistic example, where we fetch the HTML from a URL and then use BeautifulSoup to extract patterns and data. We will start by fetching one webpage. I love coffee, so let’s try fetching the Wikipedia page listing countries by coffee production and then plot the countries using Pygal. towardsdatascience.com To fetch the HTML we will use the Requests library and then pass the fetched HTML to BeautifulSoup. If we opened this wiki page, we will find a big table with the countries, and different measures of coffee production. We just want to extract the country name and the coffee production in tons. To extract this information, we need to study the HTML of the page to know what to query. We can just highlight a country name, right-click, and choose inspect. Through inspecting the page, we can see that the country names and the quantity are enclosed within a ‘table’ tag. Since it is the first table on the page, we can just use the find function to extract it. However, extracting the table directly will give us all the table’s content, with the table header — the first row of the table — and the quantity in different measures. So, we need to fine-tune our search. Let’s try it out with the top 10 countries. Notice that to clean up the results, I used string manipulation to extract the information I want. towardsdatascience.com I can use this list to finally plot the top 10 countries using Pygal. Complete code for this section: Wow, that was a lot! 😃 But, we yet to write code that scraps different webpages. For this section, we will scrap the wiki page with the best 100 books of all time, and then we will categorize these books based on their genre. Trying to see if we can find a relation between the genre and the list — which genre performed best. The wiki page contains links to each of the 100 books as well as their authors. We want our code to navigate the list, go to the book wiki page, extract info like genre, name, author, and publishing year and then store this info in a Python dictionary — you can store the data in a Pandas frame as well. So, to do this we need a couple of steps: Fetch the main URL HTML code.Feed that HTML to BeautifulSoup.Extract each book from the list and get the wiki link of each book.Obtain data for each book.Get all books data, clean, and plot final results. Fetch the main URL HTML code. Feed that HTML to BeautifulSoup. Extract each book from the list and get the wiki link of each book. Obtain data for each book. Get all books data, clean, and plot final results. Let’s get started... Step #1: Fetch main URL HTML code url = 'https://en.wikipedia.org/wiki/Time%27s_List_of_the_100_Best_Novels'page = rq.get(url).text Step #2: Feed that HTML to BeautifulSoup soup = bs(page) Step #3: Extract each book from the list and get the wiki link of each book rows = soup.find('table').find_all('tr')[1:]books_links = [row.find('a')['href'] for row in rows]base_url = 'https://en.wikipedia.org'books_urls = [base_url + link for link in books_links] Step #4: Obtain data for each book This is the most lengthy and important step. We will first consider only one book, assume it’s the first one in the list. If we open the wiki page of the book we will see the different information of the book enclosed in a table on the right side of the screen. Going through the HTML we can see where everything is stored. To make things easier and more efficient, I wrote custom functions to extract different information from the book’s wiki. Now, that we have these cool functions, let’s write a function to use these functions, this will help us with the automation. In this function, I used the try..except formate to avoid crashing if some of the book's info is missing. Step #5: Get all books data, clean, and plot final results We have all we need to automate the code and run it. One last thing to note: It is legal to scrap Wikipedia, however, they don’t like it when you scrap more than one page each second. So we will need to add pauses between each fetch to avoid breaking the server. Data collected! this will take 100 seconds to finish, so feel free to do something else while you wait 😉 Finally, let’s clean the data, get the genre count, and plot the results. And we are done! I have to say, collecting data is not always a 100% accurate, as you can see in the plot, the longest bar belongs to the ‘None’ value. Which means one of two things Either the wiki page didn’t include the book’s genre.Or, the code for that specific book is different than the rest. Either the wiki page didn’t include the book’s genre. Or, the code for that specific book is different than the rest. That’s why after automating the data collection, we often go through the weird and unusual results and recheck them manually. Web scraping is one of the essential skills a data scientist needs. And it can’t be any easier than with using Python, Requests, and BeautifulSoup. We can never trust full automation, sometimes we will need to go through the final result a recheck for abnormal information manually. The full code for the books section:
[ { "code": null, "e": 245, "s": 47, "text": "As data scientists, we are always on the look for new data and information to analyze and manipulate. One of the main approaches to find data right now is scraping the web for a particular inquiry." }, { "code": null, "e": 577, "s": 245, "text": "When we browse the internet, we come across a massive number of websites, these websites display various data on the browser. If we, for some reason want to use this data for a project or an ML algorithm, we can — but shouldn’t — gather this data manually. So, we will copy the sections we want and paste them in a doc or CSV file." }, { "code": null, "e": 600, "s": 577, "text": "towardsdatascience.com" }, { "code": null, "e": 813, "s": 600, "text": "Needless to say, that will be quite a tedious task. That’s why most data scientists and developers go with web scraping using code. It’s easy to write code to extract data from a 100 webpage than do them by hand." }, { "code": null, "e": 968, "s": 813, "text": "Web Scraping is the technique used by programmers to automate the process of finding and extracting data from the internet within a relatively short time." }, { "code": null, "e": 1040, "s": 968, "text": "The most important question when it comes to web scraping, is it legal?" }, { "code": null, "e": 1059, "s": 1040, "text": "Short answer, yes." }, { "code": null, "e": 1207, "s": 1059, "text": "The more detailed answer, scraping publically available data for non-commercial purposes was announced to be completely legal in late January 2020." }, { "code": null, "e": 1262, "s": 1207, "text": "You might wonder, what does publically available mean?" }, { "code": null, "e": 1506, "s": 1262, "text": "Publically available information is the information that anyone can see/ find on the internet without the need for special access. So, information on Wikipedia, social media or Google’s search results are examples of publically available data." }, { "code": null, "e": 1729, "s": 1506, "text": "Now, social media is somewhat complicated, because there are parts of it that are not publically available, such as when a user sets their information to be private. In this case, this information is illegal to be scraped." }, { "code": null, "e": 1943, "s": 1729, "text": "One last thing, there’s a difference between publically available and copyrighted. For example, you can scrap YouTube for video titles, but you can’t use the videos for commercial use because they are copyrighted." }, { "code": null, "e": 2116, "s": 1943, "text": "There are different programming languages that you can use to scrape the web, and within every programming language, there are different libraries to achieve the same goal." }, { "code": null, "e": 2133, "s": 2116, "text": "So, what to use?" }, { "code": null, "e": 2233, "s": 2133, "text": "In this article, I will use Python, Requests, and BeautifulSoup to scrap some pages from Wikipedia." }, { "code": null, "e": 2417, "s": 2233, "text": "To scrap and extract any information from the internet, you’ll probably need to go through three stages: Fetching HTML, Obtaining HTML Tree, then Extracting information from the tree." }, { "code": null, "e": 2621, "s": 2417, "text": "We will use the Requests library to fetch the HTML code from a specific URL. Then, we will use BeautifulSoup to Parse and Extract the HTML tree, and finally, we will use pure Python to organize the data." }, { "code": null, "e": 2805, "s": 2621, "text": "Before we get scraping, let’s revise HTML basics quickly. Everything in HTML is defined within tags. The most important tag is <HTML> which means that the text to follow is HTML code." }, { "code": null, "e": 2910, "s": 2805, "text": "In HTML, each opened tag must be closed. So, at the end of the HTML file, we need a closure tag </HTML>." }, { "code": null, "e": 3087, "s": 2910, "text": "Different tags in HTML means different things. Using a combination of tags, a webpage is represented. Any text enclosed between an open and close tag is called inner HTML text." }, { "code": null, "e": 3434, "s": 3087, "text": "If we have multiple elements with the same tag, we might — actually, always — want to differentiate between them somehow. There are two ways to do that, either through using classes or ids. Ids are unique, which means we can’t have two elements with the same id. Classes, on the other hand, are not. More than one element can have the same class." }, { "code": null, "e": 3498, "s": 3434, "text": "Here are 10 HTML tags you will see a lot when scraping the web." }, { "code": null, "e": 3576, "s": 3498, "text": "Awesome, now that we know the basics, let’s start up small and then build up!" }, { "code": null, "e": 3664, "s": 3576, "text": "Our first step is to install BeautifulSoup by typing the following in the command line." }, { "code": null, "e": 3680, "s": 3664, "text": "pip install bs4" }, { "code": null, "e": 3806, "s": 3680, "text": "To get familiar with scraping basics, we will consider an example HTML code and learn how to use BeautifulSoup to explore it." }, { "code": null, "e": 3931, "s": 3806, "text": "BeautifulSoup doesn’t fetch HTML from the web, it is, however, extremely good at extracting information from an HTML string." }, { "code": null, "e": 4055, "s": 3931, "text": "In order to use the above HTML in Python, we will set it up as a string and then use different BeautifulSoup to explore it." }, { "code": null, "e": 4187, "s": 4055, "text": "Note: if you’re using Jupyter Notebook to follow this article, you can type the following command to view HTML within the Notebook." }, { "code": null, "e": 4262, "s": 4187, "text": "from IPython.core.display import display, HTMLdisplay(HTML(some_html_str))" }, { "code": null, "e": 4321, "s": 4262, "text": "For example, the above HTML will look something like this:" }, { "code": null, "e": 4514, "s": 4321, "text": "Next, we need to feed this HTML to BeautifulSoup in order to generate the HTML tree. HTML tree is a representation of the different levels of the HTML code, it shows the hierarchy of the code." }, { "code": null, "e": 4550, "s": 4514, "text": "The HTML tree of the above code is:" }, { "code": null, "e": 4581, "s": 4550, "text": "To generate the tree, we write" }, { "code": null, "e": 4884, "s": 4581, "text": "some_html_str = \"\"\"<HTML> <HEAD> <TITLE>My cool title</TITLE> </HEAD><BODY> <H1>This is a Header</H1> <ul id=\"list\" class=\"coolList\"> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul></BODY></HTML>\"\"\"#Feed the HTML to BeautifulSoupsoup = bs(some_html_str)" }, { "code": null, "e": 5025, "s": 4884, "text": "The variable soup now has the information extracted from the HTML string. We can use this variable to obtain information from the HTML tree." }, { "code": null, "e": 5183, "s": 5025, "text": "BeautifulSoup has many functions that can be used to extract specific aspects of the HTML string. However, two functions are used to most: find and find_all." }, { "code": null, "e": 5302, "s": 5183, "text": "The function find returns only the first occurrence of the search query, while find_all returns a list of all matches." }, { "code": null, "e": 5358, "s": 5302, "text": "Say, we are searching for all <h1> headers in the code." }, { "code": null, "e": 5515, "s": 5358, "text": "As you can see, the find function gave me the <h1> tag. With the tags and all. Often, we only want to extract the inner HTML text. To do that we use .text ." }, { "code": null, "e": 5733, "s": 5515, "text": "That was simply because we only have one <h1> tag. But what if we want to look for list items — we have an unordered list with three items in our example — we can’t use find. If we do, we will only get the first item." }, { "code": null, "e": 5786, "s": 5733, "text": "To find all the list items, we need to use find_all." }, { "code": null, "e": 5854, "s": 5786, "text": "Okay, now that we have a list of items, let’s answer two questions:" }, { "code": null, "e": 5902, "s": 5854, "text": "1- How to get the inner HTML of the list items?" }, { "code": null, "e": 6109, "s": 5902, "text": "To obtain the inner text only, we can’t use .text straight away, because now we have a list of elements and not just one. Hence, we need to iterate over the list and obtain the inner HTML of each list item." }, { "code": null, "e": 6156, "s": 6109, "text": "2- What if we have multiple lists in the code?" }, { "code": null, "e": 6456, "s": 6156, "text": "If we have more than one list in the code — which is usually the case — we can be precise when searching for elements. In our example, the list has id=’list’ and class=’coolList’. We can use this — both or just one — with the find_all or find functions to be precise and get the information we want." }, { "code": null, "e": 6672, "s": 6456, "text": "One thing to note here is the return of the find or find_all functions are BeautifulSoup objects and those can be traversed further. So, we can treat them just like the object obtained directly from the HTML string." }, { "code": null, "e": 6704, "s": 6672, "text": "Complete code for this section:" }, { "code": null, "e": 6805, "s": 6704, "text": "We can traverse the HTML tree using other BeautifulSoup functions, like children, parent, next, etc." }, { "code": null, "e": 6938, "s": 6805, "text": "Let’s consider a more realistic example, where we fetch the HTML from a URL and then use BeautifulSoup to extract patterns and data." }, { "code": null, "e": 7113, "s": 6938, "text": "We will start by fetching one webpage. I love coffee, so let’s try fetching the Wikipedia page listing countries by coffee production and then plot the countries using Pygal." }, { "code": null, "e": 7136, "s": 7113, "text": "towardsdatascience.com" }, { "code": null, "e": 7236, "s": 7136, "text": "To fetch the HTML we will use the Requests library and then pass the fetched HTML to BeautifulSoup." }, { "code": null, "e": 7431, "s": 7236, "text": "If we opened this wiki page, we will find a big table with the countries, and different measures of coffee production. We just want to extract the country name and the coffee production in tons." }, { "code": null, "e": 7592, "s": 7431, "text": "To extract this information, we need to study the HTML of the page to know what to query. We can just highlight a country name, right-click, and choose inspect." }, { "code": null, "e": 7797, "s": 7592, "text": "Through inspecting the page, we can see that the country names and the quantity are enclosed within a ‘table’ tag. Since it is the first table on the page, we can just use the find function to extract it." }, { "code": null, "e": 7967, "s": 7797, "text": "However, extracting the table directly will give us all the table’s content, with the table header — the first row of the table — and the quantity in different measures." }, { "code": null, "e": 8048, "s": 7967, "text": "So, we need to fine-tune our search. Let’s try it out with the top 10 countries." }, { "code": null, "e": 8147, "s": 8048, "text": "Notice that to clean up the results, I used string manipulation to extract the information I want." }, { "code": null, "e": 8170, "s": 8147, "text": "towardsdatascience.com" }, { "code": null, "e": 8240, "s": 8170, "text": "I can use this list to finally plot the top 10 countries using Pygal." }, { "code": null, "e": 8272, "s": 8240, "text": "Complete code for this section:" }, { "code": null, "e": 8295, "s": 8272, "text": "Wow, that was a lot! 😃" }, { "code": null, "e": 8353, "s": 8295, "text": "But, we yet to write code that scraps different webpages." }, { "code": null, "e": 8599, "s": 8353, "text": "For this section, we will scrap the wiki page with the best 100 books of all time, and then we will categorize these books based on their genre. Trying to see if we can find a relation between the genre and the list — which genre performed best." }, { "code": null, "e": 8903, "s": 8599, "text": "The wiki page contains links to each of the 100 books as well as their authors. We want our code to navigate the list, go to the book wiki page, extract info like genre, name, author, and publishing year and then store this info in a Python dictionary — you can store the data in a Pandas frame as well." }, { "code": null, "e": 8945, "s": 8903, "text": "So, to do this we need a couple of steps:" }, { "code": null, "e": 9150, "s": 8945, "text": "Fetch the main URL HTML code.Feed that HTML to BeautifulSoup.Extract each book from the list and get the wiki link of each book.Obtain data for each book.Get all books data, clean, and plot final results." }, { "code": null, "e": 9180, "s": 9150, "text": "Fetch the main URL HTML code." }, { "code": null, "e": 9213, "s": 9180, "text": "Feed that HTML to BeautifulSoup." }, { "code": null, "e": 9281, "s": 9213, "text": "Extract each book from the list and get the wiki link of each book." }, { "code": null, "e": 9308, "s": 9281, "text": "Obtain data for each book." }, { "code": null, "e": 9359, "s": 9308, "text": "Get all books data, clean, and plot final results." }, { "code": null, "e": 9380, "s": 9359, "text": "Let’s get started..." }, { "code": null, "e": 9414, "s": 9380, "text": "Step #1: Fetch main URL HTML code" }, { "code": null, "e": 9512, "s": 9414, "text": "url = 'https://en.wikipedia.org/wiki/Time%27s_List_of_the_100_Best_Novels'page = rq.get(url).text" }, { "code": null, "e": 9553, "s": 9512, "text": "Step #2: Feed that HTML to BeautifulSoup" }, { "code": null, "e": 9569, "s": 9553, "text": "soup = bs(page)" }, { "code": null, "e": 9645, "s": 9569, "text": "Step #3: Extract each book from the list and get the wiki link of each book" }, { "code": null, "e": 9834, "s": 9645, "text": "rows = soup.find('table').find_all('tr')[1:]books_links = [row.find('a')['href'] for row in rows]base_url = 'https://en.wikipedia.org'books_urls = [base_url + link for link in books_links]" }, { "code": null, "e": 9869, "s": 9834, "text": "Step #4: Obtain data for each book" }, { "code": null, "e": 10131, "s": 9869, "text": "This is the most lengthy and important step. We will first consider only one book, assume it’s the first one in the list. If we open the wiki page of the book we will see the different information of the book enclosed in a table on the right side of the screen." }, { "code": null, "e": 10193, "s": 10131, "text": "Going through the HTML we can see where everything is stored." }, { "code": null, "e": 10315, "s": 10193, "text": "To make things easier and more efficient, I wrote custom functions to extract different information from the book’s wiki." }, { "code": null, "e": 10441, "s": 10315, "text": "Now, that we have these cool functions, let’s write a function to use these functions, this will help us with the automation." }, { "code": null, "e": 10547, "s": 10441, "text": "In this function, I used the try..except formate to avoid crashing if some of the book's info is missing." }, { "code": null, "e": 10606, "s": 10547, "text": "Step #5: Get all books data, clean, and plot final results" }, { "code": null, "e": 10659, "s": 10606, "text": "We have all we need to automate the code and run it." }, { "code": null, "e": 10869, "s": 10659, "text": "One last thing to note: It is legal to scrap Wikipedia, however, they don’t like it when you scrap more than one page each second. So we will need to add pauses between each fetch to avoid breaking the server." }, { "code": null, "e": 10974, "s": 10869, "text": "Data collected! this will take 100 seconds to finish, so feel free to do something else while you wait 😉" }, { "code": null, "e": 11048, "s": 10974, "text": "Finally, let’s clean the data, get the genre count, and plot the results." }, { "code": null, "e": 11065, "s": 11048, "text": "And we are done!" }, { "code": null, "e": 11230, "s": 11065, "text": "I have to say, collecting data is not always a 100% accurate, as you can see in the plot, the longest bar belongs to the ‘None’ value. Which means one of two things" }, { "code": null, "e": 11347, "s": 11230, "text": "Either the wiki page didn’t include the book’s genre.Or, the code for that specific book is different than the rest." }, { "code": null, "e": 11401, "s": 11347, "text": "Either the wiki page didn’t include the book’s genre." }, { "code": null, "e": 11465, "s": 11401, "text": "Or, the code for that specific book is different than the rest." }, { "code": null, "e": 11591, "s": 11465, "text": "That’s why after automating the data collection, we often go through the weird and unusual results and recheck them manually." }, { "code": null, "e": 11739, "s": 11591, "text": "Web scraping is one of the essential skills a data scientist needs. And it can’t be any easier than with using Python, Requests, and BeautifulSoup." }, { "code": null, "e": 11874, "s": 11739, "text": "We can never trust full automation, sometimes we will need to go through the final result a recheck for abnormal information manually." } ]
Merge two sorted linked lists - GeeksforGeeks
12 Apr, 2022 Write a SortedMerge() function that takes two lists, each of which is sorted in increasing order, and merges the two together into one list which is in increasing order. SortedMerge() should return the new list. The new list should be made by splicing together the nodes of the first two lists. For example if the first linked list a is 5->10->15 and the other linked list b is 2->3->20, then SortedMerge() should return a pointer to the head node of the merged list 2->3->5->10->15->20. There are many cases to deal with: either ‘a’ or ‘b’ may be empty, during processing either ‘a’ or ‘b’ may run out first, and finally, there’s the problem of starting the result list empty, and building it up while going through ‘a’ and ‘b’. Method 1 (Using Dummy Nodes) The strategy here uses a temporary dummy node as the start of the result list. The pointer Tail always points to the last node in the result list, so appending new nodes is easy. The dummy node gives the tail something to point to initially when the result list is empty. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either ‘a’ or ‘b’, and adding it to the tail. When We are done, the result is in dummy.next. The below image is a dry run of the above approach: Below is the implementation of the above approach: C++ C Java Python3 C# Javascript /* C++ program to merge two sorted linked lists */#include <bits/stdc++.h>using namespace std; /* Link list node */class Node{ public: int data; Node* next;}; /* pull off the front node ofthe source and put it in dest */void MoveNode(Node** destRef, Node** sourceRef); /* Takes two lists sorted in increasingorder, and splices their nodes togetherto make one big sorted list whichis returned. */Node* SortedMerge(Node* a, Node* b){ /* a dummy first node to hang the result on */ Node dummy; /* tail points to the last result node */ Node* tail = &dummy; /* so tail->next is the place to add new nodes to the result. */ dummy.next = NULL; while (1) { if (a == NULL) { /* if either list runs out, use the other list */ tail->next = b; break; } else if (b == NULL) { tail->next = a; break; } if (a->data <= b->data) MoveNode(&(tail->next), &a); else MoveNode(&(tail->next), &b); tail = tail->next; } return(dummy.next);} /* UTILITY FUNCTIONS *//* MoveNode() function takes thenode from the front of the source,and move it to the front of the dest.It is an error to call this with thesource list empty. Before calling MoveNode():source == {1, 2, 3}dest == {1, 2, 3} After calling MoveNode():source == {2, 3}dest == {1, 1, 2, 3} */void MoveNode(Node** destRef, Node** sourceRef){ /* the front source node */ Node* newNode = *sourceRef; assert(newNode != NULL); /* Advance the source pointer */ *sourceRef = newNode->next; /* Link the old dest off the new node */ newNode->next = *destRef; /* Move dest to point to the new node */ *destRef = newNode;} /* Function to insert a node at the beginning of the linked list */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(Node *node){ while (node!=NULL) { cout<<node->data<<" "; node = node->next; }} /* Driver code*/int main(){ /* Start with the empty list */ Node* res = NULL; Node* a = NULL; Node* b = NULL; /* Let us create two sorted linked lists to test the functions Created lists, a: 5->10->15, b: 2->3->20 */ push(&a, 15); push(&a, 10); push(&a, 5); push(&b, 20); push(&b, 3); push(&b, 2); /* Remove duplicates from linked list */ res = SortedMerge(a, b); cout << "Merged Linked List is: \n"; printList(res); return 0;} // This code is contributed by rathbhupendra /* C program to merge two sorted linked lists */#include<stdio.h>#include<stdlib.h>#include<assert.h> /* Link list node */struct Node{ int data; struct Node* next;}; /* pull off the front node of the source and put it in dest */void MoveNode(struct Node** destRef, struct Node** sourceRef); /* Takes two lists sorted in increasing order, and splices their nodes together to make one big sorted list which is returned. */struct Node* SortedMerge(struct Node* a, struct Node* b){ /* a dummy first node to hang the result on */ struct Node dummy; /* tail points to the last result node */ struct Node* tail = &dummy; /* so tail->next is the place to add new nodes to the result. */ dummy.next = NULL; while (1) { if (a == NULL) { /* if either list runs out, use the other list */ tail->next = b; break; } else if (b == NULL) { tail->next = a; break; } if (a->data <= b->data) MoveNode(&(tail->next), &a); else MoveNode(&(tail->next), &b); tail = tail->next; } return(dummy.next);} /* UTILITY FUNCTIONS *//* MoveNode() function takes the node from the front of the source, and move it to the front of the dest. It is an error to call this with the source list empty. Before calling MoveNode(): source == {1, 2, 3} dest == {1, 2, 3} After calling MoveNode(): source == {2, 3} dest == {1, 1, 2, 3} */void MoveNode(struct Node** destRef, struct Node** sourceRef){ /* the front source node */ struct Node* newNode = *sourceRef; assert(newNode != NULL); /* Advance the source pointer */ *sourceRef = newNode->next; /* Link the old dest off the new node */ newNode->next = *destRef; /* Move dest to point to the new node */ *destRef = newNode;} /* Function to insert a node at the beginning of the linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node *node){ while (node!=NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* res = NULL; struct Node* a = NULL; struct Node* b = NULL; /* Let us create two sorted linked lists to test the functions Created lists, a: 5->10->15, b: 2->3->20 */ push(&a, 15); push(&a, 10); push(&a, 5); push(&b, 20); push(&b, 3); push(&b, 2); /* Remove duplicates from linked list */ res = SortedMerge(a, b); printf("Merged Linked List is: \n"); printList(res); return 0;} /* Java program to merge two sorted linked lists */import java.util.*; /* Link list node */class Node{ int data; Node next; Node(int d) {data = d; next = null;}} class MergeLists{Node head; /* Method to insert a node at the end of the linked list */public void addToTheLast(Node node){ if (head == null) { head = node; } else { Node temp = head; while (temp.next != null) temp = temp.next; temp.next = node; }} /* Method to print linked list */void printList(){ Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println();} // Driver Codepublic static void main(String args[]){ /* Let us create two sorted linked lists to test the methods Created lists: llist1: 5->10->15, llist2: 2->3->20 */ MergeLists llist1 = new MergeLists(); MergeLists llist2 = new MergeLists(); // Node head1 = new Node(5); llist1.addToTheLast(new Node(5)); llist1.addToTheLast(new Node(10)); llist1.addToTheLast(new Node(15)); // Node head2 = new Node(2); llist2.addToTheLast(new Node(2)); llist2.addToTheLast(new Node(3)); llist2.addToTheLast(new Node(20)); llist1.head = new Gfg().sortedMerge(llist1.head, llist2.head); llist1.printList(); }} class Gfg{/* Takes two lists sorted inincreasing order, and splicestheir nodes together to makeone big sorted list which isreturned. */Node sortedMerge(Node headA, Node headB){ /* a dummy first node to hang the result on */ Node dummyNode = new Node(0); /* tail points to the last result node */ Node tail = dummyNode; while(true) { /* if either list runs out, use the other list */ if(headA == null) { tail.next = headB; break; } if(headB == null) { tail.next = headA; break; } /* Compare the data of the two lists whichever lists' data is smaller, append it into tail and advance the head to the next Node */ if(headA.data <= headB.data) { tail.next = headA; headA = headA.next; } else { tail.next = headB; headB = headB.next; } /* Advance the tail */ tail = tail.next; } return dummyNode.next;}} // This code is contributed// by Shubhaw Kumar """ Python program to merge twosorted linked lists """ # Linked List Nodeclass Node: def __init__(self, data): self.data = data self.next = None # Create & Handle List operationsclass LinkedList: def __init__(self): self.head = None # Method to display the list def printList(self): temp = self.head while temp: print(temp.data, end=" ") temp = temp.next # Method to add element to list def addToList(self, newData): newNode = Node(newData) if self.head is None: self.head = newNode return last = self.head while last.next: last = last.next last.next = newNode # Function to merge the lists# Takes two lists which are sorted# joins them to get a single sorted listdef mergeLists(headA, headB): # A dummy node to store the result dummyNode = Node(0) # Tail stores the last node tail = dummyNode while True: # If any of the list gets completely empty # directly join all the elements of the other list if headA is None: tail.next = headB break if headB is None: tail.next = headA break # Compare the data of the lists and whichever is smaller is # appended to the last of the merged list and the head is changed if headA.data <= headB.data: tail.next = headA headA = headA.next else: tail.next = headB headB = headB.next # Advance the tail tail = tail.next # Returns the head of the merged list return dummyNode.next # Create 2 listslistA = LinkedList()listB = LinkedList() # Add elements to the list in sorted orderlistA.addToList(5)listA.addToList(10)listA.addToList(15) listB.addToList(2)listB.addToList(3)listB.addToList(20) # Call the merge functionlistA.head = mergeLists(listA.head, listB.head) # Display merged listprint("Merged Linked List is:")listA.printList() """ This code is contributedby Debidutta Rath """ /* C# program to merge twosorted linked lists */using System; /* Link list node */ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } public class MergeLists { Node head; /* Method to insert a node at the end of the linked list */ public void addToTheLast(Node node) { if (head == null) { head = node; } else { Node temp = head; while (temp.next != null) temp = temp.next; temp.next = node; } } /* Method to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } // Driver Code public static void Main(String []args) { /* Let us create two sorted linked lists to test the methods Created lists: llist1: 5->10->15, llist2: 2->3->20 */ MergeLists llist1 = new MergeLists(); MergeLists llist2 = new MergeLists(); // Node head1 = new Node(5); llist1.addToTheLast(new Node(5)); llist1.addToTheLast(new Node(10)); llist1.addToTheLast(new Node(15)); // Node head2 = new Node(2); llist2.addToTheLast(new Node(2)); llist2.addToTheLast(new Node(3)); llist2.addToTheLast(new Node(20)); llist1.head = new Gfg().sortedMerge(llist1.head, llist2.head); llist1.printList(); } } public class Gfg { /* Takes two lists sorted in increasing order, and splices their nodes together to make one big sorted list which is returned. */ public Node sortedMerge(Node headA, Node headB) { /* a dummy first node to hang the result on */ Node dummyNode = new Node(0); /* tail points to the last result node */ Node tail = dummyNode; while(true) { /* if either list runs out, use the other list */ if(headA == null) { tail.next = headB; break; } if(headB == null) { tail.next = headA; break; } /* Compare the data of the two lists whichever lists' data is smaller, append it into tail and advance the head to the next Node */ if(headA.data <= headB.data) { tail.next = headA; headA = headA.next; } else { tail.next = headB; headB = headB.next; } /* Advance the tail */ tail = tail.next; } return dummyNode.next; }} // This code is contributed 29AjayKumar <script> class Node{ constructor(d) { this.data=d; this.next = null; }} class LinkedList{ constructor(){ this.head=null;} addToTheLast(node){ if (this.head == null) { this.head = node; } else { let temp = this.head; while (temp.next != null) temp = temp.next; temp.next = node; }} printList(){ let temp = this.head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write("<br>");}} function sortedMerge(headA,headB){ /* a dummy first node to hang the result on */ let dummyNode = new Node(0); /* tail points to the last result node */ let tail = dummyNode; while(true) { /* if either list runs out, use the other list */ if(headA == null) { tail.next = headB; break; } if(headB == null) { tail.next = headA; break; } /* Compare the data of the two lists whichever lists' data is smaller, append it into tail and advance the head to the next Node */ if(headA.data <= headB.data) { tail.next = headA; headA = headA.next; } else { tail.next = headB; headB = headB.next; } /* Advance the tail */ tail = tail.next; } return dummyNode.next;} /* Let us create two sorted linked lists to test the methods Created lists: llist1: 5->10->15, llist2: 2->3->20 */let llist1 = new LinkedList();let llist2 = new LinkedList(); // Node head1 = new Node(5);llist1.addToTheLast(new Node(5));llist1.addToTheLast(new Node(10));llist1.addToTheLast(new Node(15)); // Node head2 = new Node(2);llist2.addToTheLast(new Node(2));llist2.addToTheLast(new Node(3));llist2.addToTheLast(new Node(20)); llist1.head = sortedMerge(llist1.head, llist2.head);document.write("Merged Linked List is:<br>")llist1.printList(); // This code is contributed by patel2127</script> Output : Merged Linked List is: 2 3 5 10 15 20 Method 2 (Using Local References) This solution is structurally very similar to the above, but it avoids using a dummy node. Instead, it maintains a struct node** pointer, lastPtrRef, that always points to the last pointer of the result list. This solves the same case that the dummy node did — dealing with the result list when it is empty. If you are trying to build up a list at its tail, either the dummy node or the struct node** “reference” strategy can be used (see Section 1 for details). C++14 C Java Python3 C# Javascript Node* SortedMerge(Node* a, Node* b){ Node* result = NULL; /* point to the last result pointer */ Node** lastPtrRef = &result; while (1) { if (a == NULL) { *lastPtrRef = b; break; } else if (b == NULL) { *lastPtrRef = a; break; } if (a->data <= b->data) MoveNode(lastPtrRef, &a); else MoveNode(lastPtrRef, &b); /* tricky: advance to point to the next ".next" * field */ lastPtrRef = &((*lastPtrRef)->next); } return (result);} // This code is contributed by Aditya Kumar (adityakumar129) struct Node* SortedMerge(struct Node* a, struct Node* b){ struct Node* result = NULL; /* point to the last result pointer */ struct Node** lastPtrRef = &result; while (1) { if (a == NULL) { *lastPtrRef = b; break; } else if (b == NULL) { *lastPtrRef = a; break; } if (a->data <= b->data) MoveNode(lastPtrRef, &a); else MoveNode(lastPtrRef, &b); /* tricky: advance to point to the next ".next" * field */ lastPtrRef = &((*lastPtrRef)->next); } return (result);} // This code is contributed by Aditya Kumar (adityakumar129) Node SortedMerge(Node a, Node b){ Node result = null; /* point to the last result pointer */ Node lastPtrRef = result; while (1) { if (a == null) { lastPtrRef = b; break; } else if (b == null) { lastPtrRef = a; break; } if (a.data <= b.data) MoveNode(lastPtrRef, a); else MoveNode(lastPtrRef, b); /* tricky: advance to point to the next ".next" * field */ lastPtrRef = ((lastPtrRef).next); } return (result);} // This code is contributed by Aditya Kumar (adityakumar129) def SortedMerge( a, b): result = None; ''' point to the last result pointer ''' lastPtrRef = result; while(1): if (a == None): lastPtrRef = b; break; elif(b == None): lastPtrRef = a; break; if(a.data <= b.data): MoveNode(lastPtrRef, a); else: MoveNode(lastPtrRef, b); ''' tricky: advance to point to the next ".next" field ''' lastPtrRef = ((lastPtrRef).next); return(result); # This code is contributed by umadevi9616 Node SortedMerge(Node a, Node b){ Node result = null; // Point to the last result pointer Node lastPtrRef = result; while (1) { if (a == null) { lastPtrRef = b; break; } else if (b == null) { lastPtrRef = a; break; } if (a.data <= b.data) MoveNode(lastPtrRef, a); else MoveNode(lastPtrRef, b); // tricky: advance to point to // the next ".next" field lastPtrRef = ((lastPtrRef).next); } return (result);} // This code is contributed by gauravrajput1 <script> function SortedMerge(a,b){ let result = null; /* point to the last result pointer */let lastPtrRef = result; while(1){ if (a == null) { lastPtrRef = b; break; } else if (b==null) { lastPtrRef = a; break; } if(a.data <= b.data) { MoveNode(lastPtrRef, a); } else { MoveNode(lastPtrRef, b); } /* tricky: advance to point to the next ".next" field */ lastPtrRef = ((lastPtrRef).next);}return(result);} // This code is contributed by rag2127 </script> Method 3 (Using Recursion) Merge is one of those nice recursive problems where the recursive solution code is much cleaner than the iterative code. You probably wouldn’t want to use the recursive version for production code, however, because it will use stack space which is proportional to the length of the lists. C++ C Java Python3 C# Javascript Node* SortedMerge(Node* a, Node* b){ Node* result = NULL; /* Base cases */ if (a == NULL) return(b); else if (b == NULL) return(a); /* Pick either a or b, and recur */ if (a->data <= b->data) { result = a; result->next = SortedMerge(a->next, b); } else { result = b; result->next = SortedMerge(a, b->next); } return(result);} // This code is contributed by rathbhupendra struct Node* SortedMerge(struct Node* a, struct Node* b){ struct Node* result = NULL; /* Base cases */ if (a == NULL) return(b); else if (b==NULL) return(a); /* Pick either a or b, and recur */ if (a->data <= b->data) { result = a; result->next = SortedMerge(a->next, b); } else { result = b; result->next = SortedMerge(a, b->next); } return(result);} class GFG{ public Node SortedMerge(Node A, Node B) { if(A == null) return B; if(B == null) return A; if(A.data < B.data) { A.next = SortedMerge(A.next, B); return A; } else { B.next = SortedMerge(A, B.next); return B; } }} // This code is contributed by Tuhin Das # Python3 program merge two sorted linked# in third linked list using recursive. # Node classclass Node: def __init__(self, data): self.data = data self.next = None # Constructor to initialize the node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # Method to print linked list def printList(self): temp = self.head while temp : print(temp.data, end="->") temp = temp.next # Function to add of node at the end. def append(self, new_data): new_node = Node(new_data) if self.head is None: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node # Function to merge two sorted linked list.def mergeLists(head1, head2): # create a temp node NULL temp = None # List1 is empty then return List2 if head1 is None: return head2 # if List2 is empty then return List1 if head2 is None: return head1 # If List1's data is smaller or # equal to List2's data if head1.data <= head2.data: # assign temp to List1's data temp = head1 # Again check List1's data is smaller or equal List2's # data and call mergeLists function. temp.next = mergeLists(head1.next, head2) else: # If List2's data is greater than or equal List1's # data assign temp to head2 temp = head2 # Again check List2's data is greater or equal List's # data and call mergeLists function. temp.next = mergeLists(head1, head2.next) # return the temp list. return temp # Driver Functionif __name__ == '__main__': # Create linked list : # 10->20->30->40->50 list1 = LinkedList() list1.append(10) list1.append(20) list1.append(30) list1.append(40) list1.append(50) # Create linked list 2 : # 5->15->18->35->60 list2 = LinkedList() list2.append(5) list2.append(15) list2.append(18) list2.append(35) list2.append(60) # Create linked list 3 list3 = LinkedList() # Merging linked list 1 and linked list 2 # in linked list 3 list3.head = mergeLists(list1.head, list2.head) print(" Merged Linked List is : ", end="") list3.printList() # This code is contributed by 'Shriaknt13'. using System; class GFG{ public Node sortedMerge(Node A, Node B){ // Base cases if (A == null) return B; if (B == null) return A; // Pick either a or b, and recur if (A.data < B.data) { A.next = sortedMerge(A.next, B); return A; } else { B.next = sortedMerge(A, B.next); return B; }}} // This code is contributed by hunter2000 <script> function SortedMerge( A, B) { if (A == null) return B; if (B == null) return A; if (A.data < B.data) { A.next = SortedMerge(A.next, B); return A; } else { B.next = SortedMerge(A, B.next); return B; } } // This code contributed by umadevi9616</script> Time Complexity: Since we are traversing through the two lists fully. So, the time complexity is O(m+n) where m and n are the lengths of the two lists to be merged. Method 4 (Reversing The Lists) This idea involves first reversing both the given lists and after reversing, traversing both the lists till the end and then comparing the nodes of both the lists and inserting the node with a larger value at the beginning of the result list. And in this way we will get the resulting list in increasing order. 1) Initialize result list as empty: head = NULL. 2) Let 'a' and 'b' be the heads of first and second list respectively. 3) Reverse both the lists. 4) While (a != NULL and b != NULL) a) Find the larger of two (Current 'a' and 'b') b) Insert the larger value of node at the front of result list. c) Move ahead in the list of larger node. 5) If 'b' becomes NULL before 'a', insert all nodes of 'a' into result list at the beginning. 6) If 'a' becomes NULL before 'b', insert all nodes of 'b' into result list at the beginning. Below is the implementation of above solution. C C++ Java C# /*Given two sorted linked lists consisting of N and M nodesrespectively. The task is to merge both of the list(in-place) and return head of the merged list.*/#include <stdio.h>#include <stdlib.h> /* Link list Node */typedef struct Node { int key; struct Node* next;}Node; // Function to reverse a given Linked List using RecursionNode* reverseList(Node* head){ if (head->next == NULL) return head; Node* rest = reverseList(head->next); head->next->next = head; head->next = NULL; return rest;} // Given two non-empty linked lists 'a' and 'b'Node* sortedMerge(Node* a, Node* b){ // Reverse Linked List 'a' a = reverseList(a); // Reverse Linked List 'b' b = reverseList(b); // Initialize head of resultant list Node* head = NULL; Node* temp; // Traverse both lists while both of them // have nodes. while (a != NULL && b != NULL) { // If a's current value is greater than or equal to // b's current value. if (a->key >= b->key) { // Store next of current Node in first list temp = a->next; // Add 'a' at the front of resultant list a->next = head; // Make 'a' - head of the result list head = a; // Move ahead in first list a = temp; } // If b's value is greater. Below steps are similar // to above (Only 'a' is replaced with 'b') else { temp = b->next; b->next = head; head = b; b = temp; } } // If second list reached end, but first list has // nodes. Add remaining nodes of first list at the // beginning of result list while (a != NULL) { temp = a->next; a->next = head; head = a; a = temp; } // If first list reached end, but second list has // nodes. Add remaining nodes of second list at the // beginning of result list while (b != NULL) { temp = b->next; b->next = head; head = b; b = temp; } // Return the head of the result list return head;} /* Function to print Nodes in a given linked list */void printList(struct Node* Node){ while (Node != NULL) { printf("%d ",Node->key); Node = Node->next; }} /* Utility function to create a new node with given key */Node* newNode(int key){ Node* temp = (Node *)malloc(sizeof(Node)); temp->key = key; temp->next = NULL; return temp;} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* res = NULL; /* Let us create two sorted linked lists to test the above functions. Created lists shall be a: 5->10->15->40 b: 2->3->20 */ Node* a = newNode(5); a->next = newNode(10); a->next->next = newNode(15); a->next->next->next = newNode(40); Node* b = newNode(2); b->next = newNode(3); b->next->next = newNode(20); printf("List A before merge: \n"); printList(a); printf("\nList B before merge: \n"); printList(b); /* merge 2 sorted Linked Lists */ res = sortedMerge(a, b); printf("\nMerged Linked List is: \n"); printList(res); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) /*Given two sorted linked lists consisting of N and M nodesrespectively. The task is to merge both of the list(in-place) and return head of the merged list.*/#include <iostream>using namespace std; /* Link list Node */struct Node { int key; struct Node* next;}; // Function to reverse a given Linked List using RecursionNode* reverseList(Node* head){ if (head->next == NULL) return head; Node* rest = reverseList(head->next); head->next->next = head; head->next = NULL; return rest;} // Given two non-empty linked lists 'a' and 'b'Node* sortedMerge(Node* a, Node* b){ // Reverse Linked List 'a' a = reverseList(a); // Reverse Linked List 'b' b = reverseList(b); // Initialize head of resultant list Node* head = NULL; Node* temp; // Traverse both lists while both of them // have nodes. while (a != NULL && b != NULL) { // If a's current value is greater than or equal to // b's current value. if (a->key >= b->key) { // Store next of current Node in first list temp = a->next; // Add 'a' at the front of resultant list a->next = head; // Make 'a' - head of the result list head = a; // Move ahead in first list a = temp; } // If b's value is greater. Below steps are similar // to above (Only 'a' is replaced with 'b') else { temp = b->next; b->next = head; head = b; b = temp; } } // If second list reached end, but first list has // nodes. Add remaining nodes of first list at the // beginning of result list while (a != NULL) { temp = a->next; a->next = head; head = a; a = temp; } // If first list reached end, but second list has // nodes. Add remaining nodes of second list at the // beginning of result list while (b != NULL) { temp = b->next; b->next = head; head = b; b = temp; } // Return the head of the result list return head;} /* Function to print Nodes in a given linked list */void printList(struct Node* Node){ while (Node != NULL) { cout << Node->key << " "; Node = Node->next; }} /* Utility function to create a new node with given key */Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->next = NULL; return temp;} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* res = NULL; /* Let us create two sorted linked lists to test the above functions. Created lists shall be a: 5->10->15->40 b: 2->3->20 */ Node* a = newNode(5); a->next = newNode(10); a->next->next = newNode(15); a->next->next->next = newNode(40); Node* b = newNode(2); b->next = newNode(3); b->next->next = newNode(20); cout << "List A before merge: \n"; printList(a); cout << "\nList B before merge: \n"; printList(b); /* merge 2 sorted Linked Lists */ res = sortedMerge(a, b); cout << "\nMerged Linked List is: \n"; printList(res); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) /*Given two sorted linked lists consisting of N and M nodesrespectively. The task is to merge both of the list(in-place) and return head of the merged list.*/ import java.util.*; class GFG{ /* Link list Node */static class Node { int key; Node next;}; // Function to reverse a given Linked List using Recursionstatic Node reverseList(Node head){ if (head.next == null) return head; Node rest = reverseList(head.next); head.next.next = head; head.next = null; return rest;} // Given two non-empty linked lists 'a' and 'b'static Node sortedMerge(Node a, Node b){ // Reverse Linked List 'a' a = reverseList(a); // Reverse Linked List 'b' b = reverseList(b); // Initialize head of resultant list Node head = null; Node temp; // Traverse both lists while both of them // have nodes. while (a != null && b != null) { // If a's current value is greater than or equal to // b's current value. if (a.key >= b.key) { // Store next of current Node in first list temp = a.next; // Add 'a' at the front of resultant list a.next = head; // Make 'a' - head of the result list head = a; // Move ahead in first list a = temp; } // If b's value is greater. Below steps are similar // to above (Only 'a' is replaced with 'b') else { temp = b.next; b.next = head; head = b; b = temp; } } // If second list reached end, but first list has // nodes. Add remaining nodes of first list at the // beginning of result list while (a != null) { temp = a.next; a.next = head; head = a; a = temp; } // If first list reached end, but second list has // nodes. Add remaining nodes of second list at the // beginning of result list while (b != null) { temp = b.next; b.next = head; head = b; b = temp; } // Return the head of the result list return head;} /* Function to print Nodes in a given linked list */static void printList(Node Node){ while (Node != null) { System.out.print(Node.key+ " "); Node = Node.next; }} /* Utility function to create a new node with given key */static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.next = null; return temp;} /* Driver program to test above functions*/public static void main(String[] args){ /* Start with the empty list */ Node res = null; /* Let us create two sorted linked lists to test the above functions. Created lists shall be a: 5.10.15.40 b: 2.3.20 */ Node a = newNode(5); a.next = newNode(10); a.next.next = newNode(15); a.next.next.next = newNode(40); Node b = newNode(2); b.next = newNode(3); b.next.next = newNode(20); System.out.print("List A before merge: \n"); printList(a); System.out.print("\nList B before merge: \n"); printList(b); /* merge 2 sorted Linked Lists */ res = sortedMerge(a, b); System.out.print("\nMerged Linked List is: \n"); printList(res);}} // This code is contributed by umadevi9616 /*Given two sorted linked lists consisting of N and M nodesrespectively. The task is to merge both of the list(in-place) and return head of the merged list.*/ using System;using System.Collections.Generic; public class GFG{ /* Link list Node */public class Node { public int key; public Node next;}; // Function to reverse a given Linked List using Recursionstatic Node reverseList(Node head){ if (head.next == null) return head; Node rest = reverseList(head.next); head.next.next = head; head.next = null; return rest;} // Given two non-empty linked lists 'a' and 'b'static Node sortedMerge(Node a, Node b){ // Reverse Linked List 'a' a = reverseList(a); // Reverse Linked List 'b' b = reverseList(b); // Initialize head of resultant list Node head = null; Node temp; // Traverse both lists while both of them // have nodes. while (a != null && b != null) { // If a's current value is greater than or equal to // b's current value. if (a.key >= b.key) { // Store next of current Node in first list temp = a.next; // Add 'a' at the front of resultant list a.next = head; // Make 'a' - head of the result list head = a; // Move ahead in first list a = temp; } // If b's value is greater. Below steps are similar // to above (Only 'a' is replaced with 'b') else { temp = b.next; b.next = head; head = b; b = temp; } } // If second list reached end, but first list has // nodes. Add remaining nodes of first list at the // beginning of result list while (a != null) { temp = a.next; a.next = head; head = a; a = temp; } // If first list reached end, but second list has // nodes. Add remaining nodes of second list at the // beginning of result list while (b != null) { temp = b.next; b.next = head; head = b; b = temp; } // Return the head of the result list return head;} /* Function to print Nodes in a given linked list */static void printList(Node Node){ while (Node != null) { Console.Write(Node.key+ " "); Node = Node.next; }} /* Utility function to create a new node with given key */static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.next = null; return temp;} /* Driver program to test above functions*/public static void Main(String[] args){ /* Start with the empty list */ Node res = null; /* Let us create two sorted linked lists to test the above functions. Created lists shall be a: 5.10.15.40 b: 2.3.20 */ Node a = newNode(5); a.next = newNode(10); a.next.next = newNode(15); a.next.next.next = newNode(40); Node b = newNode(2); b.next = newNode(3); b.next.next = newNode(20); Console.Write("List A before merge: \n"); printList(a); Console.Write("\nList B before merge: \n"); printList(b); /* merge 2 sorted Linked Lists */ res = sortedMerge(a, b); Console.Write("\nMerged Linked List is: \n"); printList(res);}} // This code is contributed by umadevi9616 Output: List A before merge: 5 10 15 40 List B before merge: 2 3 20 Merged Linked List is: 2 3 5 10 15 20 40 Time Complexity: Since we are traversing through the two lists fully. So, the time complexity is O(m+n) where m and n are the lengths of the two lists to be merged. This method is contributed by Mehul Mathur(mathurmehul01). This idea is similar to this post. Please refer below post for simpler implementations : Merge two sorted lists (in-place)Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdfPlease write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem. Shubhaw Kumar 29AjayKumar rathbhupendra tuhindas221b AmiyaRanjanRout hunter2000 ryadav2 mathurmehul01 umadevi9616 GauravRajput1 rag2127 patel2127 simranarora5sos simmytarika5 surinderdawra388 adityakumar129 Accolite Amazon Belzabar Brocade FactSet Flipkart MakeMyTrip Merge Sort Microsoft OATS Systems Oracle Samsung Synopsys Zoho Linked List Zoho Flipkart Accolite Amazon Microsoft Samsung FactSet MakeMyTrip Oracle Brocade Synopsys OATS Systems Belzabar Linked List Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Delete a Linked List node at a given position Queue - Linked List Implementation Implement a stack using singly linked list Implementing a Linked List in Java using Class Circular Linked List | Set 1 (Introduction and Applications) Remove duplicates from a sorted linked list Find Length of a Linked List (Iterative and Recursive) Function to check if a singly linked list is palindrome Search an element in a Linked List (Iterative and Recursive) Write a function to delete a Linked List
[ { "code": null, "e": 24233, "s": 24205, "text": "\n12 Apr, 2022" }, { "code": null, "e": 24528, "s": 24233, "text": "Write a SortedMerge() function that takes two lists, each of which is sorted in increasing order, and merges the two together into one list which is in increasing order. SortedMerge() should return the new list. The new list should be made by splicing together the nodes of the first two lists." }, { "code": null, "e": 24721, "s": 24528, "text": "For example if the first linked list a is 5->10->15 and the other linked list b is 2->3->20, then SortedMerge() should return a pointer to the head node of the merged list 2->3->5->10->15->20." }, { "code": null, "e": 24963, "s": 24721, "text": "There are many cases to deal with: either ‘a’ or ‘b’ may be empty, during processing either ‘a’ or ‘b’ may run out first, and finally, there’s the problem of starting the result list empty, and building it up while going through ‘a’ and ‘b’." }, { "code": null, "e": 25172, "s": 24963, "text": "Method 1 (Using Dummy Nodes) The strategy here uses a temporary dummy node as the start of the result list. The pointer Tail always points to the last node in the result list, so appending new nodes is easy. " }, { "code": null, "e": 25451, "s": 25172, "text": "The dummy node gives the tail something to point to initially when the result list is empty. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either ‘a’ or ‘b’, and adding it to the tail. When " }, { "code": null, "e": 25494, "s": 25451, "text": "We are done, the result is in dummy.next. " }, { "code": null, "e": 25546, "s": 25494, "text": "The below image is a dry run of the above approach:" }, { "code": null, "e": 25598, "s": 25546, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25602, "s": 25598, "text": "C++" }, { "code": null, "e": 25604, "s": 25602, "text": "C" }, { "code": null, "e": 25609, "s": 25604, "text": "Java" }, { "code": null, "e": 25617, "s": 25609, "text": "Python3" }, { "code": null, "e": 25620, "s": 25617, "text": "C#" }, { "code": null, "e": 25631, "s": 25620, "text": "Javascript" }, { "code": "/* C++ program to merge two sorted linked lists */#include <bits/stdc++.h>using namespace std; /* Link list node */class Node{ public: int data; Node* next;}; /* pull off the front node ofthe source and put it in dest */void MoveNode(Node** destRef, Node** sourceRef); /* Takes two lists sorted in increasingorder, and splices their nodes togetherto make one big sorted list whichis returned. */Node* SortedMerge(Node* a, Node* b){ /* a dummy first node to hang the result on */ Node dummy; /* tail points to the last result node */ Node* tail = &dummy; /* so tail->next is the place to add new nodes to the result. */ dummy.next = NULL; while (1) { if (a == NULL) { /* if either list runs out, use the other list */ tail->next = b; break; } else if (b == NULL) { tail->next = a; break; } if (a->data <= b->data) MoveNode(&(tail->next), &a); else MoveNode(&(tail->next), &b); tail = tail->next; } return(dummy.next);} /* UTILITY FUNCTIONS *//* MoveNode() function takes thenode from the front of the source,and move it to the front of the dest.It is an error to call this with thesource list empty. Before calling MoveNode():source == {1, 2, 3}dest == {1, 2, 3} After calling MoveNode():source == {2, 3}dest == {1, 1, 2, 3} */void MoveNode(Node** destRef, Node** sourceRef){ /* the front source node */ Node* newNode = *sourceRef; assert(newNode != NULL); /* Advance the source pointer */ *sourceRef = newNode->next; /* Link the old dest off the new node */ newNode->next = *destRef; /* Move dest to point to the new node */ *destRef = newNode;} /* Function to insert a node at the beginning of the linked list */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(Node *node){ while (node!=NULL) { cout<<node->data<<\" \"; node = node->next; }} /* Driver code*/int main(){ /* Start with the empty list */ Node* res = NULL; Node* a = NULL; Node* b = NULL; /* Let us create two sorted linked lists to test the functions Created lists, a: 5->10->15, b: 2->3->20 */ push(&a, 15); push(&a, 10); push(&a, 5); push(&b, 20); push(&b, 3); push(&b, 2); /* Remove duplicates from linked list */ res = SortedMerge(a, b); cout << \"Merged Linked List is: \\n\"; printList(res); return 0;} // This code is contributed by rathbhupendra", "e": 28482, "s": 25631, "text": null }, { "code": "/* C program to merge two sorted linked lists */#include<stdio.h>#include<stdlib.h>#include<assert.h> /* Link list node */struct Node{ int data; struct Node* next;}; /* pull off the front node of the source and put it in dest */void MoveNode(struct Node** destRef, struct Node** sourceRef); /* Takes two lists sorted in increasing order, and splices their nodes together to make one big sorted list which is returned. */struct Node* SortedMerge(struct Node* a, struct Node* b){ /* a dummy first node to hang the result on */ struct Node dummy; /* tail points to the last result node */ struct Node* tail = &dummy; /* so tail->next is the place to add new nodes to the result. */ dummy.next = NULL; while (1) { if (a == NULL) { /* if either list runs out, use the other list */ tail->next = b; break; } else if (b == NULL) { tail->next = a; break; } if (a->data <= b->data) MoveNode(&(tail->next), &a); else MoveNode(&(tail->next), &b); tail = tail->next; } return(dummy.next);} /* UTILITY FUNCTIONS *//* MoveNode() function takes the node from the front of the source, and move it to the front of the dest. It is an error to call this with the source list empty. Before calling MoveNode(): source == {1, 2, 3} dest == {1, 2, 3} After calling MoveNode(): source == {2, 3} dest == {1, 1, 2, 3} */void MoveNode(struct Node** destRef, struct Node** sourceRef){ /* the front source node */ struct Node* newNode = *sourceRef; assert(newNode != NULL); /* Advance the source pointer */ *sourceRef = newNode->next; /* Link the old dest off the new node */ newNode->next = *destRef; /* Move dest to point to the new node */ *destRef = newNode;} /* Function to insert a node at the beginning of the linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given linked list */void printList(struct Node *node){ while (node!=NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* res = NULL; struct Node* a = NULL; struct Node* b = NULL; /* Let us create two sorted linked lists to test the functions Created lists, a: 5->10->15, b: 2->3->20 */ push(&a, 15); push(&a, 10); push(&a, 5); push(&b, 20); push(&b, 3); push(&b, 2); /* Remove duplicates from linked list */ res = SortedMerge(a, b); printf(\"Merged Linked List is: \\n\"); printList(res); return 0;}", "e": 31527, "s": 28482, "text": null }, { "code": "/* Java program to merge two sorted linked lists */import java.util.*; /* Link list node */class Node{ int data; Node next; Node(int d) {data = d; next = null;}} class MergeLists{Node head; /* Method to insert a node at the end of the linked list */public void addToTheLast(Node node){ if (head == null) { head = node; } else { Node temp = head; while (temp.next != null) temp = temp.next; temp.next = node; }} /* Method to print linked list */void printList(){ Node temp = head; while (temp != null) { System.out.print(temp.data + \" \"); temp = temp.next; } System.out.println();} // Driver Codepublic static void main(String args[]){ /* Let us create two sorted linked lists to test the methods Created lists: llist1: 5->10->15, llist2: 2->3->20 */ MergeLists llist1 = new MergeLists(); MergeLists llist2 = new MergeLists(); // Node head1 = new Node(5); llist1.addToTheLast(new Node(5)); llist1.addToTheLast(new Node(10)); llist1.addToTheLast(new Node(15)); // Node head2 = new Node(2); llist2.addToTheLast(new Node(2)); llist2.addToTheLast(new Node(3)); llist2.addToTheLast(new Node(20)); llist1.head = new Gfg().sortedMerge(llist1.head, llist2.head); llist1.printList(); }} class Gfg{/* Takes two lists sorted inincreasing order, and splicestheir nodes together to makeone big sorted list which isreturned. */Node sortedMerge(Node headA, Node headB){ /* a dummy first node to hang the result on */ Node dummyNode = new Node(0); /* tail points to the last result node */ Node tail = dummyNode; while(true) { /* if either list runs out, use the other list */ if(headA == null) { tail.next = headB; break; } if(headB == null) { tail.next = headA; break; } /* Compare the data of the two lists whichever lists' data is smaller, append it into tail and advance the head to the next Node */ if(headA.data <= headB.data) { tail.next = headA; headA = headA.next; } else { tail.next = headB; headB = headB.next; } /* Advance the tail */ tail = tail.next; } return dummyNode.next;}} // This code is contributed// by Shubhaw Kumar", "e": 34116, "s": 31527, "text": null }, { "code": "\"\"\" Python program to merge twosorted linked lists \"\"\" # Linked List Nodeclass Node: def __init__(self, data): self.data = data self.next = None # Create & Handle List operationsclass LinkedList: def __init__(self): self.head = None # Method to display the list def printList(self): temp = self.head while temp: print(temp.data, end=\" \") temp = temp.next # Method to add element to list def addToList(self, newData): newNode = Node(newData) if self.head is None: self.head = newNode return last = self.head while last.next: last = last.next last.next = newNode # Function to merge the lists# Takes two lists which are sorted# joins them to get a single sorted listdef mergeLists(headA, headB): # A dummy node to store the result dummyNode = Node(0) # Tail stores the last node tail = dummyNode while True: # If any of the list gets completely empty # directly join all the elements of the other list if headA is None: tail.next = headB break if headB is None: tail.next = headA break # Compare the data of the lists and whichever is smaller is # appended to the last of the merged list and the head is changed if headA.data <= headB.data: tail.next = headA headA = headA.next else: tail.next = headB headB = headB.next # Advance the tail tail = tail.next # Returns the head of the merged list return dummyNode.next # Create 2 listslistA = LinkedList()listB = LinkedList() # Add elements to the list in sorted orderlistA.addToList(5)listA.addToList(10)listA.addToList(15) listB.addToList(2)listB.addToList(3)listB.addToList(20) # Call the merge functionlistA.head = mergeLists(listA.head, listB.head) # Display merged listprint(\"Merged Linked List is:\")listA.printList() \"\"\" This code is contributedby Debidutta Rath \"\"\"", "e": 36172, "s": 34116, "text": null }, { "code": "/* C# program to merge twosorted linked lists */using System; /* Link list node */ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } public class MergeLists { Node head; /* Method to insert a node at the end of the linked list */ public void addToTheLast(Node node) { if (head == null) { head = node; } else { Node temp = head; while (temp.next != null) temp = temp.next; temp.next = node; } } /* Method to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.WriteLine(); } // Driver Code public static void Main(String []args) { /* Let us create two sorted linked lists to test the methods Created lists: llist1: 5->10->15, llist2: 2->3->20 */ MergeLists llist1 = new MergeLists(); MergeLists llist2 = new MergeLists(); // Node head1 = new Node(5); llist1.addToTheLast(new Node(5)); llist1.addToTheLast(new Node(10)); llist1.addToTheLast(new Node(15)); // Node head2 = new Node(2); llist2.addToTheLast(new Node(2)); llist2.addToTheLast(new Node(3)); llist2.addToTheLast(new Node(20)); llist1.head = new Gfg().sortedMerge(llist1.head, llist2.head); llist1.printList(); } } public class Gfg { /* Takes two lists sorted in increasing order, and splices their nodes together to make one big sorted list which is returned. */ public Node sortedMerge(Node headA, Node headB) { /* a dummy first node to hang the result on */ Node dummyNode = new Node(0); /* tail points to the last result node */ Node tail = dummyNode; while(true) { /* if either list runs out, use the other list */ if(headA == null) { tail.next = headB; break; } if(headB == null) { tail.next = headA; break; } /* Compare the data of the two lists whichever lists' data is smaller, append it into tail and advance the head to the next Node */ if(headA.data <= headB.data) { tail.next = headA; headA = headA.next; } else { tail.next = headB; headB = headB.next; } /* Advance the tail */ tail = tail.next; } return dummyNode.next; }} // This code is contributed 29AjayKumar", "e": 39378, "s": 36172, "text": null }, { "code": "<script> class Node{ constructor(d) { this.data=d; this.next = null; }} class LinkedList{ constructor(){ this.head=null;} addToTheLast(node){ if (this.head == null) { this.head = node; } else { let temp = this.head; while (temp.next != null) temp = temp.next; temp.next = node; }} printList(){ let temp = this.head; while (temp != null) { document.write(temp.data + \" \"); temp = temp.next; } document.write(\"<br>\");}} function sortedMerge(headA,headB){ /* a dummy first node to hang the result on */ let dummyNode = new Node(0); /* tail points to the last result node */ let tail = dummyNode; while(true) { /* if either list runs out, use the other list */ if(headA == null) { tail.next = headB; break; } if(headB == null) { tail.next = headA; break; } /* Compare the data of the two lists whichever lists' data is smaller, append it into tail and advance the head to the next Node */ if(headA.data <= headB.data) { tail.next = headA; headA = headA.next; } else { tail.next = headB; headB = headB.next; } /* Advance the tail */ tail = tail.next; } return dummyNode.next;} /* Let us create two sorted linked lists to test the methods Created lists: llist1: 5->10->15, llist2: 2->3->20 */let llist1 = new LinkedList();let llist2 = new LinkedList(); // Node head1 = new Node(5);llist1.addToTheLast(new Node(5));llist1.addToTheLast(new Node(10));llist1.addToTheLast(new Node(15)); // Node head2 = new Node(2);llist2.addToTheLast(new Node(2));llist2.addToTheLast(new Node(3));llist2.addToTheLast(new Node(20)); llist1.head = sortedMerge(llist1.head, llist2.head);document.write(\"Merged Linked List is:<br>\")llist1.printList(); // This code is contributed by patel2127</script>", "e": 41542, "s": 39378, "text": null }, { "code": null, "e": 41552, "s": 41542, "text": "Output : " }, { "code": null, "e": 41591, "s": 41552, "text": "Merged Linked List is: \n2 3 5 10 15 20" }, { "code": null, "e": 42089, "s": 41591, "text": "Method 2 (Using Local References) This solution is structurally very similar to the above, but it avoids using a dummy node. Instead, it maintains a struct node** pointer, lastPtrRef, that always points to the last pointer of the result list. This solves the same case that the dummy node did — dealing with the result list when it is empty. If you are trying to build up a list at its tail, either the dummy node or the struct node** “reference” strategy can be used (see Section 1 for details). " }, { "code": null, "e": 42095, "s": 42089, "text": "C++14" }, { "code": null, "e": 42097, "s": 42095, "text": "C" }, { "code": null, "e": 42102, "s": 42097, "text": "Java" }, { "code": null, "e": 42110, "s": 42102, "text": "Python3" }, { "code": null, "e": 42113, "s": 42110, "text": "C#" }, { "code": null, "e": 42124, "s": 42113, "text": "Javascript" }, { "code": "Node* SortedMerge(Node* a, Node* b){ Node* result = NULL; /* point to the last result pointer */ Node** lastPtrRef = &result; while (1) { if (a == NULL) { *lastPtrRef = b; break; } else if (b == NULL) { *lastPtrRef = a; break; } if (a->data <= b->data) MoveNode(lastPtrRef, &a); else MoveNode(lastPtrRef, &b); /* tricky: advance to point to the next \".next\" * field */ lastPtrRef = &((*lastPtrRef)->next); } return (result);} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 42762, "s": 42124, "text": null }, { "code": "struct Node* SortedMerge(struct Node* a, struct Node* b){ struct Node* result = NULL; /* point to the last result pointer */ struct Node** lastPtrRef = &result; while (1) { if (a == NULL) { *lastPtrRef = b; break; } else if (b == NULL) { *lastPtrRef = a; break; } if (a->data <= b->data) MoveNode(lastPtrRef, &a); else MoveNode(lastPtrRef, &b); /* tricky: advance to point to the next \".next\" * field */ lastPtrRef = &((*lastPtrRef)->next); } return (result);} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 43435, "s": 42762, "text": null }, { "code": "Node SortedMerge(Node a, Node b){ Node result = null; /* point to the last result pointer */ Node lastPtrRef = result; while (1) { if (a == null) { lastPtrRef = b; break; } else if (b == null) { lastPtrRef = a; break; } if (a.data <= b.data) MoveNode(lastPtrRef, a); else MoveNode(lastPtrRef, b); /* tricky: advance to point to the next \".next\" * field */ lastPtrRef = ((lastPtrRef).next); } return (result);} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 44057, "s": 43435, "text": null }, { "code": "def SortedMerge( a, b): result = None; ''' point to the last result pointer ''' lastPtrRef = result; while(1): if (a == None): lastPtrRef = b; break; elif(b == None): lastPtrRef = a; break; if(a.data <= b.data): MoveNode(lastPtrRef, a); else: MoveNode(lastPtrRef, b); ''' tricky: advance to point to the next \".next\" field ''' lastPtrRef = ((lastPtrRef).next); return(result); # This code is contributed by umadevi9616", "e": 44622, "s": 44057, "text": null }, { "code": "Node SortedMerge(Node a, Node b){ Node result = null; // Point to the last result pointer Node lastPtrRef = result; while (1) { if (a == null) { lastPtrRef = b; break; } else if (b == null) { lastPtrRef = a; break; } if (a.data <= b.data) MoveNode(lastPtrRef, a); else MoveNode(lastPtrRef, b); // tricky: advance to point to // the next \".next\" field lastPtrRef = ((lastPtrRef).next); } return (result);} // This code is contributed by gauravrajput1", "e": 45222, "s": 44622, "text": null }, { "code": "<script> function SortedMerge(a,b){ let result = null; /* point to the last result pointer */let lastPtrRef = result; while(1){ if (a == null) { lastPtrRef = b; break; } else if (b==null) { lastPtrRef = a; break; } if(a.data <= b.data) { MoveNode(lastPtrRef, a); } else { MoveNode(lastPtrRef, b); } /* tricky: advance to point to the next \".next\" field */ lastPtrRef = ((lastPtrRef).next);}return(result);} // This code is contributed by rag2127 </script>", "e": 45762, "s": 45222, "text": null }, { "code": null, "e": 46080, "s": 45762, "text": "Method 3 (Using Recursion) Merge is one of those nice recursive problems where the recursive solution code is much cleaner than the iterative code. You probably wouldn’t want to use the recursive version for production code, however, because it will use stack space which is proportional to the length of the lists. " }, { "code": null, "e": 46084, "s": 46080, "text": "C++" }, { "code": null, "e": 46086, "s": 46084, "text": "C" }, { "code": null, "e": 46091, "s": 46086, "text": "Java" }, { "code": null, "e": 46099, "s": 46091, "text": "Python3" }, { "code": null, "e": 46102, "s": 46099, "text": "C#" }, { "code": null, "e": 46113, "s": 46102, "text": "Javascript" }, { "code": "Node* SortedMerge(Node* a, Node* b){ Node* result = NULL; /* Base cases */ if (a == NULL) return(b); else if (b == NULL) return(a); /* Pick either a or b, and recur */ if (a->data <= b->data) { result = a; result->next = SortedMerge(a->next, b); } else { result = b; result->next = SortedMerge(a, b->next); } return(result);} // This code is contributed by rathbhupendra", "e": 46572, "s": 46113, "text": null }, { "code": "struct Node* SortedMerge(struct Node* a, struct Node* b){ struct Node* result = NULL; /* Base cases */ if (a == NULL) return(b); else if (b==NULL) return(a); /* Pick either a or b, and recur */ if (a->data <= b->data) { result = a; result->next = SortedMerge(a->next, b); } else { result = b; result->next = SortedMerge(a, b->next); } return(result);}", "e": 46962, "s": 46572, "text": null }, { "code": "class GFG{ public Node SortedMerge(Node A, Node B) { if(A == null) return B; if(B == null) return A; if(A.data < B.data) { A.next = SortedMerge(A.next, B); return A; } else { B.next = SortedMerge(A, B.next); return B; } }} // This code is contributed by Tuhin Das", "e": 47358, "s": 46962, "text": null }, { "code": "# Python3 program merge two sorted linked# in third linked list using recursive. # Node classclass Node: def __init__(self, data): self.data = data self.next = None # Constructor to initialize the node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # Method to print linked list def printList(self): temp = self.head while temp : print(temp.data, end=\"->\") temp = temp.next # Function to add of node at the end. def append(self, new_data): new_node = Node(new_data) if self.head is None: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node # Function to merge two sorted linked list.def mergeLists(head1, head2): # create a temp node NULL temp = None # List1 is empty then return List2 if head1 is None: return head2 # if List2 is empty then return List1 if head2 is None: return head1 # If List1's data is smaller or # equal to List2's data if head1.data <= head2.data: # assign temp to List1's data temp = head1 # Again check List1's data is smaller or equal List2's # data and call mergeLists function. temp.next = mergeLists(head1.next, head2) else: # If List2's data is greater than or equal List1's # data assign temp to head2 temp = head2 # Again check List2's data is greater or equal List's # data and call mergeLists function. temp.next = mergeLists(head1, head2.next) # return the temp list. return temp # Driver Functionif __name__ == '__main__': # Create linked list : # 10->20->30->40->50 list1 = LinkedList() list1.append(10) list1.append(20) list1.append(30) list1.append(40) list1.append(50) # Create linked list 2 : # 5->15->18->35->60 list2 = LinkedList() list2.append(5) list2.append(15) list2.append(18) list2.append(35) list2.append(60) # Create linked list 3 list3 = LinkedList() # Merging linked list 1 and linked list 2 # in linked list 3 list3.head = mergeLists(list1.head, list2.head) print(\" Merged Linked List is : \", end=\"\") list3.printList() # This code is contributed by 'Shriaknt13'. ", "e": 49777, "s": 47358, "text": null }, { "code": "using System; class GFG{ public Node sortedMerge(Node A, Node B){ // Base cases if (A == null) return B; if (B == null) return A; // Pick either a or b, and recur if (A.data < B.data) { A.next = sortedMerge(A.next, B); return A; } else { B.next = sortedMerge(A, B.next); return B; }}} // This code is contributed by hunter2000", "e": 50190, "s": 49777, "text": null }, { "code": "<script> function SortedMerge( A, B) { if (A == null) return B; if (B == null) return A; if (A.data < B.data) { A.next = SortedMerge(A.next, B); return A; } else { B.next = SortedMerge(A, B.next); return B; } } // This code contributed by umadevi9616</script>", "e": 50562, "s": 50190, "text": null }, { "code": null, "e": 50730, "s": 50562, "text": " Time Complexity: Since we are traversing through the two lists fully. So, the time complexity is O(m+n) where m and n are the lengths of the two lists to be merged. " }, { "code": null, "e": 50761, "s": 50730, "text": "Method 4 (Reversing The Lists)" }, { "code": null, "e": 51072, "s": 50761, "text": "This idea involves first reversing both the given lists and after reversing, traversing both the lists till the end and then comparing the nodes of both the lists and inserting the node with a larger value at the beginning of the result list. And in this way we will get the resulting list in increasing order." }, { "code": null, "e": 51619, "s": 51072, "text": "1) Initialize result list as empty: head = NULL.\n2) Let 'a' and 'b' be the heads of first and second list respectively.\n3) Reverse both the lists.\n4) While (a != NULL and b != NULL)\n a) Find the larger of two (Current 'a' and 'b')\n b) Insert the larger value of node at the front of result list.\n c) Move ahead in the list of larger node. \n5) If 'b' becomes NULL before 'a', insert all nodes of 'a' \n into result list at the beginning.\n6) If 'a' becomes NULL before 'b', insert all nodes of 'b' \n into result list at the beginning. " }, { "code": null, "e": 51666, "s": 51619, "text": "Below is the implementation of above solution." }, { "code": null, "e": 51668, "s": 51666, "text": "C" }, { "code": null, "e": 51672, "s": 51668, "text": "C++" }, { "code": null, "e": 51677, "s": 51672, "text": "Java" }, { "code": null, "e": 51680, "s": 51677, "text": "C#" }, { "code": "/*Given two sorted linked lists consisting of N and M nodesrespectively. The task is to merge both of the list(in-place) and return head of the merged list.*/#include <stdio.h>#include <stdlib.h> /* Link list Node */typedef struct Node { int key; struct Node* next;}Node; // Function to reverse a given Linked List using RecursionNode* reverseList(Node* head){ if (head->next == NULL) return head; Node* rest = reverseList(head->next); head->next->next = head; head->next = NULL; return rest;} // Given two non-empty linked lists 'a' and 'b'Node* sortedMerge(Node* a, Node* b){ // Reverse Linked List 'a' a = reverseList(a); // Reverse Linked List 'b' b = reverseList(b); // Initialize head of resultant list Node* head = NULL; Node* temp; // Traverse both lists while both of them // have nodes. while (a != NULL && b != NULL) { // If a's current value is greater than or equal to // b's current value. if (a->key >= b->key) { // Store next of current Node in first list temp = a->next; // Add 'a' at the front of resultant list a->next = head; // Make 'a' - head of the result list head = a; // Move ahead in first list a = temp; } // If b's value is greater. Below steps are similar // to above (Only 'a' is replaced with 'b') else { temp = b->next; b->next = head; head = b; b = temp; } } // If second list reached end, but first list has // nodes. Add remaining nodes of first list at the // beginning of result list while (a != NULL) { temp = a->next; a->next = head; head = a; a = temp; } // If first list reached end, but second list has // nodes. Add remaining nodes of second list at the // beginning of result list while (b != NULL) { temp = b->next; b->next = head; head = b; b = temp; } // Return the head of the result list return head;} /* Function to print Nodes in a given linked list */void printList(struct Node* Node){ while (Node != NULL) { printf(\"%d \",Node->key); Node = Node->next; }} /* Utility function to create a new node with given key */Node* newNode(int key){ Node* temp = (Node *)malloc(sizeof(Node)); temp->key = key; temp->next = NULL; return temp;} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* res = NULL; /* Let us create two sorted linked lists to test the above functions. Created lists shall be a: 5->10->15->40 b: 2->3->20 */ Node* a = newNode(5); a->next = newNode(10); a->next->next = newNode(15); a->next->next->next = newNode(40); Node* b = newNode(2); b->next = newNode(3); b->next->next = newNode(20); printf(\"List A before merge: \\n\"); printList(a); printf(\"\\nList B before merge: \\n\"); printList(b); /* merge 2 sorted Linked Lists */ res = sortedMerge(a, b); printf(\"\\nMerged Linked List is: \\n\"); printList(res); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 54940, "s": 51680, "text": null }, { "code": "/*Given two sorted linked lists consisting of N and M nodesrespectively. The task is to merge both of the list(in-place) and return head of the merged list.*/#include <iostream>using namespace std; /* Link list Node */struct Node { int key; struct Node* next;}; // Function to reverse a given Linked List using RecursionNode* reverseList(Node* head){ if (head->next == NULL) return head; Node* rest = reverseList(head->next); head->next->next = head; head->next = NULL; return rest;} // Given two non-empty linked lists 'a' and 'b'Node* sortedMerge(Node* a, Node* b){ // Reverse Linked List 'a' a = reverseList(a); // Reverse Linked List 'b' b = reverseList(b); // Initialize head of resultant list Node* head = NULL; Node* temp; // Traverse both lists while both of them // have nodes. while (a != NULL && b != NULL) { // If a's current value is greater than or equal to // b's current value. if (a->key >= b->key) { // Store next of current Node in first list temp = a->next; // Add 'a' at the front of resultant list a->next = head; // Make 'a' - head of the result list head = a; // Move ahead in first list a = temp; } // If b's value is greater. Below steps are similar // to above (Only 'a' is replaced with 'b') else { temp = b->next; b->next = head; head = b; b = temp; } } // If second list reached end, but first list has // nodes. Add remaining nodes of first list at the // beginning of result list while (a != NULL) { temp = a->next; a->next = head; head = a; a = temp; } // If first list reached end, but second list has // nodes. Add remaining nodes of second list at the // beginning of result list while (b != NULL) { temp = b->next; b->next = head; head = b; b = temp; } // Return the head of the result list return head;} /* Function to print Nodes in a given linked list */void printList(struct Node* Node){ while (Node != NULL) { cout << Node->key << \" \"; Node = Node->next; }} /* Utility function to create a new node with given key */Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->next = NULL; return temp;} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* res = NULL; /* Let us create two sorted linked lists to test the above functions. Created lists shall be a: 5->10->15->40 b: 2->3->20 */ Node* a = newNode(5); a->next = newNode(10); a->next->next = newNode(15); a->next->next->next = newNode(40); Node* b = newNode(2); b->next = newNode(3); b->next->next = newNode(20); cout << \"List A before merge: \\n\"; printList(a); cout << \"\\nList B before merge: \\n\"; printList(b); /* merge 2 sorted Linked Lists */ res = sortedMerge(a, b); cout << \"\\nMerged Linked List is: \\n\"; printList(res); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 58171, "s": 54940, "text": null }, { "code": "/*Given two sorted linked lists consisting of N and M nodesrespectively. The task is to merge both of the list(in-place) and return head of the merged list.*/ import java.util.*; class GFG{ /* Link list Node */static class Node { int key; Node next;}; // Function to reverse a given Linked List using Recursionstatic Node reverseList(Node head){ if (head.next == null) return head; Node rest = reverseList(head.next); head.next.next = head; head.next = null; return rest;} // Given two non-empty linked lists 'a' and 'b'static Node sortedMerge(Node a, Node b){ // Reverse Linked List 'a' a = reverseList(a); // Reverse Linked List 'b' b = reverseList(b); // Initialize head of resultant list Node head = null; Node temp; // Traverse both lists while both of them // have nodes. while (a != null && b != null) { // If a's current value is greater than or equal to // b's current value. if (a.key >= b.key) { // Store next of current Node in first list temp = a.next; // Add 'a' at the front of resultant list a.next = head; // Make 'a' - head of the result list head = a; // Move ahead in first list a = temp; } // If b's value is greater. Below steps are similar // to above (Only 'a' is replaced with 'b') else { temp = b.next; b.next = head; head = b; b = temp; } } // If second list reached end, but first list has // nodes. Add remaining nodes of first list at the // beginning of result list while (a != null) { temp = a.next; a.next = head; head = a; a = temp; } // If first list reached end, but second list has // nodes. Add remaining nodes of second list at the // beginning of result list while (b != null) { temp = b.next; b.next = head; head = b; b = temp; } // Return the head of the result list return head;} /* Function to print Nodes in a given linked list */static void printList(Node Node){ while (Node != null) { System.out.print(Node.key+ \" \"); Node = Node.next; }} /* Utility function to create a new node with given key */static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.next = null; return temp;} /* Driver program to test above functions*/public static void main(String[] args){ /* Start with the empty list */ Node res = null; /* Let us create two sorted linked lists to test the above functions. Created lists shall be a: 5.10.15.40 b: 2.3.20 */ Node a = newNode(5); a.next = newNode(10); a.next.next = newNode(15); a.next.next.next = newNode(40); Node b = newNode(2); b.next = newNode(3); b.next.next = newNode(20); System.out.print(\"List A before merge: \\n\"); printList(a); System.out.print(\"\\nList B before merge: \\n\"); printList(b); /* merge 2 sorted Linked Lists */ res = sortedMerge(a, b); System.out.print(\"\\nMerged Linked List is: \\n\"); printList(res);}} // This code is contributed by umadevi9616", "e": 61445, "s": 58171, "text": null }, { "code": "/*Given two sorted linked lists consisting of N and M nodesrespectively. The task is to merge both of the list(in-place) and return head of the merged list.*/ using System;using System.Collections.Generic; public class GFG{ /* Link list Node */public class Node { public int key; public Node next;}; // Function to reverse a given Linked List using Recursionstatic Node reverseList(Node head){ if (head.next == null) return head; Node rest = reverseList(head.next); head.next.next = head; head.next = null; return rest;} // Given two non-empty linked lists 'a' and 'b'static Node sortedMerge(Node a, Node b){ // Reverse Linked List 'a' a = reverseList(a); // Reverse Linked List 'b' b = reverseList(b); // Initialize head of resultant list Node head = null; Node temp; // Traverse both lists while both of them // have nodes. while (a != null && b != null) { // If a's current value is greater than or equal to // b's current value. if (a.key >= b.key) { // Store next of current Node in first list temp = a.next; // Add 'a' at the front of resultant list a.next = head; // Make 'a' - head of the result list head = a; // Move ahead in first list a = temp; } // If b's value is greater. Below steps are similar // to above (Only 'a' is replaced with 'b') else { temp = b.next; b.next = head; head = b; b = temp; } } // If second list reached end, but first list has // nodes. Add remaining nodes of first list at the // beginning of result list while (a != null) { temp = a.next; a.next = head; head = a; a = temp; } // If first list reached end, but second list has // nodes. Add remaining nodes of second list at the // beginning of result list while (b != null) { temp = b.next; b.next = head; head = b; b = temp; } // Return the head of the result list return head;} /* Function to print Nodes in a given linked list */static void printList(Node Node){ while (Node != null) { Console.Write(Node.key+ \" \"); Node = Node.next; }} /* Utility function to create a new node with given key */static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.next = null; return temp;} /* Driver program to test above functions*/public static void Main(String[] args){ /* Start with the empty list */ Node res = null; /* Let us create two sorted linked lists to test the above functions. Created lists shall be a: 5.10.15.40 b: 2.3.20 */ Node a = newNode(5); a.next = newNode(10); a.next.next = newNode(15); a.next.next.next = newNode(40); Node b = newNode(2); b.next = newNode(3); b.next.next = newNode(20); Console.Write(\"List A before merge: \\n\"); printList(a); Console.Write(\"\\nList B before merge: \\n\"); printList(b); /* merge 2 sorted Linked Lists */ res = sortedMerge(a, b); Console.Write(\"\\nMerged Linked List is: \\n\"); printList(res);}} // This code is contributed by umadevi9616", "e": 64755, "s": 61445, "text": null }, { "code": null, "e": 64763, "s": 64755, "text": "Output:" }, { "code": null, "e": 64870, "s": 64763, "text": "List A before merge: \n5 10 15 40 \nList B before merge: \n2 3 20 \nMerged Linked List is: \n2 3 5 10 15 20 40 " }, { "code": null, "e": 65037, "s": 64870, "text": "Time Complexity: Since we are traversing through the two lists fully. So, the time complexity is O(m+n) where m and n are the lengths of the two lists to be merged. " }, { "code": null, "e": 65097, "s": 65037, "text": "This method is contributed by Mehul Mathur(mathurmehul01). " }, { "code": null, "e": 65132, "s": 65097, "text": "This idea is similar to this post." }, { "code": null, "e": 65400, "s": 65132, "text": "Please refer below post for simpler implementations : Merge two sorted lists (in-place)Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdfPlease write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem." }, { "code": null, "e": 65414, "s": 65400, "text": "Shubhaw Kumar" }, { "code": null, "e": 65426, "s": 65414, "text": "29AjayKumar" }, { "code": null, "e": 65440, "s": 65426, "text": "rathbhupendra" }, { "code": null, "e": 65453, "s": 65440, "text": "tuhindas221b" }, { "code": null, "e": 65469, "s": 65453, "text": "AmiyaRanjanRout" }, { "code": null, "e": 65480, "s": 65469, "text": "hunter2000" }, { "code": null, "e": 65488, "s": 65480, "text": "ryadav2" }, { "code": null, "e": 65502, "s": 65488, "text": "mathurmehul01" }, { "code": null, "e": 65514, "s": 65502, "text": "umadevi9616" }, { "code": null, "e": 65528, "s": 65514, "text": "GauravRajput1" }, { "code": null, "e": 65536, "s": 65528, "text": "rag2127" }, { "code": null, "e": 65546, "s": 65536, "text": "patel2127" }, { "code": null, "e": 65562, "s": 65546, "text": "simranarora5sos" }, { "code": null, "e": 65575, "s": 65562, "text": "simmytarika5" }, { "code": null, "e": 65592, "s": 65575, "text": "surinderdawra388" }, { "code": null, "e": 65607, "s": 65592, "text": "adityakumar129" }, { "code": null, "e": 65616, "s": 65607, "text": "Accolite" }, { "code": null, "e": 65623, "s": 65616, "text": "Amazon" }, { "code": null, "e": 65632, "s": 65623, "text": "Belzabar" }, { "code": null, "e": 65640, "s": 65632, "text": "Brocade" }, { "code": null, "e": 65648, "s": 65640, "text": "FactSet" }, { "code": null, "e": 65657, "s": 65648, "text": "Flipkart" }, { "code": null, "e": 65668, "s": 65657, "text": "MakeMyTrip" }, { "code": null, "e": 65679, "s": 65668, "text": "Merge Sort" }, { "code": null, "e": 65689, "s": 65679, "text": "Microsoft" }, { "code": null, "e": 65702, "s": 65689, "text": "OATS Systems" }, { "code": null, "e": 65709, "s": 65702, "text": "Oracle" }, { "code": null, "e": 65717, "s": 65709, "text": "Samsung" }, { "code": null, "e": 65726, "s": 65717, "text": "Synopsys" }, { "code": null, "e": 65731, "s": 65726, "text": "Zoho" }, { "code": null, "e": 65743, "s": 65731, "text": "Linked List" }, { "code": null, "e": 65748, "s": 65743, "text": "Zoho" }, { "code": null, "e": 65757, "s": 65748, "text": "Flipkart" }, { "code": null, "e": 65766, "s": 65757, "text": "Accolite" }, { "code": null, "e": 65773, "s": 65766, "text": "Amazon" }, { "code": null, "e": 65783, "s": 65773, "text": "Microsoft" }, { "code": null, "e": 65791, "s": 65783, "text": "Samsung" }, { "code": null, "e": 65799, "s": 65791, "text": "FactSet" }, { "code": null, "e": 65810, "s": 65799, "text": "MakeMyTrip" }, { "code": null, "e": 65817, "s": 65810, "text": "Oracle" }, { "code": null, "e": 65825, "s": 65817, "text": "Brocade" }, { "code": null, "e": 65834, "s": 65825, "text": "Synopsys" }, { "code": null, "e": 65847, "s": 65834, "text": "OATS Systems" }, { "code": null, "e": 65856, "s": 65847, "text": "Belzabar" }, { "code": null, "e": 65868, "s": 65856, "text": "Linked List" }, { "code": null, "e": 65879, "s": 65868, "text": "Merge Sort" }, { "code": null, "e": 65977, "s": 65879, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 65986, "s": 65977, "text": "Comments" }, { "code": null, "e": 65999, "s": 65986, "text": "Old Comments" }, { "code": null, "e": 66045, "s": 65999, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 66080, "s": 66045, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 66123, "s": 66080, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 66170, "s": 66123, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 66231, "s": 66170, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 66275, "s": 66231, "text": "Remove duplicates from a sorted linked list" }, { "code": null, "e": 66330, "s": 66275, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 66386, "s": 66330, "text": "Function to check if a singly linked list is palindrome" }, { "code": null, "e": 66447, "s": 66386, "text": "Search an element in a Linked List (Iterative and Recursive)" } ]
Tryit Editor v3.7
Tryit: HTML image map - circle area
[]
Sentence Palindrome (Palindrome after removing spaces, dots, .. etc) - GeeksforGeeks
14 Mar, 2022 Write a program to check if a sentence is a palindrome or not. You can ignore white spaces and other characters to consider sentences as palindrome.Examples: Input : str = "Too hot to hoot." Output : Sentence is palindrome. Input : str = "Abc def ghi jklm." Output : Sentence is not palindrome. Note that there may be multiple spaces and/or dots between two words. To find if a sentence is palindrome, compare each character from left and right. If they are equal, compare until left and right of string are equal or right becomes less than left. Remember to ignore white spaces and other characters in a string. C++ Java Python3 C# PHP Javascript // CPP program to find if a sentence is// palindrome#include <bits/stdc++.h>using namespace std; // To check sentence is palindrome or notbool sentencePalindrome(string str){ int l = 0, h = str.length() - 1; // Lowercase string for (int i = 0; i <= h; i++) str[i] = tolower(str[i]); // Compares character until they are equal while (l <= h) { // If there is another symbol in left // of sentence if (!(str[l] >= 'a' && str[l] <= 'z')) l++; // If there is another symbol in right // of sentence else if (!(str[h] >= 'a' && str[h] <= 'z')) h--; // If characters are equal else if (str[l] == str[h]) l++, h--; // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence is palindrome return true;} // Driver program to test sentencePalindrome()int main(){ string str = "Too hot to hoot."; if (sentencePalindrome(str)) cout << "Sentence is palindrome."; else cout << "Sentence is not palindrome."; return 0;} // Java program to find if a sentence is// palindromepublic class GFG{ // To check sentence is palindrome or not static boolean sentencePalindrome(String str) { int l = 0; int h = str.length()-1; // Lowercase string str = str.toLowerCase(); // Compares character until they are equal while(l <= h) { char getAtl = str.charAt(l); char getAth = str.charAt(h); // If there is another symbol in left // of sentence if (!(getAtl >= 'a' && getAtl <= 'z')) l++; // If there is another symbol in right // of sentence else if(!(getAth >= 'a' && getAth <= 'z')) h--; // If characters are equal else if( getAtl == getAth) { l++; h--; } // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence is palindrome return true; } // Driver program to test sentencePallindrome() public static void main(String[] args) { String str = "Too hot to hoot."; if( sentencePalindrome(str)) System.out.println("Sentence is palindrome"); else System.out.println("Sentence is not" + " " + "palindrome"); }} //This code is contributed by Sumit Ghosh # Python program to find if a sentence is# palindrome# To check sentence is palindrome or notdef sentencePalindrome(s): l, h = 0, len(s) - 1 # Lowercase string s = s.lower() # Compares character until they are equal while (l <= h): # If there is another symbol in left # of sentence if (not(s[l] >= 'a' and s[l] <= 'z')): l += 1 # If there is another symbol in right # of sentence else if (not(s[h] >= 'a' and s[h] <= 'z')): h -= 1 # If characters are equal else if (s[l] == s[h]): l += 1 h -= 1 # If characters are not equal then # sentence is not palindrome else: return False # Returns true if sentence is palindrome return True # Driver program to test sentencePalindrome()s = "Too hot to hoot."if (sentencePalindrome(s)): print ("Sentence is palindrome.")else: print ("Sentence is not palindrome.") # This code is contributed by Sachin Bisht // C# program to find if a// sentence is palindromeusing System; public class GFG{ // To check sentence is // palindrome or not static bool sentencePalindrome(String str) { int l = 0; int h = str.Length - 1; // Lowercase string str = str.ToLower(); // Compares character until // they are equal while(l <= h) { char getAtl = str[l]; char getAth = str[h]; // If there is another symbol // in left of sentence if (!(getAtl >= 'a' && getAtl <= 'z')) l++; // If there is another symbol // in right of sentence else if(! (getAth >= 'a' && getAth <= 'z')) h--; // If characters are equal else if( getAtl == getAth) { l++; h--; } // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence // is palindrome return true; } // Driver Code public static void Main() { String str = "Too hot to hoot."; if( sentencePalindrome(str)) Console.Write("Sentence is palindrome"); else Console.Write("Sentence is not" + " " + "palindrome"); }} // This code is contributed by Nitin Mittal. <?php// PHP program to find if a sentence is// palindrome // To check sentence is palindrome or notfunction sentencePalindrome($str){ $l = 0; $h = strlen($str)-1; // Lowercase string for ($i = 0; $i < $h; $i++) $str[$i] = strtolower($str[$i]); // Compares character until they are equal while ($l <= $h) { // If there is another symbol in left // of sentence if (!($str[$l] >= 'a' && $str[$l] <= 'z')) $l++; // If there is another symbol in right // of sentence else if (!($str[$h] >= 'a' && $str[$h] <= 'z')) $h--; // If characters are equal else if ($str[$l] == $str[$h]) { $l++; $h--; } // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence is palindrome return true;} // Driver program to test sentencePalindrome() $str = "Too hot to hoot."; if (sentencePalindrome($str)) echo "Sentence is palindrome.";else echo "Sentence is not palindrome."; return 0;?> <script>// Javascript program to find if a sentence is// palindrome // To check sentence is palindrome or not function sentencePalindrome(str) { let l = 0; let h = str.length-1; // Lowercase string str = str.toLowerCase(); // Compares character until they are equal while(l <= h) { let getAtl = str[l]; let getAth = str[h]; // If there is another symbol in left // of sentence if (!(getAtl >= 'a' && getAtl <= 'z')) l++; // If there is another symbol in right // of sentence else if(!(getAth >= 'a' && getAth <= 'z')) h--; // If characters are equal else if( getAtl == getAth) { l++; h--; } // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence is palindrome return true; } // Driver program to test sentencePallindrome() let str = "Too hot to hoot."; if( sentencePalindrome(str)) document.write("Sentence is palindrome"); else document.write("Sentence is not" + " " + "palindrome"); //This code is contributed by avanitrachhadiya2155 </script> Output: Sentence is palindrome. Time Complexity: O(N) where N is the length of the sentenceSpace Complexity: O(1) This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal ukasp shivanshuayachi avanitrachhadiya2155 CoderSaty amartyaghoshgfg surinderdawra388 palindrome Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Check for Balanced Brackets in an expression (well-formedness) using Stack KMP Algorithm for Pattern Searching Convert string to char array in C++ Array of Strings in C++ (5 Different Ways to Create) Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Length of the longest substring without repeating characters Check whether two strings are anagram of each other How to split a string in C/C++, Python and Java? Remove duplicates from a given string
[ { "code": null, "e": 24607, "s": 24579, "text": "\n14 Mar, 2022" }, { "code": null, "e": 24766, "s": 24607, "text": "Write a program to check if a sentence is a palindrome or not. You can ignore white spaces and other characters to consider sentences as palindrome.Examples: " }, { "code": null, "e": 24904, "s": 24766, "text": "Input : str = \"Too hot to hoot.\"\nOutput : Sentence is palindrome.\n\nInput : str = \"Abc def ghi jklm.\"\nOutput : Sentence is not palindrome." }, { "code": null, "e": 24975, "s": 24904, "text": "Note that there may be multiple spaces and/or dots between two words. " }, { "code": null, "e": 25225, "s": 24975, "text": "To find if a sentence is palindrome, compare each character from left and right. If they are equal, compare until left and right of string are equal or right becomes less than left. Remember to ignore white spaces and other characters in a string. " }, { "code": null, "e": 25229, "s": 25225, "text": "C++" }, { "code": null, "e": 25234, "s": 25229, "text": "Java" }, { "code": null, "e": 25242, "s": 25234, "text": "Python3" }, { "code": null, "e": 25245, "s": 25242, "text": "C#" }, { "code": null, "e": 25249, "s": 25245, "text": "PHP" }, { "code": null, "e": 25260, "s": 25249, "text": "Javascript" }, { "code": "// CPP program to find if a sentence is// palindrome#include <bits/stdc++.h>using namespace std; // To check sentence is palindrome or notbool sentencePalindrome(string str){ int l = 0, h = str.length() - 1; // Lowercase string for (int i = 0; i <= h; i++) str[i] = tolower(str[i]); // Compares character until they are equal while (l <= h) { // If there is another symbol in left // of sentence if (!(str[l] >= 'a' && str[l] <= 'z')) l++; // If there is another symbol in right // of sentence else if (!(str[h] >= 'a' && str[h] <= 'z')) h--; // If characters are equal else if (str[l] == str[h]) l++, h--; // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence is palindrome return true;} // Driver program to test sentencePalindrome()int main(){ string str = \"Too hot to hoot.\"; if (sentencePalindrome(str)) cout << \"Sentence is palindrome.\"; else cout << \"Sentence is not palindrome.\"; return 0;}", "e": 26418, "s": 25260, "text": null }, { "code": "// Java program to find if a sentence is// palindromepublic class GFG{ // To check sentence is palindrome or not static boolean sentencePalindrome(String str) { int l = 0; int h = str.length()-1; // Lowercase string str = str.toLowerCase(); // Compares character until they are equal while(l <= h) { char getAtl = str.charAt(l); char getAth = str.charAt(h); // If there is another symbol in left // of sentence if (!(getAtl >= 'a' && getAtl <= 'z')) l++; // If there is another symbol in right // of sentence else if(!(getAth >= 'a' && getAth <= 'z')) h--; // If characters are equal else if( getAtl == getAth) { l++; h--; } // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence is palindrome return true; } // Driver program to test sentencePallindrome() public static void main(String[] args) { String str = \"Too hot to hoot.\"; if( sentencePalindrome(str)) System.out.println(\"Sentence is palindrome\"); else System.out.println(\"Sentence is not\" + \" \" + \"palindrome\"); }} //This code is contributed by Sumit Ghosh", "e": 28010, "s": 26418, "text": null }, { "code": "# Python program to find if a sentence is# palindrome# To check sentence is palindrome or notdef sentencePalindrome(s): l, h = 0, len(s) - 1 # Lowercase string s = s.lower() # Compares character until they are equal while (l <= h): # If there is another symbol in left # of sentence if (not(s[l] >= 'a' and s[l] <= 'z')): l += 1 # If there is another symbol in right # of sentence else if (not(s[h] >= 'a' and s[h] <= 'z')): h -= 1 # If characters are equal else if (s[l] == s[h]): l += 1 h -= 1 # If characters are not equal then # sentence is not palindrome else: return False # Returns true if sentence is palindrome return True # Driver program to test sentencePalindrome()s = \"Too hot to hoot.\"if (sentencePalindrome(s)): print (\"Sentence is palindrome.\")else: print (\"Sentence is not palindrome.\") # This code is contributed by Sachin Bisht", "e": 29042, "s": 28010, "text": null }, { "code": "// C# program to find if a// sentence is palindromeusing System; public class GFG{ // To check sentence is // palindrome or not static bool sentencePalindrome(String str) { int l = 0; int h = str.Length - 1; // Lowercase string str = str.ToLower(); // Compares character until // they are equal while(l <= h) { char getAtl = str[l]; char getAth = str[h]; // If there is another symbol // in left of sentence if (!(getAtl >= 'a' && getAtl <= 'z')) l++; // If there is another symbol // in right of sentence else if(! (getAth >= 'a' && getAth <= 'z')) h--; // If characters are equal else if( getAtl == getAth) { l++; h--; } // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence // is palindrome return true; } // Driver Code public static void Main() { String str = \"Too hot to hoot.\"; if( sentencePalindrome(str)) Console.Write(\"Sentence is palindrome\"); else Console.Write(\"Sentence is not\" + \" \" + \"palindrome\"); }} // This code is contributed by Nitin Mittal.", "e": 30630, "s": 29042, "text": null }, { "code": "<?php// PHP program to find if a sentence is// palindrome // To check sentence is palindrome or notfunction sentencePalindrome($str){ $l = 0; $h = strlen($str)-1; // Lowercase string for ($i = 0; $i < $h; $i++) $str[$i] = strtolower($str[$i]); // Compares character until they are equal while ($l <= $h) { // If there is another symbol in left // of sentence if (!($str[$l] >= 'a' && $str[$l] <= 'z')) $l++; // If there is another symbol in right // of sentence else if (!($str[$h] >= 'a' && $str[$h] <= 'z')) $h--; // If characters are equal else if ($str[$l] == $str[$h]) { $l++; $h--; } // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence is palindrome return true;} // Driver program to test sentencePalindrome() $str = \"Too hot to hoot.\"; if (sentencePalindrome($str)) echo \"Sentence is palindrome.\";else echo \"Sentence is not palindrome.\"; return 0;?>", "e": 31763, "s": 30630, "text": null }, { "code": "<script>// Javascript program to find if a sentence is// palindrome // To check sentence is palindrome or not function sentencePalindrome(str) { let l = 0; let h = str.length-1; // Lowercase string str = str.toLowerCase(); // Compares character until they are equal while(l <= h) { let getAtl = str[l]; let getAth = str[h]; // If there is another symbol in left // of sentence if (!(getAtl >= 'a' && getAtl <= 'z')) l++; // If there is another symbol in right // of sentence else if(!(getAth >= 'a' && getAth <= 'z')) h--; // If characters are equal else if( getAtl == getAth) { l++; h--; } // If characters are not equal then // sentence is not palindrome else return false; } // Returns true if sentence is palindrome return true; } // Driver program to test sentencePallindrome() let str = \"Too hot to hoot.\"; if( sentencePalindrome(str)) document.write(\"Sentence is palindrome\"); else document.write(\"Sentence is not\" + \" \" + \"palindrome\"); //This code is contributed by avanitrachhadiya2155 </script>", "e": 33286, "s": 31763, "text": null }, { "code": null, "e": 33295, "s": 33286, "text": "Output: " }, { "code": null, "e": 33319, "s": 33295, "text": "Sentence is palindrome." }, { "code": null, "e": 33402, "s": 33319, "text": "Time Complexity: O(N) where N is the length of the sentenceSpace Complexity: O(1) " }, { "code": null, "e": 33818, "s": 33402, "text": "This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33831, "s": 33818, "text": "nitin mittal" }, { "code": null, "e": 33837, "s": 33831, "text": "ukasp" }, { "code": null, "e": 33853, "s": 33837, "text": "shivanshuayachi" }, { "code": null, "e": 33874, "s": 33853, "text": "avanitrachhadiya2155" }, { "code": null, "e": 33884, "s": 33874, "text": "CoderSaty" }, { "code": null, "e": 33900, "s": 33884, "text": "amartyaghoshgfg" }, { "code": null, "e": 33917, "s": 33900, "text": "surinderdawra388" }, { "code": null, "e": 33928, "s": 33917, "text": "palindrome" }, { "code": null, "e": 33936, "s": 33928, "text": "Strings" }, { "code": null, "e": 33944, "s": 33936, "text": "Strings" }, { "code": null, "e": 33955, "s": 33944, "text": "palindrome" }, { "code": null, "e": 34053, "s": 33955, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34062, "s": 34053, "text": "Comments" }, { "code": null, "e": 34075, "s": 34062, "text": "Old Comments" }, { "code": null, "e": 34150, "s": 34075, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 34186, "s": 34150, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 34222, "s": 34186, "text": "Convert string to char array in C++" }, { "code": null, "e": 34275, "s": 34222, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 34313, "s": 34275, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 34343, "s": 34313, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 34404, "s": 34343, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 34456, "s": 34404, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 34505, "s": 34456, "text": "How to split a string in C/C++, Python and Java?" } ]
Bootstrap 4 .card-img-top class
Use the card-img-top class in Bootstrap to set the image at the top inside a card − <img class="card-img-top" src="Image-Source" alt="ALT-TEXT" style="width:100%"> After that add the card and card body − <div class="card-body"> <h4 class="card-title">Swift 4</h4> <p class="card-text">Learn Swift 4</p> <a href="#" class="btn btn-primary">Begin</a> </div> You can try to run the following code to implement the card-img-top class in Bootstrap 4 − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h3>SWIFT 4 Tutorial</h3> <p>Video Tutorial on Switft 4</p> <div class="card" style="width:350px"> <img class="card-img-top" src="https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg" alt="Swift4" style="width:100%"> <div class="card-body"> <h4 class="card-title">Swift 4</h4> <p class="card-text">Learn Swift 4</p> <a href="#" class="btn btn-primary">Begin</a> </div> </div> </div> </body> </html>
[ { "code": null, "e": 1146, "s": 1062, "text": "Use the card-img-top class in Bootstrap to set the image at the top inside a card −" }, { "code": null, "e": 1226, "s": 1146, "text": "<img class=\"card-img-top\" src=\"Image-Source\" alt=\"ALT-TEXT\" style=\"width:100%\">" }, { "code": null, "e": 1266, "s": 1226, "text": "After that add the card and card body −" }, { "code": null, "e": 1424, "s": 1266, "text": "<div class=\"card-body\">\n <h4 class=\"card-title\">Swift 4</h4>\n <p class=\"card-text\">Learn Swift 4</p>\n <a href=\"#\" class=\"btn btn-primary\">Begin</a>\n</div>" }, { "code": null, "e": 1515, "s": 1424, "text": "You can try to run the following code to implement the card-img-top class in Bootstrap 4 −" }, { "code": null, "e": 1525, "s": 1515, "text": "Live Demo" }, { "code": null, "e": 2559, "s": 1525, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n <div class=\"container\">\n <h3>SWIFT 4 Tutorial</h3>\n <p>Video Tutorial on Switft 4</p>\n <div class=\"card\" style=\"width:350px\">\n <img class=\"card-img-top\" src=\"https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg\" alt=\"Swift4\" style=\"width:100%\">\n <div class=\"card-body\">\n <h4 class=\"card-title\">Swift 4</h4>\n <p class=\"card-text\">Learn Swift 4</p>\n <a href=\"#\" class=\"btn btn-primary\">Begin</a>\n </div>\n </div>\n </div>\n\n</body>\n</html>" } ]
Difference between find() and findOne() methods in MongoDB?
The findOne() returns first document if query matches otherwise returns null. The find() method does not return null, it returns a cursor. Let us implement the concept of find() and findOne() and create a collection with documents − > db.createCollection('emptyCollection'); { "ok" : 1 } Let us count how many documents are in the above collection − > db.emptyCollection.count(); This will produce the following output − 0 There is no document present in the above collection. Following is the query to check the result with findOne() − > if(db.emptyCollection.findOne()){print("Returns Cursor")} else {print("Not returning cursor")} This will produce the following output − Not returning cursor Following is the query to check the result with find() − > if(db.emptyCollection.find()){print("Returns Cursor")} else {print("Not returning cursor")} This will produce the following output − Returns Cursor
[ { "code": null, "e": 1201, "s": 1062, "text": "The findOne() returns first document if query matches otherwise returns null. The find() method does not return null, it returns a cursor." }, { "code": null, "e": 1295, "s": 1201, "text": "Let us implement the concept of find() and findOne() and create a collection with documents −" }, { "code": null, "e": 1350, "s": 1295, "text": "> db.createCollection('emptyCollection');\n{ \"ok\" : 1 }" }, { "code": null, "e": 1412, "s": 1350, "text": "Let us count how many documents are in the above collection −" }, { "code": null, "e": 1442, "s": 1412, "text": "> db.emptyCollection.count();" }, { "code": null, "e": 1483, "s": 1442, "text": "This will produce the following output −" }, { "code": null, "e": 1485, "s": 1483, "text": "0" }, { "code": null, "e": 1539, "s": 1485, "text": "There is no document present in the above collection." }, { "code": null, "e": 1599, "s": 1539, "text": "Following is the query to check the result with findOne() −" }, { "code": null, "e": 1696, "s": 1599, "text": "> if(db.emptyCollection.findOne()){print(\"Returns Cursor\")} else {print(\"Not returning cursor\")}" }, { "code": null, "e": 1737, "s": 1696, "text": "This will produce the following output −" }, { "code": null, "e": 1758, "s": 1737, "text": "Not returning cursor" }, { "code": null, "e": 1815, "s": 1758, "text": "Following is the query to check the result with find() −" }, { "code": null, "e": 1909, "s": 1815, "text": "> if(db.emptyCollection.find()){print(\"Returns Cursor\")} else {print(\"Not returning cursor\")}" }, { "code": null, "e": 1950, "s": 1909, "text": "This will produce the following output −" }, { "code": null, "e": 1965, "s": 1950, "text": "Returns Cursor" } ]
MATLAB - Polynomials
MATLAB represents polynomials as row vectors containing coefficients ordered by descending powers. For example, the equation P(x) = x4 + 7x3 - 5x + 9 could be represented as − p = [1 7 0 -5 9]; The polyval function is used for evaluating a polynomial at a specified value. For example, to evaluate our previous polynomial p, at x = 4, type − p = [1 7 0 -5 9]; polyval(p,4) MATLAB executes the above statements and returns the following result − ans = 693 MATLAB also provides the polyvalm function for evaluating a matrix polynomial. A matrix polynomial is a polynomial with matrices as variables. For example, let us create a square matrix X and evaluate the polynomial p, at X − p = [1 7 0 -5 9]; X = [1 2 -3 4; 2 -5 6 3; 3 1 0 2; 5 -7 3 8]; polyvalm(p, X) MATLAB executes the above statements and returns the following result − ans = 2307 -1769 -939 4499 2314 -2376 -249 4695 2256 -1892 -549 4310 4570 -4532 -1062 9269 The roots function calculates the roots of a polynomial. For example, to calculate the roots of our polynomial p, type − p = [1 7 0 -5 9]; r = roots(p) MATLAB executes the above statements and returns the following result − r = -6.8661 + 0.0000i -1.4247 + 0.0000i 0.6454 + 0.7095i 0.6454 - 0.7095i The function poly is an inverse of the roots function and returns to the polynomial coefficients. For example − p2 = poly(r) MATLAB executes the above statements and returns the following result − p2 = Columns 1 through 3: 1.00000 + 0.00000i 7.00000 + 0.00000i 0.00000 + 0.00000i Columns 4 and 5: -5.00000 - 0.00000i 9.00000 + 0.00000i The polyfit function finds the coefficients of a polynomial that fits a set of data in a least-squares sense. If x and y are two vectors containing the x and y data to be fitted to a n-degree polynomial, then we get the polynomial fitting the data by writing − p = polyfit(x,y,n) Create a script file and type the following code − x = [1 2 3 4 5 6]; y = [5.5 43.1 128 290.7 498.4 978.67]; %data p = polyfit(x,y,4) %get the polynomial % Compute the values of the polyfit estimate over a finer range, % and plot the estimate over the real data values for comparison: x2 = 1:.1:6; y2 = polyval(p,x2); plot(x,y,'o',x2,y2) grid on When you run the file, MATLAB displays the following result − p = 4.1056 -47.9607 222.2598 -362.7453 191.1250 And plots the following graph − 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2317, "s": 2141, "text": "MATLAB represents polynomials as row vectors containing coefficients ordered by descending powers. For example, the equation P(x) = x4 + 7x3 - 5x + 9 could be represented as −" }, { "code": null, "e": 2336, "s": 2317, "text": "p = [1 7 0 -5 9];" }, { "code": null, "e": 2484, "s": 2336, "text": "The polyval function is used for evaluating a polynomial at a specified value. For example, to evaluate our previous polynomial p, at x = 4, type −" }, { "code": null, "e": 2516, "s": 2484, "text": "p = [1 7 0 -5 9];\npolyval(p,4)" }, { "code": null, "e": 2588, "s": 2516, "text": "MATLAB executes the above statements and returns the following result −" }, { "code": null, "e": 2599, "s": 2588, "text": "ans = 693\n" }, { "code": null, "e": 2742, "s": 2599, "text": "MATLAB also provides the polyvalm function for evaluating a matrix polynomial. A matrix polynomial is a polynomial with matrices as variables." }, { "code": null, "e": 2825, "s": 2742, "text": "For example, let us create a square matrix X and evaluate the polynomial p, at X −" }, { "code": null, "e": 2904, "s": 2825, "text": "p = [1 7 0 -5 9];\nX = [1 2 -3 4; 2 -5 6 3; 3 1 0 2; 5 -7 3 8];\npolyvalm(p, X)" }, { "code": null, "e": 2976, "s": 2904, "text": "MATLAB executes the above statements and returns the following result −" }, { "code": null, "e": 3171, "s": 2976, "text": "ans =\n 2307 -1769 -939 4499\n 2314 -2376 -249 4695\n 2256 -1892 -549 4310\n 4570 -4532 -1062 9269\n" }, { "code": null, "e": 3292, "s": 3171, "text": "The roots function calculates the roots of a polynomial. For example, to calculate the roots of our polynomial p, type −" }, { "code": null, "e": 3324, "s": 3292, "text": "p = [1 7 0 -5 9];\nr = roots(p)" }, { "code": null, "e": 3396, "s": 3324, "text": "MATLAB executes the above statements and returns the following result −" }, { "code": null, "e": 3483, "s": 3396, "text": "r =\n -6.8661 + 0.0000i\n -1.4247 + 0.0000i\n 0.6454 + 0.7095i\n 0.6454 - 0.7095i\n" }, { "code": null, "e": 3595, "s": 3483, "text": "The function poly is an inverse of the roots function and returns to the polynomial coefficients. For example −" }, { "code": null, "e": 3608, "s": 3595, "text": "p2 = poly(r)" }, { "code": null, "e": 3680, "s": 3608, "text": "MATLAB executes the above statements and returns the following result −" }, { "code": null, "e": 3848, "s": 3680, "text": "p2 =\n\n Columns 1 through 3:\n\n 1.00000 + 0.00000i 7.00000 + 0.00000i 0.00000 + 0.00000i\n\n Columns 4 and 5:\n\n -5.00000 - 0.00000i 9.00000 + 0.00000i\n" }, { "code": null, "e": 4109, "s": 3848, "text": "The polyfit function finds the coefficients of a polynomial that fits a set of data in a least-squares sense. If x and y are two vectors containing the x and y data to be fitted to a n-degree polynomial, then we get the polynomial fitting the data by writing −" }, { "code": null, "e": 4128, "s": 4109, "text": "p = polyfit(x,y,n)" }, { "code": null, "e": 4179, "s": 4128, "text": "Create a script file and type the following code −" }, { "code": null, "e": 4490, "s": 4179, "text": "x = [1 2 3 4 5 6]; y = [5.5 43.1 128 290.7 498.4 978.67]; %data\np = polyfit(x,y,4) %get the polynomial\n\n% Compute the values of the polyfit estimate over a finer range, \n% and plot the estimate over the real data values for comparison:\nx2 = 1:.1:6; \ny2 = polyval(p,x2);\nplot(x,y,'o',x2,y2)\ngrid on" }, { "code": null, "e": 4552, "s": 4490, "text": "When you run the file, MATLAB displays the following result −" }, { "code": null, "e": 4607, "s": 4552, "text": "p =\n 4.1056 -47.9607 222.2598 -362.7453 191.1250\n" }, { "code": null, "e": 4639, "s": 4607, "text": "And plots the following graph −" }, { "code": null, "e": 4672, "s": 4639, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 4685, "s": 4672, "text": " Nouman Azam" }, { "code": null, "e": 4720, "s": 4685, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 4733, "s": 4720, "text": " Nouman Azam" }, { "code": null, "e": 4766, "s": 4733, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 4775, "s": 4766, "text": " Sanjeev" }, { "code": null, "e": 4808, "s": 4775, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 4824, "s": 4808, "text": " TELCOMA Global" }, { "code": null, "e": 4857, "s": 4824, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 4873, "s": 4857, "text": " TELCOMA Global" }, { "code": null, "e": 4906, "s": 4873, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 4923, "s": 4906, "text": " Phinite Academy" }, { "code": null, "e": 4930, "s": 4923, "text": " Print" }, { "code": null, "e": 4941, "s": 4930, "text": " Add Notes" } ]
Find sum of factorials in an array - GeeksforGeeks
15 Apr, 2021 Given an array arr[] of N integers. The task is to find the sum of factorials of each element of the array. Examples: Input: arr[] = {7, 3, 5, 4, 8} Output: 45510 7! + 3! + 5! + 4! + 8! = 5040 + 6 + 120 + 24 + 40320 = 45510 Input: arr[] = {2, 1, 3} Output: 9 Approach: Implement a function factorial(n) that finds the factorial of n and initialize sum = 0. Now, traverse the given array and for each element arr[i] update sum = sum + factorial(arr[i]). Print the calculated sum in the end. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <iostream>#include <bits/stdc++.h>using namespace std; // Function to return the factorial of nint factorial(int n){ int f = 1; for (int i = 1; i <= n; i++) { f *= i; } return f;} // Function to return the sum of// factorials of the array elementsint sumFactorial(int *arr, int n){ // To store the required sum int s = 0,i; for (i = 0; i < n; i++) { // Add factorial of all the elements s += factorial(arr[i]); } return s;} // Driver codeint main(){ int arr[] = { 7, 3, 5, 4, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << sumFactorial(arr, n); return 0;} // This code is contributed by 29AjayKumar // Java implementation of the approachclass GFG { // Function to return the factorial of n static int factorial(int n) { int f = 1; for (int i = 1; i <= n; i++) { f *= i; } return f; } // Function to return the sum of // factorials of the array elements static int sumFactorial(int[] arr, int n) { // To store the required sum int s = 0; for (int i = 0; i < n; i++) { // Add factorial of all the elements s += factorial(arr[i]); } return s; } // Driver Code public static void main(String[] args) { int[] arr = { 7, 3, 5, 4, 8 }; int n = arr.length; System.out.println(sumFactorial(arr, n)); }} # Python implementation of the approach # Function to return the factorial of ndef factorial(n): f = 1; for i in range(1, n + 1): f *= i; return f; # Function to return the sum of# factorials of the array elementsdef sumFactorial(arr, n): # To store the required sum s = 0; for i in range(0,n): # Add factorial of all the elements s += factorial(arr[i]); return s; # Driver codearr = [7, 3, 5, 4, 8 ];n = len(arr);print(sumFactorial(arr, n)); # This code contributed by Rajput-Ji // C# implementation of the approachusing System; class GFG{ // Function to return the factorial of n static int factorial(int n) { int f = 1; for (int i = 1; i <= n; i++) { f *= i; } return f; } // Function to return the sum of // factorials of the array elements static int sumFactorial(int[] arr, int n) { // To store the required sum int s = 0; for (int i = 0; i < n; i++) { // Add factorial of all the elements s += factorial(arr[i]); } return s; } // Driver Code public static void Main() { int[] arr = { 7, 3, 5, 4, 8 }; int n = arr.Length; Console.WriteLine(sumFactorial(arr, n)); }} // This code is contributed by Ryuga <?php // PHP implementation of the approach // Function to return the factorial of nfunction factorial( $n){ $f = 1; for ( $i = 1; $i <= $n; $i++) { $f *=$i; } return $f;} // Function to return the sum of// factorials of the array elementsfunction sumFactorial($arr, $n){ // To store the required sum $s = 0; for ($i = 0; $i < $n; $i++) { // Add factorial of all the elements $s += factorial($arr[$i]); } return $s;} // Driver code $arr = array( 7, 3, 5, 4, 8 );$n = sizeof($arr);echo sumFactorial($arr, $n); // This code is contributed by ihritik ?> <script> // Javascript implementation of the approach // Function to return the factorial of nfunction factorial(n){ let f = 1; for(let i = 1; i <= n; i++) { f *= i; } return f;} // Function to return the sum of// factorials of the array elementsfunction sumFactorial(arr, n){ // To store the required sum let s = 0; for (let i = 0; i < n; i++) { // Add factorial of all the elements s += factorial(arr[i]); } return s;} // Driver codelet arr = [ 7, 3, 5, 4, 8 ];let n = arr.length; document.write(sumFactorial(arr, n)); // This code is contributed by bobby </script> 45510 ankthon 29AjayKumar Rajput-Ji ihritik gottumukkalabobby factorial Arrays Mathematical School Programming Arrays Mathematical factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers
[ { "code": null, "e": 25388, "s": 25360, "text": "\n15 Apr, 2021" }, { "code": null, "e": 25496, "s": 25388, "text": "Given an array arr[] of N integers. The task is to find the sum of factorials of each element of the array." }, { "code": null, "e": 25507, "s": 25496, "text": "Examples: " }, { "code": null, "e": 25613, "s": 25507, "text": "Input: arr[] = {7, 3, 5, 4, 8} Output: 45510 7! + 3! + 5! + 4! + 8! = 5040 + 6 + 120 + 24 + 40320 = 45510" }, { "code": null, "e": 25650, "s": 25613, "text": "Input: arr[] = {2, 1, 3} Output: 9 " }, { "code": null, "e": 25881, "s": 25650, "text": "Approach: Implement a function factorial(n) that finds the factorial of n and initialize sum = 0. Now, traverse the given array and for each element arr[i] update sum = sum + factorial(arr[i]). Print the calculated sum in the end." }, { "code": null, "e": 25934, "s": 25881, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25938, "s": 25934, "text": "C++" }, { "code": null, "e": 25943, "s": 25938, "text": "Java" }, { "code": null, "e": 25951, "s": 25943, "text": "Python3" }, { "code": null, "e": 25954, "s": 25951, "text": "C#" }, { "code": null, "e": 25958, "s": 25954, "text": "PHP" }, { "code": null, "e": 25969, "s": 25958, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>#include <bits/stdc++.h>using namespace std; // Function to return the factorial of nint factorial(int n){ int f = 1; for (int i = 1; i <= n; i++) { f *= i; } return f;} // Function to return the sum of// factorials of the array elementsint sumFactorial(int *arr, int n){ // To store the required sum int s = 0,i; for (i = 0; i < n; i++) { // Add factorial of all the elements s += factorial(arr[i]); } return s;} // Driver codeint main(){ int arr[] = { 7, 3, 5, 4, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << sumFactorial(arr, n); return 0;} // This code is contributed by 29AjayKumar", "e": 26690, "s": 25969, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the factorial of n static int factorial(int n) { int f = 1; for (int i = 1; i <= n; i++) { f *= i; } return f; } // Function to return the sum of // factorials of the array elements static int sumFactorial(int[] arr, int n) { // To store the required sum int s = 0; for (int i = 0; i < n; i++) { // Add factorial of all the elements s += factorial(arr[i]); } return s; } // Driver Code public static void main(String[] args) { int[] arr = { 7, 3, 5, 4, 8 }; int n = arr.length; System.out.println(sumFactorial(arr, n)); }}", "e": 27446, "s": 26690, "text": null }, { "code": "# Python implementation of the approach # Function to return the factorial of ndef factorial(n): f = 1; for i in range(1, n + 1): f *= i; return f; # Function to return the sum of# factorials of the array elementsdef sumFactorial(arr, n): # To store the required sum s = 0; for i in range(0,n): # Add factorial of all the elements s += factorial(arr[i]); return s; # Driver codearr = [7, 3, 5, 4, 8 ];n = len(arr);print(sumFactorial(arr, n)); # This code contributed by Rajput-Ji", "e": 27970, "s": 27446, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the factorial of n static int factorial(int n) { int f = 1; for (int i = 1; i <= n; i++) { f *= i; } return f; } // Function to return the sum of // factorials of the array elements static int sumFactorial(int[] arr, int n) { // To store the required sum int s = 0; for (int i = 0; i < n; i++) { // Add factorial of all the elements s += factorial(arr[i]); } return s; } // Driver Code public static void Main() { int[] arr = { 7, 3, 5, 4, 8 }; int n = arr.Length; Console.WriteLine(sumFactorial(arr, n)); }} // This code is contributed by Ryuga", "e": 28774, "s": 27970, "text": null }, { "code": "<?php // PHP implementation of the approach // Function to return the factorial of nfunction factorial( $n){ $f = 1; for ( $i = 1; $i <= $n; $i++) { $f *=$i; } return $f;} // Function to return the sum of// factorials of the array elementsfunction sumFactorial($arr, $n){ // To store the required sum $s = 0; for ($i = 0; $i < $n; $i++) { // Add factorial of all the elements $s += factorial($arr[$i]); } return $s;} // Driver code $arr = array( 7, 3, 5, 4, 8 );$n = sizeof($arr);echo sumFactorial($arr, $n); // This code is contributed by ihritik ?> ", "e": 29386, "s": 28774, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the factorial of nfunction factorial(n){ let f = 1; for(let i = 1; i <= n; i++) { f *= i; } return f;} // Function to return the sum of// factorials of the array elementsfunction sumFactorial(arr, n){ // To store the required sum let s = 0; for (let i = 0; i < n; i++) { // Add factorial of all the elements s += factorial(arr[i]); } return s;} // Driver codelet arr = [ 7, 3, 5, 4, 8 ];let n = arr.length; document.write(sumFactorial(arr, n)); // This code is contributed by bobby </script>", "e": 30018, "s": 29386, "text": null }, { "code": null, "e": 30024, "s": 30018, "text": "45510" }, { "code": null, "e": 30034, "s": 30026, "text": "ankthon" }, { "code": null, "e": 30046, "s": 30034, "text": "29AjayKumar" }, { "code": null, "e": 30056, "s": 30046, "text": "Rajput-Ji" }, { "code": null, "e": 30064, "s": 30056, "text": "ihritik" }, { "code": null, "e": 30082, "s": 30064, "text": "gottumukkalabobby" }, { "code": null, "e": 30092, "s": 30082, "text": "factorial" }, { "code": null, "e": 30099, "s": 30092, "text": "Arrays" }, { "code": null, "e": 30112, "s": 30099, "text": "Mathematical" }, { "code": null, "e": 30131, "s": 30112, "text": "School Programming" }, { "code": null, "e": 30138, "s": 30131, "text": "Arrays" }, { "code": null, "e": 30151, "s": 30138, "text": "Mathematical" }, { "code": null, "e": 30161, "s": 30151, "text": "factorial" }, { "code": null, "e": 30259, "s": 30161, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30268, "s": 30259, "text": "Comments" }, { "code": null, "e": 30281, "s": 30268, "text": "Old Comments" }, { "code": null, "e": 30329, "s": 30281, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 30373, "s": 30329, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 30396, "s": 30373, "text": "Introduction to Arrays" }, { "code": null, "e": 30428, "s": 30396, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30442, "s": 30428, "text": "Linear Search" }, { "code": null, "e": 30472, "s": 30442, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30487, "s": 30472, "text": "C++ Data Types" }, { "code": null, "e": 30547, "s": 30487, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 30590, "s": 30547, "text": "Set in C++ Standard Template Library (STL)" } ]
HTML contenteditable Attribute
The contenteditable attribute in HTML is used to set whether the content is editable or not using boolean values true or false. This attribute can be used with any element since it is a Global Attribute. Following is the syntax − <element contenteditable =”true|false”> Above, set true if you want the element to be editable, else false. Let us now see an example to implement the contenteditable attribute in HTML − Live Demo <!DOCTYPE html> <html> <body> <h2 contenteditable="true">Demo Heading</h2> <p contenteditable="true">This is a demo line.</p> </body> </html> This will produce the following output. Displaying the heading and p elements are now editable − Now, we can edit the heading and content. Therefore, let us change the heading and display the screenshot − In the above example, we have set a heading and some text − <h2 contenteditable="true">Demo Heading</h2> <p contenteditable="true">This is a demo line.</p> We have made the heading and the content as editable using the contenteditable property. On setting it true, you will be able to edit it on the web page itself − h2 contenteditable="true"
[ { "code": null, "e": 1266, "s": 1062, "text": "The contenteditable attribute in HTML is used to set whether the content is editable or not using boolean values true or false. This attribute can be used with any element since it is a Global Attribute." }, { "code": null, "e": 1292, "s": 1266, "text": "Following is the syntax −" }, { "code": null, "e": 1332, "s": 1292, "text": "<element contenteditable =”true|false”>" }, { "code": null, "e": 1401, "s": 1332, "text": "Above, set true if you want the element to be editable, else false. " }, { "code": null, "e": 1480, "s": 1401, "text": "Let us now see an example to implement the contenteditable attribute in HTML −" }, { "code": null, "e": 1491, "s": 1480, "text": " Live Demo" }, { "code": null, "e": 1639, "s": 1491, "text": "<!DOCTYPE html>\n<html>\n<body>\n <h2 contenteditable=\"true\">Demo Heading</h2>\n <p contenteditable=\"true\">This is a demo line.</p>\n</body>\n</html>" }, { "code": null, "e": 1736, "s": 1639, "text": "This will produce the following output. Displaying the heading and p elements are now editable −" }, { "code": null, "e": 1844, "s": 1736, "text": "Now, we can edit the heading and content. Therefore, let us change the heading and display the screenshot −" }, { "code": null, "e": 1904, "s": 1844, "text": "In the above example, we have set a heading and some text −" }, { "code": null, "e": 2000, "s": 1904, "text": "<h2 contenteditable=\"true\">Demo Heading</h2>\n<p contenteditable=\"true\">This is a demo line.</p>" }, { "code": null, "e": 2162, "s": 2000, "text": "We have made the heading and the content as editable using the contenteditable property. On setting it true, you will be able to edit it on the web page itself −" }, { "code": null, "e": 2188, "s": 2162, "text": "h2 contenteditable=\"true\"" } ]
How to Insert Rows with NULL Values in SQL? - GeeksforGeeks
09 Nov, 2021 In SQL, due to lack of data, we sometimes need to insert rows with NULL values in the tables. Here, the keyword NULL(without quotes) is used to represent no data. There are some key points of Null value: NULL value is different from a zero value. A NULL value is used to represent a missing value, but that it usually has one of three different interpretations:The value unknown (value exists but is not known)Value not available (exists but is purposely withheld)Attribute not applicable (undefined for this tuple) The value unknown (value exists but is not known) Value not available (exists but is purposely withheld) Attribute not applicable (undefined for this tuple) It is often not possible to determine which of the meanings is intended. Hence, SQL does not distinguish between the different meanings of NULL. Syntax: INSERT INTO TABLE_NAME values (COLUMN_VALUE,NULL,........); Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks. Query: CREATE DATABASE GeeksForGeeks Output: Step 2: Use the GeeksForGeeks database. For this use the below command. Query: USE GeeksForGeeks Output: Step 3: Create a table WORKER inside the database GeeksForGeeks. This table has 4 columns namely STUDENT_ID, STUDENT_NAME, STUDENT_STANDARD, ENGLISH, MATHS, and PHYSICS containing student id, student name, standard, and marks of various subjects. Query: CREATE TABLE WORKER( W_NAME VARCHAR(20), CITY VARCHAR(20), AGE INT); Output: Step 4: Display the structure of the WORKER table. Query: EXEC SP_COLUMNS 'WORKER'; Output: Step 5: Insert 10 rows into the WORKER table. Query: INSERT INTO WORKER VALUES('SAM','ONTARIO',NULL); INSERT INTO WORKER VALUES('TIM',NULL,56); INSERT INTO WORKER VALUES(NULL,'CAIRO',43); INSERT INTO WORKER VALUES(NULL,'MUMBAI',NULL); INSERT INTO WORKER VALUES(NULL,NULL,NULL); Output: Step 6: Display all the rows of the WORKER table including the 0(zero) values. Query: SELECT * FROM WORKER; Output: Thus, in this way, we can insert NULL values into a table. Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL | Subquery How to Write a SQL Query For a Specific Date Range and Date Time? SQL Query to Convert VARCHAR to INT SQL Query to Delete Duplicate Rows SQL indexes SQL Query to Compare Two Dates
[ { "code": null, "e": 23877, "s": 23849, "text": "\n09 Nov, 2021" }, { "code": null, "e": 24082, "s": 23877, "text": "In SQL, due to lack of data, we sometimes need to insert rows with NULL values in the tables. Here, the keyword NULL(without quotes) is used to represent no data. There are some key points of Null value: " }, { "code": null, "e": 24125, "s": 24082, "text": "NULL value is different from a zero value." }, { "code": null, "e": 24394, "s": 24125, "text": "A NULL value is used to represent a missing value, but that it usually has one of three different interpretations:The value unknown (value exists but is not known)Value not available (exists but is purposely withheld)Attribute not applicable (undefined for this tuple)" }, { "code": null, "e": 24444, "s": 24394, "text": "The value unknown (value exists but is not known)" }, { "code": null, "e": 24499, "s": 24444, "text": "Value not available (exists but is purposely withheld)" }, { "code": null, "e": 24551, "s": 24499, "text": "Attribute not applicable (undefined for this tuple)" }, { "code": null, "e": 24696, "s": 24551, "text": "It is often not possible to determine which of the meanings is intended. Hence, SQL does not distinguish between the different meanings of NULL." }, { "code": null, "e": 24704, "s": 24696, "text": "Syntax:" }, { "code": null, "e": 24764, "s": 24704, "text": "INSERT INTO TABLE_NAME values\n(COLUMN_VALUE,NULL,........);" }, { "code": null, "e": 24864, "s": 24764, "text": "Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks." }, { "code": null, "e": 24871, "s": 24864, "text": "Query:" }, { "code": null, "e": 24901, "s": 24871, "text": "CREATE DATABASE GeeksForGeeks" }, { "code": null, "e": 24909, "s": 24901, "text": "Output:" }, { "code": null, "e": 24981, "s": 24909, "text": "Step 2: Use the GeeksForGeeks database. For this use the below command." }, { "code": null, "e": 24988, "s": 24981, "text": "Query:" }, { "code": null, "e": 25006, "s": 24988, "text": "USE GeeksForGeeks" }, { "code": null, "e": 25014, "s": 25006, "text": "Output:" }, { "code": null, "e": 25262, "s": 25014, "text": "Step 3: Create a table WORKER inside the database GeeksForGeeks. This table has 4 columns namely STUDENT_ID, STUDENT_NAME, STUDENT_STANDARD, ENGLISH, MATHS, and PHYSICS containing student id, student name, standard, and marks of various subjects." }, { "code": null, "e": 25269, "s": 25262, "text": "Query:" }, { "code": null, "e": 25338, "s": 25269, "text": "CREATE TABLE WORKER(\nW_NAME VARCHAR(20),\nCITY VARCHAR(20),\nAGE INT);" }, { "code": null, "e": 25346, "s": 25338, "text": "Output:" }, { "code": null, "e": 25397, "s": 25346, "text": "Step 4: Display the structure of the WORKER table." }, { "code": null, "e": 25404, "s": 25397, "text": "Query:" }, { "code": null, "e": 25430, "s": 25404, "text": "EXEC SP_COLUMNS 'WORKER';" }, { "code": null, "e": 25438, "s": 25430, "text": "Output:" }, { "code": null, "e": 25484, "s": 25438, "text": "Step 5: Insert 10 rows into the WORKER table." }, { "code": null, "e": 25491, "s": 25484, "text": "Query:" }, { "code": null, "e": 25716, "s": 25491, "text": "INSERT INTO WORKER VALUES('SAM','ONTARIO',NULL);\nINSERT INTO WORKER VALUES('TIM',NULL,56);\nINSERT INTO WORKER VALUES(NULL,'CAIRO',43);\nINSERT INTO WORKER VALUES(NULL,'MUMBAI',NULL);\nINSERT INTO WORKER VALUES(NULL,NULL,NULL);" }, { "code": null, "e": 25724, "s": 25716, "text": "Output:" }, { "code": null, "e": 25803, "s": 25724, "text": "Step 6: Display all the rows of the WORKER table including the 0(zero) values." }, { "code": null, "e": 25810, "s": 25803, "text": "Query:" }, { "code": null, "e": 25832, "s": 25810, "text": "SELECT * FROM WORKER;" }, { "code": null, "e": 25840, "s": 25832, "text": "Output:" }, { "code": null, "e": 25899, "s": 25840, "text": "Thus, in this way, we can insert NULL values into a table." }, { "code": null, "e": 25906, "s": 25899, "text": "Picked" }, { "code": null, "e": 25916, "s": 25906, "text": "SQL-Query" }, { "code": null, "e": 25927, "s": 25916, "text": "SQL-Server" }, { "code": null, "e": 25931, "s": 25927, "text": "SQL" }, { "code": null, "e": 25935, "s": 25931, "text": "SQL" }, { "code": null, "e": 26033, "s": 25935, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26042, "s": 26033, "text": "Comments" }, { "code": null, "e": 26055, "s": 26042, "text": "Old Comments" }, { "code": null, "e": 26121, "s": 26055, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26153, "s": 26121, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26231, "s": 26153, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 26248, "s": 26231, "text": "SQL using Python" }, { "code": null, "e": 26263, "s": 26248, "text": "SQL | Subquery" }, { "code": null, "e": 26329, "s": 26263, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 26365, "s": 26329, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 26400, "s": 26365, "text": "SQL Query to Delete Duplicate Rows" }, { "code": null, "e": 26412, "s": 26400, "text": "SQL indexes" } ]
How to precompile a COBOL-DB2 program?
Precompilation is the process through which the SQL statements used in the COBOL-DB2 program are replaced by appropriate COBOL calls. The precompilation is necessary before the actual compilation because the COBOL compiler cannot recognize the DB2 SQL statements and will throw errors due to them. DB2 utility DSNHPC is used for the precompilation. The inputs to the precompilation JCL step are DCLGEN (in SYSLIB) for the respective tables which are used in COBOL-DB2 program and COBOL-DB2 source program (in SYSIN). //STEP010 EXEC PGM=IKJEFT01 //SYSIN DD DSN=DIS.TEST.COBOL(PSNEW2),DISP=SHR //SYSLIB DD DSN=DIS.TEST.DCLGEN(PSDC2), DISP=SHR //DBRMLIB DD DSN=DIS.TEST.DBRMLIB(PSNEW2),DISP=SHR //SYSCIN DD DSN=DIS.TEST.COBL(PSCOB2), DISP=(NEW,CATLG,DEL), SPACE=(20, (90,90)) //SYSOUT DD SYSOUT=* Once we execute this JCL step we will receive below two main elements − DBRM is received in DBRMLIB that contains all the SQL statements which were present in the program. The DBRM is further used in the BIND step to obtain a PLAN or a PACKAGE. DBRM is received in DBRMLIB that contains all the SQL statements which were present in the program. The DBRM is further used in the BIND step to obtain a PLAN or a PACKAGE. The modified COBOL source program is received in SYSCIN that has all the SQL statements replaced by COBOL calls. This modified source is further compiled and link edited. The modified COBOL source program is received in SYSCIN that has all the SQL statements replaced by COBOL calls. This modified source is further compiled and link edited.
[ { "code": null, "e": 1360, "s": 1062, "text": "Precompilation is the process through which the SQL statements used in the COBOL-DB2 program are replaced by appropriate COBOL calls. The precompilation is necessary before the actual compilation because the COBOL compiler cannot recognize the DB2 SQL statements and will throw errors due to them." }, { "code": null, "e": 1579, "s": 1360, "text": "DB2 utility DSNHPC is used for the precompilation. The inputs to the precompilation JCL step are DCLGEN (in SYSLIB) for the respective tables which are used in COBOL-DB2 program and COBOL-DB2 source program (in SYSIN)." }, { "code": null, "e": 1856, "s": 1579, "text": "//STEP010 EXEC PGM=IKJEFT01\n//SYSIN DD DSN=DIS.TEST.COBOL(PSNEW2),DISP=SHR\n//SYSLIB DD DSN=DIS.TEST.DCLGEN(PSDC2), DISP=SHR\n//DBRMLIB DD DSN=DIS.TEST.DBRMLIB(PSNEW2),DISP=SHR\n//SYSCIN DD DSN=DIS.TEST.COBL(PSCOB2), DISP=(NEW,CATLG,DEL), SPACE=(20, (90,90))\n//SYSOUT DD SYSOUT=*" }, { "code": null, "e": 1928, "s": 1856, "text": "Once we execute this JCL step we will receive below two main elements −" }, { "code": null, "e": 2101, "s": 1928, "text": "DBRM is received in DBRMLIB that contains all the SQL statements which were present in the program. The DBRM is further used in the BIND step to obtain a PLAN or a PACKAGE." }, { "code": null, "e": 2274, "s": 2101, "text": "DBRM is received in DBRMLIB that contains all the SQL statements which were present in the program. The DBRM is further used in the BIND step to obtain a PLAN or a PACKAGE." }, { "code": null, "e": 2445, "s": 2274, "text": "The modified COBOL source program is received in SYSCIN that has all the SQL statements replaced by COBOL calls. This modified source is further compiled and link edited." }, { "code": null, "e": 2616, "s": 2445, "text": "The modified COBOL source program is received in SYSCIN that has all the SQL statements replaced by COBOL calls. This modified source is further compiled and link edited." } ]
Convert list of string to list of list in Python
In this article we will see how to create a list of lists which contain string data types. The inner list themselves or of string data type and they may contain numeric or strings as their elements. We use these two methods which will first separate out the lists and then convert each element of the list to a string. Live Demo list1 = [ '[0, 1, 2, 3]','["Mon", "Tue", "Wed", "Thu"]' ] print ("The given list is : \n" + str(list1)) print("\n") # using strip() + split() result = [k.strip("[]").split(", ") for k in list1] print ("Converting list of string to list of list : \n" + str(result)) Running the above code gives us the following result − The given list is : ['[0, 1, 2, 3]', '["Mon", "Tue", "Wed", "Thu"]'] Converting list of string to list of list : [['0', '1', '2', '3'], ['"Mon"', '"Tue"', '"Wed"', '"Thu"']] In this approach, we will use string slicing and then split the string to get the list of lists. Here the split function is applied along with a for loop. Live Demo list1 = [ '[0, 1, 2, 3]','["Mon", "Tue", "Wed", "Thu"]' ] print ("The given list is : \n" + str(list1)) print("\n") # using split() result = [i[1 : -1].split(', ') for i in list1] print ("Converting list of string to list of list : \n" + str(result)) Running the above code gives us the following result − The given list is : ['[0, 1, 2, 3]', '["Mon", "Tue", "Wed", "Thu"]'] Converting list of string to list of list : [['0', '1', '2', '3'], ['"Mon"', '"Tue"', '"Wed"', '"Thu"']]
[ { "code": null, "e": 1261, "s": 1062, "text": "In this article we will see how to create a list of lists which contain string data types. The inner list themselves or of string data type and they may contain numeric or strings as their elements." }, { "code": null, "e": 1381, "s": 1261, "text": "We use these two methods which will first separate out the lists and then convert each element of the list to a string." }, { "code": null, "e": 1392, "s": 1381, "text": " Live Demo" }, { "code": null, "e": 1657, "s": 1392, "text": "list1 = [ '[0, 1, 2, 3]','[\"Mon\", \"Tue\", \"Wed\", \"Thu\"]' ]\nprint (\"The given list is : \\n\" + str(list1))\nprint(\"\\n\")\n# using strip() + split()\nresult = [k.strip(\"[]\").split(\", \") for k in list1]\nprint (\"Converting list of string to list of list : \\n\" + str(result))" }, { "code": null, "e": 1712, "s": 1657, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1886, "s": 1712, "text": "The given list is :\n['[0, 1, 2, 3]', '[\"Mon\", \"Tue\", \"Wed\", \"Thu\"]']\nConverting list of string to list of list :\n[['0', '1', '2', '3'], ['\"Mon\"', '\"Tue\"', '\"Wed\"', '\"Thu\"']]" }, { "code": null, "e": 2041, "s": 1886, "text": "In this approach, we will use string slicing and then split the string to get the list of lists. Here the split function is applied along with a for loop." }, { "code": null, "e": 2052, "s": 2041, "text": " Live Demo" }, { "code": null, "e": 2303, "s": 2052, "text": "list1 = [ '[0, 1, 2, 3]','[\"Mon\", \"Tue\", \"Wed\", \"Thu\"]' ]\nprint (\"The given list is : \\n\" + str(list1))\nprint(\"\\n\")\n# using split()\nresult = [i[1 : -1].split(', ') for i in list1]\nprint (\"Converting list of string to list of list : \\n\" + str(result))" }, { "code": null, "e": 2358, "s": 2303, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2532, "s": 2358, "text": "The given list is :\n['[0, 1, 2, 3]', '[\"Mon\", \"Tue\", \"Wed\", \"Thu\"]']\nConverting list of string to list of list :\n[['0', '1', '2', '3'], ['\"Mon\"', '\"Tue\"', '\"Wed\"', '\"Thu\"']]" } ]
C# | Math Class - GeeksforGeeks
05 Mar, 2021 In C#, Math class comes under the System namespace. It is used to provide static methods and constants for logarithmic, trigonometric, and other useful mathematical functions. It is a static class and inherits the object class. public static class Math A field is a variable that is declared in a class or struct. These are considered as the members of their containing type. Fields may be static or instance fields. Math class contains the two fields i.e. E and PI. Math.E Field: This field represents the natural logarithmic base, specified by the constant, e.Math.PI Field: It represents the ratio of the circumference of a circle to its diameter, specified by the constant, PI(π). Math.E Field: This field represents the natural logarithmic base, specified by the constant, e. Math.PI Field: It represents the ratio of the circumference of a circle to its diameter, specified by the constant, PI(π). Example: // C# program to demonstrate the// value of Math Class Fieldsusing System; class GFG { // Main method static void Main() { // To find E constant values double e = Math.E; // Print result Console.WriteLine("Math.E = " + e); // To find PI constant values double pi_value = Math.PI; // Print result Console.WriteLine("Math.PI = " + pi_value); }} Output: Math.E = 2.71828182845905 Math.PI = 3.14159265358979 You can read more about fields from C# | Math Class Fields with Examples. Example: // C# program to illustrate the// Math class methodsusing System; public class GFG { // Main method static public void Main() { // using Floor() Method Console.WriteLine("Floor value of 123.123: " + Math.Floor(123.123)); // using Asin() Method Console.WriteLine("Asin value of 0.35: " + Math.Asin(0.35)); // using Sqrt() Method Console.WriteLine("Square Root of 81: " + Math.Sqrt(81)); // using Round() Method Console.WriteLine("Round value of 14.6534: " + Math.Round(14.6534)); }} Output: Floor value of 123.123: 123 Asin value of 0.35: 0.35757110364551 Square Root of 81: 9 Round value of 14.6534: 15 CSharp-Math C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples C# | Method Overriding C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Delegates Introduction to .NET Framework C# | Data Types Difference between Ref and Out keywords in C#
[ { "code": null, "e": 24452, "s": 24424, "text": "\n05 Mar, 2021" }, { "code": null, "e": 24680, "s": 24452, "text": "In C#, Math class comes under the System namespace. It is used to provide static methods and constants for logarithmic, trigonometric, and other useful mathematical functions. It is a static class and inherits the object class." }, { "code": null, "e": 24705, "s": 24680, "text": "public static class Math" }, { "code": null, "e": 24919, "s": 24705, "text": "A field is a variable that is declared in a class or struct. These are considered as the members of their containing type. Fields may be static or instance fields. Math class contains the two fields i.e. E and PI." }, { "code": null, "e": 25137, "s": 24919, "text": "Math.E Field: This field represents the natural logarithmic base, specified by the constant, e.Math.PI Field: It represents the ratio of the circumference of a circle to its diameter, specified by the constant, PI(π)." }, { "code": null, "e": 25233, "s": 25137, "text": "Math.E Field: This field represents the natural logarithmic base, specified by the constant, e." }, { "code": null, "e": 25356, "s": 25233, "text": "Math.PI Field: It represents the ratio of the circumference of a circle to its diameter, specified by the constant, PI(π)." }, { "code": null, "e": 25365, "s": 25356, "text": "Example:" }, { "code": "// C# program to demonstrate the// value of Math Class Fieldsusing System; class GFG { // Main method static void Main() { // To find E constant values double e = Math.E; // Print result Console.WriteLine(\"Math.E = \" + e); // To find PI constant values double pi_value = Math.PI; // Print result Console.WriteLine(\"Math.PI = \" + pi_value); }}", "e": 25787, "s": 25365, "text": null }, { "code": null, "e": 25795, "s": 25787, "text": "Output:" }, { "code": null, "e": 25849, "s": 25795, "text": "Math.E = 2.71828182845905\nMath.PI = 3.14159265358979\n" }, { "code": null, "e": 25923, "s": 25849, "text": "You can read more about fields from C# | Math Class Fields with Examples." }, { "code": null, "e": 25932, "s": 25923, "text": "Example:" }, { "code": "// C# program to illustrate the// Math class methodsusing System; public class GFG { // Main method static public void Main() { // using Floor() Method Console.WriteLine(\"Floor value of 123.123: \" + Math.Floor(123.123)); // using Asin() Method Console.WriteLine(\"Asin value of 0.35: \" + Math.Asin(0.35)); // using Sqrt() Method Console.WriteLine(\"Square Root of 81: \" + Math.Sqrt(81)); // using Round() Method Console.WriteLine(\"Round value of 14.6534: \" + Math.Round(14.6534)); }}", "e": 26606, "s": 25932, "text": null }, { "code": null, "e": 26614, "s": 26606, "text": "Output:" }, { "code": null, "e": 26728, "s": 26614, "text": "Floor value of 123.123: 123\nAsin value of 0.35: 0.35757110364551\nSquare Root of 81: 9\nRound value of 14.6534: 15\n" }, { "code": null, "e": 26740, "s": 26728, "text": "CSharp-Math" }, { "code": null, "e": 26743, "s": 26740, "text": "C#" }, { "code": null, "e": 26841, "s": 26743, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26850, "s": 26841, "text": "Comments" }, { "code": null, "e": 26863, "s": 26850, "text": "Old Comments" }, { "code": null, "e": 26891, "s": 26863, "text": "C# Dictionary with examples" }, { "code": null, "e": 26914, "s": 26891, "text": "C# | Method Overriding" }, { "code": null, "e": 26936, "s": 26914, "text": "C# | Class and Object" }, { "code": null, "e": 26954, "s": 26936, "text": "C# | Constructors" }, { "code": null, "e": 26994, "s": 26954, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27017, "s": 26994, "text": "Extension Method in C#" }, { "code": null, "e": 27032, "s": 27017, "text": "C# | Delegates" }, { "code": null, "e": 27063, "s": 27032, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27079, "s": 27063, "text": "C# | Data Types" } ]
Heart arrhythmia detection using Deep Learning | by Cristiano Aguiar | Towards Data Science
A common problem that Deep Learning is helping to solve lately involves time series classification. A classic approach to this kind of problem is generating features from the signals we have and training a machine learning model. The process of handcrafting features might take a great chunk of your project schedule. For that matter, employing a combination of a Convolutional Neural Network with a Long Short-Term Memory Recurrent Neural Network. This architecture has proven to be effective in order to reduce the amount of time spent on feature engineering. In this article, we're going to train a couple of models to detect irregular heart rhythms. The idea is to show step by step how to build a sequence model for time series classification. If you want a deep understanding of this problem, I highly recommend this article from the Stanford ML Group. For this experiment, we'll be using the MIT-BIH Arrhythmia Database that contains 48 half-hour excerpts of two-channel ambulatory ECG recordings, obtained from 47 subjects. The dataset is annotated by a cardiologist, all the labels and a full explanation of how the data were collected can be found here. For the purpose of this experiment, let's consider only two classes: normal beats and abnormal beats. Invalid beats were discarded from the labels. These are considered labels, the ones not on these lists are marked as normal. Each record is composed of a signal and its annotations. Both files are read with the library Python WFDB. The record can be read using: record = wfdb.rdrecord(filename)annotation = wfdb.rdann(filename, "atr") The annotation contains each beat annotation. Each sample in our model will be a beat label as target and a sequence surrounding this beat as input (3 seconds each side). Now let's define two functions that will help us to process the records. One to simply classify the record, given the list above, into a normal vs. abnormal beat. Another function will build a sample for our CNN/LSTM 1D model. To better understand the second function, we need to understand how the input for the CNN or LSTM model is formatted. You'll have to input a three dimensional array with the shape (batch_size, sequence_size, number_of_features). In this case, each sample would be (1, sequence_size, 1) since we have only one feature in our model. Later, you're going to see that for CNN with LSTM we also need to define another dimension (subsequences). Next, the following code will build a list of sequences (inputs) list of labels (target) and a map for each patient. The idea is to stratify for training and validation based on the rate of abnormal beats. Let's try different models to train our classifiers. The main purpose here is to show how to setup the keras layers, the architectures aren't very well designed. The first one is a CNN only model. This model looks like something below: To train the model let's call the fit method from keras: With this architecture, we can accomplish an accuracy of 0.82 in the validation set. It might not mean an amazing model, especially because of the loss over epochs that doesn't improve. Another common architecture used for sequential models is CNN with LSTM. The idea is to have a CNN layer working as a feature extraction layer and an LSTM to interpret the sequence of subsequences. This kind of architecture looks like this: Building a model using the Sequential API doesn't change much from what was done above. With this architecture, the accuracy on the validation set was 0.8. Next step, you can improve those models by reducing overfit through dropout layers or kernel regularizations. The code for this experiment is in the repo for this post.
[ { "code": null, "e": 402, "s": 172, "text": "A common problem that Deep Learning is helping to solve lately involves time series classification. A classic approach to this kind of problem is generating features from the signals we have and training a machine learning model." }, { "code": null, "e": 734, "s": 402, "text": "The process of handcrafting features might take a great chunk of your project schedule. For that matter, employing a combination of a Convolutional Neural Network with a Long Short-Term Memory Recurrent Neural Network. This architecture has proven to be effective in order to reduce the amount of time spent on feature engineering." }, { "code": null, "e": 1031, "s": 734, "text": "In this article, we're going to train a couple of models to detect irregular heart rhythms. The idea is to show step by step how to build a sequence model for time series classification. If you want a deep understanding of this problem, I highly recommend this article from the Stanford ML Group." }, { "code": null, "e": 1336, "s": 1031, "text": "For this experiment, we'll be using the MIT-BIH Arrhythmia Database that contains 48 half-hour excerpts of two-channel ambulatory ECG recordings, obtained from 47 subjects. The dataset is annotated by a cardiologist, all the labels and a full explanation of how the data were collected can be found here." }, { "code": null, "e": 1563, "s": 1336, "text": "For the purpose of this experiment, let's consider only two classes: normal beats and abnormal beats. Invalid beats were discarded from the labels. These are considered labels, the ones not on these lists are marked as normal." }, { "code": null, "e": 1700, "s": 1563, "text": "Each record is composed of a signal and its annotations. Both files are read with the library Python WFDB. The record can be read using:" }, { "code": null, "e": 1773, "s": 1700, "text": "record = wfdb.rdrecord(filename)annotation = wfdb.rdann(filename, \"atr\")" }, { "code": null, "e": 1944, "s": 1773, "text": "The annotation contains each beat annotation. Each sample in our model will be a beat label as target and a sequence surrounding this beat as input (3 seconds each side)." }, { "code": null, "e": 2171, "s": 1944, "text": "Now let's define two functions that will help us to process the records. One to simply classify the record, given the list above, into a normal vs. abnormal beat. Another function will build a sample for our CNN/LSTM 1D model." }, { "code": null, "e": 2609, "s": 2171, "text": "To better understand the second function, we need to understand how the input for the CNN or LSTM model is formatted. You'll have to input a three dimensional array with the shape (batch_size, sequence_size, number_of_features). In this case, each sample would be (1, sequence_size, 1) since we have only one feature in our model. Later, you're going to see that for CNN with LSTM we also need to define another dimension (subsequences)." }, { "code": null, "e": 2815, "s": 2609, "text": "Next, the following code will build a list of sequences (inputs) list of labels (target) and a map for each patient. The idea is to stratify for training and validation based on the rate of abnormal beats." }, { "code": null, "e": 3012, "s": 2815, "text": "Let's try different models to train our classifiers. The main purpose here is to show how to setup the keras layers, the architectures aren't very well designed. The first one is a CNN only model." }, { "code": null, "e": 3051, "s": 3012, "text": "This model looks like something below:" }, { "code": null, "e": 3108, "s": 3051, "text": "To train the model let's call the fit method from keras:" }, { "code": null, "e": 3294, "s": 3108, "text": "With this architecture, we can accomplish an accuracy of 0.82 in the validation set. It might not mean an amazing model, especially because of the loss over epochs that doesn't improve." }, { "code": null, "e": 3492, "s": 3294, "text": "Another common architecture used for sequential models is CNN with LSTM. The idea is to have a CNN layer working as a feature extraction layer and an LSTM to interpret the sequence of subsequences." }, { "code": null, "e": 3535, "s": 3492, "text": "This kind of architecture looks like this:" }, { "code": null, "e": 3623, "s": 3535, "text": "Building a model using the Sequential API doesn't change much from what was done above." }, { "code": null, "e": 3691, "s": 3623, "text": "With this architecture, the accuracy on the validation set was 0.8." }, { "code": null, "e": 3801, "s": 3691, "text": "Next step, you can improve those models by reducing overfit through dropout layers or kernel regularizations." } ]
How to insert spaces/tabs in text using HTML/CSS? - GeeksforGeeks
30 Jul, 2021 Spacing can be added using HTML and CSS by 3 approaches: Method 1: Using the special characters designated for different spaces The &nbsp; character entity used to denote a non-breaking space which is a fixed space. This may be perceived as twice the space of a normal space. It is used to create a space in a line that cannot be broken by word wrap. The &ensp; character entity used to denote an ‘en’ space which means half point size of the current font. This may be perceived as twice the space of a normal space. The &emsp; character entity used to denote an ’em’ space which means equal to the point size of the current font. This may be perceived as four times the space of a normal space. Syntax: Regular space: &nbsp; Two spaces gap: &ensp; Four spaces gap: &emsp; Example: <!DOCTYPE html><html><head> <title> How to insert spaces/tabs in text using HTML/CSS? </title></head><body> <h1 style="color: green">GeeksforGeeks</h1> <b>How to insert spaces/tabs in text using HTML/CSS?</b> <p>This is a &nbsp; regular space.</p> <p>This is a &ensp; two spaces gap.</p> <p>This is a &emsp; four spaces gap.</p></body></html> In the above code the regular space and two space and four space gaps code is not visible so here is how it looks Output: Method 2: Using the tab-size property to set spacing for tab characters The tab-size CSS property is set the number of spaces each tab character will display. Changing this value allows inserting the needed amount of space on one tab character. This method however only works with pre-formatted text (using <pre> tags). The tab character can be inserted by holding the Alt and pressing 0 and 9 together. Syntax: .tab { tab-size: 2; } Example: <!DOCTYPE html><html><head> <title> How to insert spaces/tabs in text using HTML/CSS? </title> <style> .tab1 { tab-size: 2; } .tab2 { tab-size: 4; } .tab4 { tab-size: 8; } </style></head><body> <h1 style="color: green">GeeksforGeeks</h1> <b>How to insert spaces/tabs in text using HTML/CSS?</b> <pre class="tab1">This is a tab with 2 spaces.</pre> <pre class="tab2">This is a tab with 4 spaces.</pre> <pre class="tab4">This is a tab with 8 spaces.</pre></body></html> Output: Method 3: Creating a new class for spacing using CSS A new class can be created which gives a certain amount of spacing by using the margin-left property. The amount of space could be given by the number of pixels specified in this property. The display property is also set to ‘inline-block’ so that no line-break is added after the element. This allows the space to sit next to text and other elements. Syntax: .tab { display: inline-block; margin-left: 40px; } Example: <!DOCTYPE html><html><head> <title> How to insert spaces/tabs in text using HTML/CSS? </title> <style> .tab { display: inline-block; margin-left: 40px; } </style></head><body> <h1 style="color: green">GeeksforGeeks</h1> <b>How to insert spaces/tabs in text using HTML/CSS?</b> <p>This is a<span class="tab"></span>tab space in the document.</p></body></html> Output: HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. gurukiranx CSS-Misc HTML-Misc Picked CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to apply style to parent if it has child with CSS? How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction)
[ { "code": null, "e": 26144, "s": 26116, "text": "\n30 Jul, 2021" }, { "code": null, "e": 26201, "s": 26144, "text": "Spacing can be added using HTML and CSS by 3 approaches:" }, { "code": null, "e": 26272, "s": 26201, "text": "Method 1: Using the special characters designated for different spaces" }, { "code": null, "e": 26495, "s": 26272, "text": "The &nbsp; character entity used to denote a non-breaking space which is a fixed space. This may be perceived as twice the space of a normal space. It is used to create a space in a line that cannot be broken by word wrap." }, { "code": null, "e": 26661, "s": 26495, "text": "The &ensp; character entity used to denote an ‘en’ space which means half point size of the current font. This may be perceived as twice the space of a normal space." }, { "code": null, "e": 26840, "s": 26661, "text": "The &emsp; character entity used to denote an ’em’ space which means equal to the point size of the current font. This may be perceived as four times the space of a normal space." }, { "code": null, "e": 26848, "s": 26840, "text": "Syntax:" }, { "code": null, "e": 26918, "s": 26848, "text": "Regular space: &nbsp;\nTwo spaces gap: &ensp;\nFour spaces gap: &emsp;\n" }, { "code": null, "e": 26927, "s": 26918, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> How to insert spaces/tabs in text using HTML/CSS? </title></head><body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>How to insert spaces/tabs in text using HTML/CSS?</b> <p>This is a &nbsp; regular space.</p> <p>This is a &ensp; two spaces gap.</p> <p>This is a &emsp; four spaces gap.</p></body></html>", "e": 27304, "s": 26927, "text": null }, { "code": null, "e": 27419, "s": 27304, "text": "In the above code the regular space and two space and four space gaps code is not visible so here is how it looks" }, { "code": null, "e": 27427, "s": 27419, "text": "Output:" }, { "code": null, "e": 27499, "s": 27427, "text": "Method 2: Using the tab-size property to set spacing for tab characters" }, { "code": null, "e": 27747, "s": 27499, "text": "The tab-size CSS property is set the number of spaces each tab character will display. Changing this value allows inserting the needed amount of space on one tab character. This method however only works with pre-formatted text (using <pre> tags)." }, { "code": null, "e": 27831, "s": 27747, "text": "The tab character can be inserted by holding the Alt and pressing 0 and 9 together." }, { "code": null, "e": 27839, "s": 27831, "text": "Syntax:" }, { "code": null, "e": 27874, "s": 27839, "text": ".tab {\n tab-size: 2;\n }\n" }, { "code": null, "e": 27883, "s": 27874, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> How to insert spaces/tabs in text using HTML/CSS? </title> <style> .tab1 { tab-size: 2; } .tab2 { tab-size: 4; } .tab4 { tab-size: 8; } </style></head><body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>How to insert spaces/tabs in text using HTML/CSS?</b> <pre class=\"tab1\">This is a tab with 2 spaces.</pre> <pre class=\"tab2\">This is a tab with 4 spaces.</pre> <pre class=\"tab4\">This is a tab with 8 spaces.</pre></body></html>", "e": 28488, "s": 27883, "text": null }, { "code": null, "e": 28496, "s": 28488, "text": "Output:" }, { "code": null, "e": 28549, "s": 28496, "text": "Method 3: Creating a new class for spacing using CSS" }, { "code": null, "e": 28738, "s": 28549, "text": "A new class can be created which gives a certain amount of spacing by using the margin-left property. The amount of space could be given by the number of pixels specified in this property." }, { "code": null, "e": 28901, "s": 28738, "text": "The display property is also set to ‘inline-block’ so that no line-break is added after the element. This allows the space to sit next to text and other elements." }, { "code": null, "e": 28909, "s": 28901, "text": "Syntax:" }, { "code": null, "e": 28969, "s": 28909, "text": ".tab {\n display: inline-block;\n margin-left: 40px;\n}\n" }, { "code": null, "e": 28978, "s": 28969, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> How to insert spaces/tabs in text using HTML/CSS? </title> <style> .tab { display: inline-block; margin-left: 40px; } </style></head><body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>How to insert spaces/tabs in text using HTML/CSS?</b> <p>This is a<span class=\"tab\"></span>tab space in the document.</p></body></html>", "e": 29407, "s": 28978, "text": null }, { "code": null, "e": 29415, "s": 29407, "text": "Output:" }, { "code": null, "e": 29609, "s": 29415, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 29795, "s": 29609, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 29932, "s": 29795, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 29943, "s": 29932, "text": "gurukiranx" }, { "code": null, "e": 29952, "s": 29943, "text": "CSS-Misc" }, { "code": null, "e": 29962, "s": 29952, "text": "HTML-Misc" }, { "code": null, "e": 29969, "s": 29962, "text": "Picked" }, { "code": null, "e": 29973, "s": 29969, "text": "CSS" }, { "code": null, "e": 29978, "s": 29973, "text": "HTML" }, { "code": null, "e": 29995, "s": 29978, "text": "Web Technologies" }, { "code": null, "e": 30022, "s": 29995, "text": "Web technologies Questions" }, { "code": null, "e": 30027, "s": 30022, "text": "HTML" }, { "code": null, "e": 30125, "s": 30027, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30173, "s": 30125, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 30210, "s": 30173, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 30265, "s": 30210, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 30329, "s": 30265, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 30368, "s": 30329, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 30416, "s": 30368, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 30476, "s": 30416, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30529, "s": 30476, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 30590, "s": 30529, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python calendar module | itermonthdates() method
12 May, 2021 Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. itermonthdates() method returns an iterator for the month (1–12) in the year. This iterator will return all days for the month and all days before the start of the month or after end of the month that are required to get a complete week. Syntax: itermonthdates(year, month) Parameter: year: year of the calendar month: month of the calendar Returns: an iterator for the month. Code #1: Python3 # Python program to demonstrate working# of itermonthdates() method # importing calendar modulefrom calendar import Calendar obj = calendar.Calendar() # iterating with itermonthdatesfor day in obj.itermonthdates(2018, 9): print(day) Output: 2018-08-27 2018-08-28 2018-08-29 2018-08-30 2018-08-31 . . . 2018-09-26 2018-09-27 2018-09-28 2018-09-29 2018-09-30 Code #2: Python3 # Python program to demonstrate working# of itermonthdates() method # importing calendar moduleimport calendar # use with firstweekday = 5obj = calendar.Calendar(firstweekday = 5) # iterating with itermonthdatesfor day in obj.itermonthdates(2018, 4): print(day) Output: 2018-08-30 2018-08-31 2018-09-01 2018-09-02 2018-09-03 . . 2018-09-30 2018-10-01 2018-10-02 2018-10-03 2018-09-01 2018-09-02 2018-09-03 . . 2018-09-28 . . 0018-03-31 0018-04-01 0018-04-02 . . 2018-04-28 2018-04-29 2018-04-30 2018-05-01 2018-05-02 anikakapoor Python Calander-module python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n12 May, 2021" }, { "code": null, "e": 539, "s": 28, "text": "Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. itermonthdates() method returns an iterator for the month (1–12) in the year. This iterator will return all days for the month and all days before the start of the month or after end of the month that are required to get a complete week. " }, { "code": null, "e": 681, "s": 539, "text": "Syntax: itermonthdates(year, month)\n\nParameter: \nyear: year of the calendar\nmonth: month of the calendar\n\nReturns: an iterator for the month." }, { "code": null, "e": 692, "s": 681, "text": "Code #1: " }, { "code": null, "e": 700, "s": 692, "text": "Python3" }, { "code": "# Python program to demonstrate working# of itermonthdates() method # importing calendar modulefrom calendar import Calendar obj = calendar.Calendar() # iterating with itermonthdatesfor day in obj.itermonthdates(2018, 9): print(day)", "e": 936, "s": 700, "text": null }, { "code": null, "e": 946, "s": 936, "text": "Output: " }, { "code": null, "e": 1062, "s": 946, "text": "2018-08-27\n2018-08-28\n2018-08-29\n2018-08-30\n2018-08-31\n.\n.\n.\n2018-09-26\n2018-09-27\n2018-09-28\n2018-09-29\n2018-09-30" }, { "code": null, "e": 1075, "s": 1062, "text": " Code #2: " }, { "code": null, "e": 1083, "s": 1075, "text": "Python3" }, { "code": "# Python program to demonstrate working# of itermonthdates() method # importing calendar moduleimport calendar # use with firstweekday = 5obj = calendar.Calendar(firstweekday = 5) # iterating with itermonthdatesfor day in obj.itermonthdates(2018, 4): print(day)", "e": 1348, "s": 1083, "text": null }, { "code": null, "e": 1358, "s": 1348, "text": "Output: " }, { "code": null, "e": 1605, "s": 1358, "text": "2018-08-30\n2018-08-31\n2018-09-01\n2018-09-02\n2018-09-03\n.\n.\n2018-09-30\n2018-10-01\n2018-10-02\n2018-10-03\n2018-09-01\n2018-09-02\n2018-09-03\n.\n.\n2018-09-28\n.\n.\n0018-03-31\n0018-04-01\n0018-04-02\n.\n.\n2018-04-28\n2018-04-29\n2018-04-30\n2018-05-01\n2018-05-02" }, { "code": null, "e": 1619, "s": 1607, "text": "anikakapoor" }, { "code": null, "e": 1642, "s": 1619, "text": "Python Calander-module" }, { "code": null, "e": 1657, "s": 1642, "text": "python-modules" }, { "code": null, "e": 1664, "s": 1657, "text": "Python" }, { "code": null, "e": 1762, "s": 1664, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1780, "s": 1762, "text": "Python Dictionary" }, { "code": null, "e": 1822, "s": 1780, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1844, "s": 1822, "text": "Enumerate() in Python" }, { "code": null, "e": 1879, "s": 1844, "text": "Read a file line by line in Python" }, { "code": null, "e": 1905, "s": 1879, "text": "Python String | replace()" }, { "code": null, "e": 1937, "s": 1905, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1966, "s": 1937, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1996, "s": 1966, "text": "Iterate over a list in Python" }, { "code": null, "e": 2023, "s": 1996, "text": "Python Classes and Objects" } ]
Program to check diagonal matrix and scalar matrix
13 Jul, 2022 A square matrix is said to be a diagonal matrix if the elements of the matrix except the main diagonal are zero. A square null matrix is also a diagonal matrix whose main diagonal elements are zero. Examples: Input: Mat[4][4] = {{4, 0, 0, 0}, {0, 5, 0, 0}, {0, 0, 2, 0}, {0, 0, 0, 1}} Output: Yes Input: Mat[4][4] = {{6, 10, 12, 0}, {0, 5, 0, 0}, {0, 0, 9, 0}, {0, 0, 0, 1}} Output: No Below is the implementation: CPP Java Python3 C# PHP Javascript // Program to check matrix is diagonal matrix or not. #include <bits/stdc++.h>#define N 4using namespace std; // Function to check matrix// is diagonal matrix or not.bool isDiagonalMatrix(int mat[N][N]){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) // condition to check other elements // except main diagonal are zero or not. if ((i != j) && (mat[i][j] != 0)) return false; return true;} // Driver functionint main(){ int mat[N][N] = { { 4, 0, 0, 0 }, { 0, 7, 0, 0 }, { 0, 0, 5, 0 }, { 0, 0, 0, 1 } }; if (isDiagonalMatrix(mat)) cout << "Yes" << endl; else cout << "No" << endl; return 0;} // Program to check matrix is// diagonal matrix or not. import java.io.*; class GFG { static int N = 4; // Function to check matrix // is diagonal matrix // or not. static boolean isDiagonalMatrix(int mat[][]) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) // condition to check // other elements // except main diagonal // are zero or not. if ((i != j) && (mat[i][j] != 0)) return false; return true; } // Driver function public static void main(String args[]) { int mat[][] = { { 4, 0, 0, 0 }, { 0, 7, 0, 0 }, { 0, 0, 5, 0 }, { 0, 0, 0, 1 } }; if (isDiagonalMatrix(mat)) System.out.println("Yes"); else System.out.println("No" ); }} // This code is contributed by// Nikita Tiwari. # Python3 Program to check if matrix# is diagonal matrix or not. N = 4 # Function to check matrix# is diagonal matrix# or not. def isDiagonalMatrix(mat) : for i in range(0, N): for j in range(0, N) : # condition to check # other elements # except main diagonal # are zero or not. if ((i != j) and (mat[i][j] != 0)) : return False return True # Driver functionmat = [[ 4, 0, 0, 0 ], [ 0, 7, 0, 0 ], [ 0, 0, 5, 0 ], [ 0, 0, 0, 1 ]] if (isDiagonalMatrix(mat)) : print("Yes")else : print("No") # This code is contributed by Nikita Tiwari. // Program to check matrix is// diagonal matrix or not.using System; class GFG { static int N = 4; // Function to check matrix // is diagonal matrix // or not. static bool isDiagonalMatrix(int [,]mat) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) // condition to check // other elements // except main diagonal // are zero or not. if ((i != j) && (mat[i,j] != 0)) return false; return true; } // Driver function public static void Main() { int [,]mat = { { 4, 0, 0, 0 }, { 0, 7, 0, 0 }, { 0, 0, 5, 0 }, { 0, 0, 0, 1 } }; if (isDiagonalMatrix(mat)) Console.WriteLine("Yes"); else Console.WriteLine("No" ); }} // This code is contributed by// vt_m. <?php// Program to check matrix is// diagonal matrix or not. $N= 4; // Function to check matrix is// diagonal matrix or not.function isDiagonalMatrix($mat){ global $N; for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) // condition to check // other elements // except main diagonal // are zero or not. if (($i != $j) && ($mat[$i][$j] != 0)) return false; return true;} // Driver Code $mat = array(array(4, 0, 0, 0), array(0, 7, 0, 0), array(0, 0, 5, 0), array(0, 0, 0, 1)); if (isDiagonalMatrix($mat)) echo "Yes" ,"\n"; else echo "No","\n"; // This code is contributed by jit_t?> <script> // JavaScript program to check matrix is// diagonal matrix or not. let N = 4; // Function to check matrix // is diagonal matrix // or not. function isDiagonalMatrix(mat) { for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) // condition to check // other elements // except main diagonal // are zero or not. if ((i != j) && (mat[i][j] != 0)) return false; return true; } // Driver code let mat = [[ 4, 0, 0, 0 ], [ 0, 7, 0, 0 ], [ 0, 0, 5, 0 ], [ 0, 0, 0, 1 ]]; if (isDiagonalMatrix(mat)) document.write("Yes"); else document.write("No" ); </script> Yes Time Complexity: O(N2), where N represents the number of rows and columns of the given matrix.Auxiliary Space: O(1), no extra space is required, so it is a constant. A square matrix is said to be a scalar matrix if all the main diagonal elements are equal and other elements except main diagonal are zero. The scalar matrix can also be written in form of n * I, where n is any real number and I is the identity matrix. Examples: Input: Mat[4][4] = {{4, 0, 0, 0}, {0, 4, 0, 0}, {0, 0, 4, 0}, {0, 0, 0, 4}} Output: Yes Input: Mat[4][4] = {{4, 0, 0, 0}, {0, 4, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 4}} Output: No Below is the implementation: CPP Java Python3 C# PHP Javascript // Program to check matrix is scalar matrix or not.#include <bits/stdc++.h>#define N 4using namespace std; // Function to check matrix is scalar matrix or not.bool isScalarMatrix(int mat[N][N]){ // Check all elements except main diagonal are // zero or not. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if ((i != j) && (mat[i][j] != 0)) return false; // Check all diagonal elements are same or not. for (int i = 0; i < N - 1; i++) if (mat[i][i] != mat[i + 1][i + 1]) return false; return true;} // Driver functionint main(){ int mat[N][N] = { { 2, 0, 0, 0 }, { 0, 2, 0, 0 }, { 0, 0, 2, 0 }, { 0, 0, 0, 2 } }; // Function call if (isScalarMatrix(mat)) cout << "Yes" << endl; else cout << "No" << endl; return 0;} // Program to check matrix// is scalar matrix or not.import java.io.*; class GFG { static int N = 4; // Function to check matrix // is scalar matrix or not. static boolean isScalarMatrix(int mat[][]) { // Check all elements // except main diagonal are // zero or not. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if ((i != j) && (mat[i][j] != 0)) return false; // Check all diagonal elements // are same or not. for (int i = 0; i < N - 1; i++) if (mat[i][i] != mat[i + 1][i + 1]) return false; return true; } // Driver function public static void main(String args[]) { int mat[ ][ ] = { { 2, 0, 0, 0 }, { 0, 2, 0, 0 }, { 0, 0, 2, 0 }, { 0, 0, 0, 2 } }; // Function call if (isScalarMatrix(mat)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed// by Nikita tiwari. # Program to check matrix# is scalar matrix or not. N = 4 # Function to check matrix is# scalar matrix or not.def isScalarMatrix(mat) : # Check all elements # except main diagonal are # zero or not. for i in range(0,N) : for j in range(0,N) : if ((i != j) and (mat[i][j] != 0)) : return False # Check all diagonal # elements are same or not. for i in range(0,N-1) : if (mat[i][i] != mat[i + 1][i + 1]) : return False return True # Driver functionmat = [[ 2, 0, 0, 0 ], [ 0, 2, 0, 0 ], [ 0, 0, 2, 0 ], [ 0, 0, 0, 2 ]] # Function callif (isScalarMatrix(mat)): print("Yes")else : print("No") # This code is contributed by# Nikita tiwari. // Program to check matrix// is scalar matrix or not.using System; class GFG { static int N = 4; // Function to check matrix // is scalar matrix or not. static bool isScalarMatrix(int [,]mat) { // Check all elements // except main diagonal are // zero or not. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if ((i != j) && (mat[i,j] != 0)) return false; // Check all diagonal elements // are same or not. for (int i = 0; i < N - 1; i++) if (mat[i, i] != mat[i + 1, i + 1]) return false; return true; } // Driver function public static void Main() { int [,]mat = { { 2, 0, 0, 0 }, { 0, 2, 0, 0 }, { 0, 0, 2, 0 }, { 0, 0, 0, 2 } }; // Function call if (isScalarMatrix(mat)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed// by vt_m. <?php// Program to check matrix// is scalar matrix or not. $N = 4; // Function to check matrix// is scalar matrix or not.function isScalarMatrix($mat){ global $N; // Check all elements except // main diagonal are zero or not. for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) if (($i != $j) && ($mat[$i][$j] != 0)) return false; // Check all diagonal elements // are same or not. for ($i = 0; $i < $N - 1; $i++) if ($mat[$i][$i] != $mat[$i + 1][$i + 1]) return false; return true;} // Driver Code$mat = array(array(2, 0, 0, 0), array(0, 2, 0, 0), array(0, 0, 2, 0), array(0, 0, 0, 2)); // Function callif (isScalarMatrix($mat)) echo "Yes";else echo "No" ; // This code is contributed by mits?> <script>// Javascript Program to check matrix// is scalar matrix or not. let N = 4; // Function to check matrix // is scalar matrix or not. function isScalarMatrix(mat) { // Check all elements // except main diagonal are // zero or not. for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) if ((i != j) && (mat[i][j] != 0)) return false; // Check all diagonal elements // are same or not. for (let i = 0; i < N - 1; i++) if (mat[i][i] != mat[i + 1][i + 1]) return false; return true; } // Driver Code let mat = [[ 2, 0, 0, 0 ], [ 0, 2, 0, 0 ], [ 0, 0, 2, 0 ], [ 0, 0, 0, 2 ]]; // Function call if (isScalarMatrix(mat)) document.write("Yes"); else document.write("No"); // This code is contributed by souravghosh0416.</script> Yes Time Complexity: O(N2), where N represents the number of rows and columns of the given matrix.Auxiliary Space: O(1), no extra space is required, so it is a constant. jit_t Mithun Kumar code_hunt souravghosh0416 tamanna17122007 harendrakumar123 Mathematical Matrix Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jul, 2022" }, { "code": null, "e": 252, "s": 52, "text": "A square matrix is said to be a diagonal matrix if the elements of the matrix except the main diagonal are zero. A square null matrix is also a diagonal matrix whose main diagonal elements are zero. " }, { "code": null, "e": 263, "s": 252, "text": "Examples: " }, { "code": null, "e": 520, "s": 263, "text": "Input: \nMat[4][4] = {{4, 0, 0, 0},\n {0, 5, 0, 0},\n {0, 0, 2, 0},\n {0, 0, 0, 1}}\nOutput: Yes\n\nInput:\nMat[4][4] = {{6, 10, 12, 0},\n {0, 5, 0, 0},\n {0, 0, 9, 0},\n {0, 0, 0, 1}}\nOutput: No" }, { "code": null, "e": 549, "s": 520, "text": "Below is the implementation:" }, { "code": null, "e": 553, "s": 549, "text": "CPP" }, { "code": null, "e": 558, "s": 553, "text": "Java" }, { "code": null, "e": 566, "s": 558, "text": "Python3" }, { "code": null, "e": 569, "s": 566, "text": "C#" }, { "code": null, "e": 573, "s": 569, "text": "PHP" }, { "code": null, "e": 584, "s": 573, "text": "Javascript" }, { "code": "// Program to check matrix is diagonal matrix or not. #include <bits/stdc++.h>#define N 4using namespace std; // Function to check matrix// is diagonal matrix or not.bool isDiagonalMatrix(int mat[N][N]){ for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) // condition to check other elements // except main diagonal are zero or not. if ((i != j) && (mat[i][j] != 0)) return false; return true;} // Driver functionint main(){ int mat[N][N] = { { 4, 0, 0, 0 }, { 0, 7, 0, 0 }, { 0, 0, 5, 0 }, { 0, 0, 0, 1 } }; if (isDiagonalMatrix(mat)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}", "e": 1338, "s": 584, "text": null }, { "code": "// Program to check matrix is// diagonal matrix or not. import java.io.*; class GFG { static int N = 4; // Function to check matrix // is diagonal matrix // or not. static boolean isDiagonalMatrix(int mat[][]) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) // condition to check // other elements // except main diagonal // are zero or not. if ((i != j) && (mat[i][j] != 0)) return false; return true; } // Driver function public static void main(String args[]) { int mat[][] = { { 4, 0, 0, 0 }, { 0, 7, 0, 0 }, { 0, 0, 5, 0 }, { 0, 0, 0, 1 } }; if (isDiagonalMatrix(mat)) System.out.println(\"Yes\"); else System.out.println(\"No\" ); }} // This code is contributed by// Nikita Tiwari.", "e": 2349, "s": 1338, "text": null }, { "code": "# Python3 Program to check if matrix# is diagonal matrix or not. N = 4 # Function to check matrix# is diagonal matrix# or not. def isDiagonalMatrix(mat) : for i in range(0, N): for j in range(0, N) : # condition to check # other elements # except main diagonal # are zero or not. if ((i != j) and (mat[i][j] != 0)) : return False return True # Driver functionmat = [[ 4, 0, 0, 0 ], [ 0, 7, 0, 0 ], [ 0, 0, 5, 0 ], [ 0, 0, 0, 1 ]] if (isDiagonalMatrix(mat)) : print(\"Yes\")else : print(\"No\") # This code is contributed by Nikita Tiwari.", "e": 3028, "s": 2349, "text": null }, { "code": "// Program to check matrix is// diagonal matrix or not.using System; class GFG { static int N = 4; // Function to check matrix // is diagonal matrix // or not. static bool isDiagonalMatrix(int [,]mat) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) // condition to check // other elements // except main diagonal // are zero or not. if ((i != j) && (mat[i,j] != 0)) return false; return true; } // Driver function public static void Main() { int [,]mat = { { 4, 0, 0, 0 }, { 0, 7, 0, 0 }, { 0, 0, 5, 0 }, { 0, 0, 0, 1 } }; if (isDiagonalMatrix(mat)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\" ); }} // This code is contributed by// vt_m.", "e": 3980, "s": 3028, "text": null }, { "code": "<?php// Program to check matrix is// diagonal matrix or not. $N= 4; // Function to check matrix is// diagonal matrix or not.function isDiagonalMatrix($mat){ global $N; for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) // condition to check // other elements // except main diagonal // are zero or not. if (($i != $j) && ($mat[$i][$j] != 0)) return false; return true;} // Driver Code $mat = array(array(4, 0, 0, 0), array(0, 7, 0, 0), array(0, 0, 5, 0), array(0, 0, 0, 1)); if (isDiagonalMatrix($mat)) echo \"Yes\" ,\"\\n\"; else echo \"No\",\"\\n\"; // This code is contributed by jit_t?>", "e": 4744, "s": 3980, "text": null }, { "code": "<script> // JavaScript program to check matrix is// diagonal matrix or not. let N = 4; // Function to check matrix // is diagonal matrix // or not. function isDiagonalMatrix(mat) { for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) // condition to check // other elements // except main diagonal // are zero or not. if ((i != j) && (mat[i][j] != 0)) return false; return true; } // Driver code let mat = [[ 4, 0, 0, 0 ], [ 0, 7, 0, 0 ], [ 0, 0, 5, 0 ], [ 0, 0, 0, 1 ]]; if (isDiagonalMatrix(mat)) document.write(\"Yes\"); else document.write(\"No\" ); </script>", "e": 5607, "s": 4744, "text": null }, { "code": null, "e": 5611, "s": 5607, "text": "Yes" }, { "code": null, "e": 5777, "s": 5611, "text": "Time Complexity: O(N2), where N represents the number of rows and columns of the given matrix.Auxiliary Space: O(1), no extra space is required, so it is a constant." }, { "code": null, "e": 6041, "s": 5777, "text": "A square matrix is said to be a scalar matrix if all the main diagonal elements are equal and other elements except main diagonal are zero. The scalar matrix can also be written in form of n * I, where n is any real number and I is the identity matrix. Examples: " }, { "code": null, "e": 6297, "s": 6041, "text": "Input:\nMat[4][4] = {{4, 0, 0, 0},\n {0, 4, 0, 0},\n {0, 0, 4, 0},\n {0, 0, 0, 4}} \nOutput: Yes\n\nInput:\nMat[4][4] = {{4, 0, 0, 0},\n {0, 4, 0, 0},\n {0, 0, 1, 0},\n {0, 0, 0, 4}} \nOutput: No" }, { "code": null, "e": 6326, "s": 6297, "text": "Below is the implementation:" }, { "code": null, "e": 6330, "s": 6326, "text": "CPP" }, { "code": null, "e": 6335, "s": 6330, "text": "Java" }, { "code": null, "e": 6343, "s": 6335, "text": "Python3" }, { "code": null, "e": 6346, "s": 6343, "text": "C#" }, { "code": null, "e": 6350, "s": 6346, "text": "PHP" }, { "code": null, "e": 6361, "s": 6350, "text": "Javascript" }, { "code": "// Program to check matrix is scalar matrix or not.#include <bits/stdc++.h>#define N 4using namespace std; // Function to check matrix is scalar matrix or not.bool isScalarMatrix(int mat[N][N]){ // Check all elements except main diagonal are // zero or not. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if ((i != j) && (mat[i][j] != 0)) return false; // Check all diagonal elements are same or not. for (int i = 0; i < N - 1; i++) if (mat[i][i] != mat[i + 1][i + 1]) return false; return true;} // Driver functionint main(){ int mat[N][N] = { { 2, 0, 0, 0 }, { 0, 2, 0, 0 }, { 0, 0, 2, 0 }, { 0, 0, 0, 2 } }; // Function call if (isScalarMatrix(mat)) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}", "e": 7246, "s": 6361, "text": null }, { "code": "// Program to check matrix// is scalar matrix or not.import java.io.*; class GFG { static int N = 4; // Function to check matrix // is scalar matrix or not. static boolean isScalarMatrix(int mat[][]) { // Check all elements // except main diagonal are // zero or not. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if ((i != j) && (mat[i][j] != 0)) return false; // Check all diagonal elements // are same or not. for (int i = 0; i < N - 1; i++) if (mat[i][i] != mat[i + 1][i + 1]) return false; return true; } // Driver function public static void main(String args[]) { int mat[ ][ ] = { { 2, 0, 0, 0 }, { 0, 2, 0, 0 }, { 0, 0, 2, 0 }, { 0, 0, 0, 2 } }; // Function call if (isScalarMatrix(mat)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed// by Nikita tiwari.", "e": 8377, "s": 7246, "text": null }, { "code": "# Program to check matrix# is scalar matrix or not. N = 4 # Function to check matrix is# scalar matrix or not.def isScalarMatrix(mat) : # Check all elements # except main diagonal are # zero or not. for i in range(0,N) : for j in range(0,N) : if ((i != j) and (mat[i][j] != 0)) : return False # Check all diagonal # elements are same or not. for i in range(0,N-1) : if (mat[i][i] != mat[i + 1][i + 1]) : return False return True # Driver functionmat = [[ 2, 0, 0, 0 ], [ 0, 2, 0, 0 ], [ 0, 0, 2, 0 ], [ 0, 0, 0, 2 ]] # Function callif (isScalarMatrix(mat)): print(\"Yes\")else : print(\"No\") # This code is contributed by# Nikita tiwari.", "e": 9154, "s": 8377, "text": null }, { "code": "// Program to check matrix// is scalar matrix or not.using System; class GFG { static int N = 4; // Function to check matrix // is scalar matrix or not. static bool isScalarMatrix(int [,]mat) { // Check all elements // except main diagonal are // zero or not. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if ((i != j) && (mat[i,j] != 0)) return false; // Check all diagonal elements // are same or not. for (int i = 0; i < N - 1; i++) if (mat[i, i] != mat[i + 1, i + 1]) return false; return true; } // Driver function public static void Main() { int [,]mat = { { 2, 0, 0, 0 }, { 0, 2, 0, 0 }, { 0, 0, 2, 0 }, { 0, 0, 0, 2 } }; // Function call if (isScalarMatrix(mat)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed// by vt_m.", "e": 10229, "s": 9154, "text": null }, { "code": "<?php// Program to check matrix// is scalar matrix or not. $N = 4; // Function to check matrix// is scalar matrix or not.function isScalarMatrix($mat){ global $N; // Check all elements except // main diagonal are zero or not. for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) if (($i != $j) && ($mat[$i][$j] != 0)) return false; // Check all diagonal elements // are same or not. for ($i = 0; $i < $N - 1; $i++) if ($mat[$i][$i] != $mat[$i + 1][$i + 1]) return false; return true;} // Driver Code$mat = array(array(2, 0, 0, 0), array(0, 2, 0, 0), array(0, 0, 2, 0), array(0, 0, 0, 2)); // Function callif (isScalarMatrix($mat)) echo \"Yes\";else echo \"No\" ; // This code is contributed by mits?>", "e": 11075, "s": 10229, "text": null }, { "code": "<script>// Javascript Program to check matrix// is scalar matrix or not. let N = 4; // Function to check matrix // is scalar matrix or not. function isScalarMatrix(mat) { // Check all elements // except main diagonal are // zero or not. for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) if ((i != j) && (mat[i][j] != 0)) return false; // Check all diagonal elements // are same or not. for (let i = 0; i < N - 1; i++) if (mat[i][i] != mat[i + 1][i + 1]) return false; return true; } // Driver Code let mat = [[ 2, 0, 0, 0 ], [ 0, 2, 0, 0 ], [ 0, 0, 2, 0 ], [ 0, 0, 0, 2 ]]; // Function call if (isScalarMatrix(mat)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by souravghosh0416.</script>", "e": 12139, "s": 11075, "text": null }, { "code": null, "e": 12143, "s": 12139, "text": "Yes" }, { "code": null, "e": 12309, "s": 12143, "text": "Time Complexity: O(N2), where N represents the number of rows and columns of the given matrix.Auxiliary Space: O(1), no extra space is required, so it is a constant." }, { "code": null, "e": 12315, "s": 12309, "text": "jit_t" }, { "code": null, "e": 12328, "s": 12315, "text": "Mithun Kumar" }, { "code": null, "e": 12338, "s": 12328, "text": "code_hunt" }, { "code": null, "e": 12354, "s": 12338, "text": "souravghosh0416" }, { "code": null, "e": 12370, "s": 12354, "text": "tamanna17122007" }, { "code": null, "e": 12387, "s": 12370, "text": "harendrakumar123" }, { "code": null, "e": 12400, "s": 12387, "text": "Mathematical" }, { "code": null, "e": 12407, "s": 12400, "text": "Matrix" }, { "code": null, "e": 12420, "s": 12407, "text": "Mathematical" }, { "code": null, "e": 12427, "s": 12420, "text": "Matrix" } ]
Boundary elements of a Matrix - GeeksforGeeks
28 Apr, 2022 Printing Boundary Elements of a Matrix. Given a matrix of size n x m. Print the boundary elements of the matrix. Boundary elements are those elements which are not surrounded by elements on all four directions, i.e. elements in first row, first column, last row and last column. Examples: Input : 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 Output : 1 2 3 4 5 8 1 4 5 6 7 8 Explanation:The boundary elements of the matrix is printed. Input: 1 2 3 5 6 7 1 2 3 Output: 1 2 3 5 7 1 2 3 Explanation:The boundary elements of the matrix is printed. Approach: The idea is simple. Traverse the matrix and check for every element if that element lies on the boundary or not, if yes then print the element else print space character. Algorithm : Traverse the array from start to end.Assign the outer loop to point the row and the inner row to traverse the elements of row.If the element lies in the boundary of matrix, then print the element, i.e. if the element lies in 1st row, 1st column, last row, last columnIf the element is not boundary element print a blank space. Traverse the array from start to end.Assign the outer loop to point the row and the inner row to traverse the elements of row.If the element lies in the boundary of matrix, then print the element, i.e. if the element lies in 1st row, 1st column, last row, last columnIf the element is not boundary element print a blank space. Traverse the array from start to end. Assign the outer loop to point the row and the inner row to traverse the elements of row. If the element lies in the boundary of matrix, then print the element, i.e. if the element lies in 1st row, 1st column, last row, last column If the element is not boundary element print a blank space. Implementation: C++ Java Python C# PHP Javascript // C++ program to print boundary element of// matrix.#include <bits/stdc++.h>using namespace std; const int MAX = 100; void printBoundary(int a[][MAX], int m, int n){ for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0 || i == n - 1 || j == n - 1) cout << a[i][j] << " "; else cout << " " << " "; } cout << "\n"; }} // Driver codeint main(){ int a[4][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printBoundary(a, 4, 4); return 0;} // JAVA Code for Boundary elements of a Matrixclass GFG { public static void printBoundary(int a[][], int m, int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0) System.out.print(a[i][j] + " "); else if (i == m - 1) System.out.print(a[i][j] + " "); else if (j == 0) System.out.print(a[i][j] + " "); else if (j == n - 1) System.out.print(a[i][j] + " "); else System.out.print(" "); } System.out.println(""); } } /* Driver program to test above function */ public static void main(String[] args) { int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printBoundary(a, 4, 4); }}// This code is contributed by Arnav Kr. Mandal. # Python program to print boundary element# of the matrix. MAX = 100 def printBoundary(a, m, n): for i in range(m): for j in range(n): if (i == 0): print a[i][j], elif (i == m-1): print a[i][j], elif (j == 0): print a[i][j], elif (j == n-1): print a[i][j], else: print " ", print # Driver codea = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]printBoundary(a, 4, 4) # This code is contributed by Sachin Bisht // C# Code for Boundary// elements of a Matrixusing System; class GFG { public static void printBoundary(int[, ] a, int m, int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0) Console.Write(a[i, j] + " "); else if (i == m - 1) Console.Write(a[i, j] + " "); else if (j == 0) Console.Write(a[i, j] + " "); else if (j == n - 1) Console.Write(a[i, j] + " "); else Console.Write(" "); } Console.WriteLine(" "); } } // Driver Code static public void Main() { int[, ] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printBoundary(a, 4, 4); }} // This code is contributed by ajit <?php// PHP program to print// boundary element of// matrix.$MAX = 100; function printBoundary($a, $m, $n){ global $MAX; for ($i = 0; $i < $m; $i++) { for ($j = 0; $j < $n; $j++) { if ($i == 0) echo $a[$i][$j], " "; else if ($i == $m - 1) echo $a[$i][$j], " "; else if ($j == 0) echo $a[$i][$j], " "; else if ($j == $n - 1) echo $a[$i][$j], " "; else echo " ", " "; } echo "\n"; }} // Driver code$a = array(array( 1, 2, 3, 4 ), array( 5, 6, 7, 8 ), array( 1, 2, 3, 4 ), array( 5, 6, 7, 8 ));printBoundary($a, 4, 4); // This code is contributed// by akt_mit?> <script> // JavaScript Code for Boundary// elements of a Matrixfunction printBoundary(a, m, n){ for (var i = 0; i < m; i++) { for (var j = 0; j < n; j++) { if (i == 0) document.write(a[i][j] + '\xa0'); else if (i == m - 1) document.write(a[i][j] + '\xa0'); else if (j == 0) document.write(a[i][j] + '\xa0'); else if (j == n - 1) document.write(a[i][j] + '\xa0'); else document.write("\xa0\xa0\xa0"); } document.write("\xa0<br>"); }}// Driver Codevar a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]];printBoundary(a, 4, 4); </script> Output: 1 2 3 4 5 8 1 4 5 6 7 8 Complexity Analysis: Time Complexity: O(n*n), where n is the size of array. This is achieved by single traversal of the matrix.Space Complexity: O(1). Since a constant space is needed. Time Complexity: O(n*n), where n is the size of array. This is achieved by single traversal of the matrix. Space Complexity: O(1). Since a constant space is needed. Finding sum of boundary elements Given an matrix of size n x m. Find the sum of boundary elements of the matrix. Boundary elements are those elements which is not surrounded by elements on all four directions, i.e. elements in first row, first column, last row and last column. Examples: Input : 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 Output : 54 Explanation:The boundary elements of the matrix 1 2 3 4 5 8 1 4 5 6 7 8 Sum = 1+2+3+4+5+8+1+4+5+6+7+8 =54 Input : 1 2 3 5 6 7 1 2 3 Output : 24 Explanation:The boundary elements of the matrix 1 2 3 5 7 1 2 3 Sum = 1+2+3+5+7+1+2+3 = 24 Approach: The idea is simple. Traverse the matrix and check for every element if that element lies on the boundary or not, if yes then add them to get the sum of all the boundary elements. Algorithm : Create a variable to store the sum and Traverse the array from start to end.Assign the outer loop to point the row and the inner row to traverse the elements of row.If the element lies in the boundary of matrix then add the element to the sum, i.e. if the element lies in 1st row, 1st column, last row, last columnprint the sum. Create a variable to store the sum and Traverse the array from start to end.Assign the outer loop to point the row and the inner row to traverse the elements of row.If the element lies in the boundary of matrix then add the element to the sum, i.e. if the element lies in 1st row, 1st column, last row, last columnprint the sum. Create a variable to store the sum and Traverse the array from start to end. Assign the outer loop to point the row and the inner row to traverse the elements of row. If the element lies in the boundary of matrix then add the element to the sum, i.e. if the element lies in 1st row, 1st column, last row, last column print the sum. Implementation: C++ Java Python C# PHP Javascript // C++ program to find sum of boundary elements// of matrix.#include <bits/stdc++.h>using namespace std; const int MAX = 100; int getBoundarySum(int a[][MAX], int m, int n){ long long int sum = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0) sum += a[i][j]; else if (i == m - 1) sum += a[i][j]; else if (j == 0) sum += a[i][j]; else if (j == n - 1) sum += a[i][j]; } } return sum;} // Driver codeint main(){ int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; long long int sum = getBoundarySum(a, 4, 4); cout << "Sum of boundary elements is " << sum; return 0;} // JAVA Code for Finding sum of boundary elementsclass GFG { public static long getBoundarySum(int a[][], int m, int n) { long sum = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0) sum += a[i][j]; else if (i == m - 1) sum += a[i][j]; else if (j == 0) sum += a[i][j]; else if (j == n - 1) sum += a[i][j]; } } return sum; } /* Driver program to test above function */ public static void main(String[] args) { int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; long sum = getBoundarySum(a, 4, 4); System.out.println("Sum of boundary elements" + " is " + sum); }}// This code is contributed by Arnav Kr. Mandal. # Python program to print boundary element# of the matrix. MAX = 100 def printBoundary(a, m, n): sum = 0 for i in range(m): for j in range(n): if (i == 0): sum += a[i][j] elif (i == m-1): sum += a[i][j] elif (j == 0): sum += a[i][j] elif (j == n-1): sum += a[i][j] return sum # Driver codea = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]sum = printBoundary(a, 4, 4)print "Sum of boundary elements is", sum # This code is contributed by Sachin Bisht // C# Code for Finding sum// of boundary elementsusing System; class GFG { public static long getBoundarySum(int[, ] a, int m, int n) { long sum = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0) sum += a[i, j]; else if (i == m - 1) sum += a[i, j]; else if (j == 0) sum += a[i, j]; else if (j == n - 1) sum += a[i, j]; } } return sum; } // Driver Code static public void Main() { int[, ] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; long sum = getBoundarySum(a, 4, 4); Console.WriteLine("Sum of boundary" + " elements is " + sum); }} // This code is contributed by ajit <?php// PHP program to find// sum of boundary// elements of matrix. function getBoundarySum($a, $m, $n){ $sum = 0; for ($i = 0; $i < $m; $i++) { for ( $j = 0; $j < $n; $j++) { if ($i == 0) $sum += $a[$i][$j]; else if ($i == $m - 1) $sum += $a[$i][$j]; else if ($j == 0) $sum += $a[$i][$j]; else if ($j == $n - 1) $sum += $a[$i][$j]; } } return $sum;} // Driver code$a = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(1, 2, 3, 4), array(5, 6, 7, 8)); $sum = getBoundarySum($a, 4, 4);echo "Sum of boundary elements is ", $sum; // This code is contributed by ajit?> <script> // Javascript code for finding sum// of boundary elementsfunction getBoundarySum(a, m, n){ let sum = 0; for(let i = 0; i < m; i++) { for(let j = 0; j < n; j++) { if (i == 0) sum += a[i][j]; else if (i == m - 1) sum += a[i][j]; else if (j == 0) sum += a[i][j]; else if (j == n - 1) sum += a[i][j]; } } return sum;} // Driver codelet a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ];let sum = getBoundarySum(a, 4, 4); document.write("Sum of boundary elements" + " is " + sum); // This code is contributed by rameshtravel07 </script> Output: Sum of boundary elements is 54 Complexity Analysis: Time Complexity: O(n*n), where n is the size of the array. This is achieved by single traversal of the matrix.Space Complexity: O(1). Since a constant space is needed. Time Complexity: O(n*n), where n is the size of the array. This is achieved by single traversal of the matrix. Space Complexity: O(1). Since a constant space is needed. This article is contributed by Sarthak Kohli. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t andrew1234 Akanksha_Rai rameshtravel07 noob2000 surinderdawra388 Matrix School Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Efficiently compute sums of diagonals of a matrix Program to multiply two matrices Count all possible paths from top left to bottom right of a mXn matrix Printing all solutions in N-Queen Problem Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 25015, "s": 24987, "text": "\n28 Apr, 2022" }, { "code": null, "e": 25055, "s": 25015, "text": "Printing Boundary Elements of a Matrix." }, { "code": null, "e": 25295, "s": 25055, "text": "Given a matrix of size n x m. Print the boundary elements of the matrix. Boundary elements are those elements which are not surrounded by elements on all four directions, i.e. elements in first row, first column, last row and last column. " }, { "code": null, "e": 25306, "s": 25295, "text": "Examples: " }, { "code": null, "e": 25693, "s": 25306, "text": "Input :\n 1 2 3 4 \n 5 6 7 8\n 1 2 3 4\n 5 6 7 8\nOutput : \n 1 2 3 4 \n 5 8 \n 1 4 \n 5 6 7 8\nExplanation:The boundary elements of the\nmatrix is printed.\n\nInput:\n 1 2 3 \n 5 6 7 \n 1 2 3 \nOutput: \n 1 2 3 \n 5 7 \n 1 2 3 \nExplanation:The boundary elements of the \nmatrix is printed." }, { "code": null, "e": 25875, "s": 25693, "text": "Approach: The idea is simple. Traverse the matrix and check for every element if that element lies on the boundary or not, if yes then print the element else print space character. " }, { "code": null, "e": 26214, "s": 25875, "text": "Algorithm : Traverse the array from start to end.Assign the outer loop to point the row and the inner row to traverse the elements of row.If the element lies in the boundary of matrix, then print the element, i.e. if the element lies in 1st row, 1st column, last row, last columnIf the element is not boundary element print a blank space." }, { "code": null, "e": 26541, "s": 26214, "text": "Traverse the array from start to end.Assign the outer loop to point the row and the inner row to traverse the elements of row.If the element lies in the boundary of matrix, then print the element, i.e. if the element lies in 1st row, 1st column, last row, last columnIf the element is not boundary element print a blank space." }, { "code": null, "e": 26579, "s": 26541, "text": "Traverse the array from start to end." }, { "code": null, "e": 26669, "s": 26579, "text": "Assign the outer loop to point the row and the inner row to traverse the elements of row." }, { "code": null, "e": 26811, "s": 26669, "text": "If the element lies in the boundary of matrix, then print the element, i.e. if the element lies in 1st row, 1st column, last row, last column" }, { "code": null, "e": 26871, "s": 26811, "text": "If the element is not boundary element print a blank space." }, { "code": null, "e": 26887, "s": 26871, "text": "Implementation:" }, { "code": null, "e": 26891, "s": 26887, "text": "C++" }, { "code": null, "e": 26896, "s": 26891, "text": "Java" }, { "code": null, "e": 26903, "s": 26896, "text": "Python" }, { "code": null, "e": 26906, "s": 26903, "text": "C#" }, { "code": null, "e": 26910, "s": 26906, "text": "PHP" }, { "code": null, "e": 26921, "s": 26910, "text": "Javascript" }, { "code": "// C++ program to print boundary element of// matrix.#include <bits/stdc++.h>using namespace std; const int MAX = 100; void printBoundary(int a[][MAX], int m, int n){ for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0 || i == n - 1 || j == n - 1) cout << a[i][j] << \" \"; else cout << \" \" << \" \"; } cout << \"\\n\"; }} // Driver codeint main(){ int a[4][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printBoundary(a, 4, 4); return 0;}", "e": 27519, "s": 26921, "text": null }, { "code": "// JAVA Code for Boundary elements of a Matrixclass GFG { public static void printBoundary(int a[][], int m, int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0) System.out.print(a[i][j] + \" \"); else if (i == m - 1) System.out.print(a[i][j] + \" \"); else if (j == 0) System.out.print(a[i][j] + \" \"); else if (j == n - 1) System.out.print(a[i][j] + \" \"); else System.out.print(\" \"); } System.out.println(\"\"); } } /* Driver program to test above function */ public static void main(String[] args) { int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printBoundary(a, 4, 4); }}// This code is contributed by Arnav Kr. Mandal.", "e": 28490, "s": 27519, "text": null }, { "code": "# Python program to print boundary element# of the matrix. MAX = 100 def printBoundary(a, m, n): for i in range(m): for j in range(n): if (i == 0): print a[i][j], elif (i == m-1): print a[i][j], elif (j == 0): print a[i][j], elif (j == n-1): print a[i][j], else: print \" \", print # Driver codea = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]printBoundary(a, 4, 4) # This code is contributed by Sachin Bisht", "e": 29078, "s": 28490, "text": null }, { "code": "// C# Code for Boundary// elements of a Matrixusing System; class GFG { public static void printBoundary(int[, ] a, int m, int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0) Console.Write(a[i, j] + \" \"); else if (i == m - 1) Console.Write(a[i, j] + \" \"); else if (j == 0) Console.Write(a[i, j] + \" \"); else if (j == n - 1) Console.Write(a[i, j] + \" \"); else Console.Write(\" \"); } Console.WriteLine(\" \"); } } // Driver Code static public void Main() { int[, ] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printBoundary(a, 4, 4); }} // This code is contributed by ajit", "e": 30093, "s": 29078, "text": null }, { "code": "<?php// PHP program to print// boundary element of// matrix.$MAX = 100; function printBoundary($a, $m, $n){ global $MAX; for ($i = 0; $i < $m; $i++) { for ($j = 0; $j < $n; $j++) { if ($i == 0) echo $a[$i][$j], \" \"; else if ($i == $m - 1) echo $a[$i][$j], \" \"; else if ($j == 0) echo $a[$i][$j], \" \"; else if ($j == $n - 1) echo $a[$i][$j], \" \"; else echo \" \", \" \"; } echo \"\\n\"; }} // Driver code$a = array(array( 1, 2, 3, 4 ), array( 5, 6, 7, 8 ), array( 1, 2, 3, 4 ), array( 5, 6, 7, 8 ));printBoundary($a, 4, 4); // This code is contributed// by akt_mit?>", "e": 30856, "s": 30093, "text": null }, { "code": "<script> // JavaScript Code for Boundary// elements of a Matrixfunction printBoundary(a, m, n){ for (var i = 0; i < m; i++) { for (var j = 0; j < n; j++) { if (i == 0) document.write(a[i][j] + '\\xa0'); else if (i == m - 1) document.write(a[i][j] + '\\xa0'); else if (j == 0) document.write(a[i][j] + '\\xa0'); else if (j == n - 1) document.write(a[i][j] + '\\xa0'); else document.write(\"\\xa0\\xa0\\xa0\"); } document.write(\"\\xa0<br>\"); }}// Driver Codevar a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ]];printBoundary(a, 4, 4); </script>", "e": 31609, "s": 30856, "text": null }, { "code": null, "e": 31618, "s": 31609, "text": "Output: " }, { "code": null, "e": 31653, "s": 31618, "text": "1 2 3 4 \n5 8 \n1 4 \n5 6 7 8" }, { "code": null, "e": 31838, "s": 31653, "text": "Complexity Analysis: Time Complexity: O(n*n), where n is the size of array. This is achieved by single traversal of the matrix.Space Complexity: O(1). Since a constant space is needed." }, { "code": null, "e": 31945, "s": 31838, "text": "Time Complexity: O(n*n), where n is the size of array. This is achieved by single traversal of the matrix." }, { "code": null, "e": 32003, "s": 31945, "text": "Space Complexity: O(1). Since a constant space is needed." }, { "code": null, "e": 32036, "s": 32003, "text": "Finding sum of boundary elements" }, { "code": null, "e": 32282, "s": 32036, "text": "Given an matrix of size n x m. Find the sum of boundary elements of the matrix. Boundary elements are those elements which is not surrounded by elements on all four directions, i.e. elements in first row, first column, last row and last column. " }, { "code": null, "e": 32294, "s": 32282, "text": "Examples: " }, { "code": null, "e": 32725, "s": 32294, "text": "Input :\n 1 2 3 4 \n 5 6 7 8\n 1 2 3 4\n 5 6 7 8\nOutput : 54\nExplanation:The boundary elements of the matrix \n 1 2 3 4 \n 5 8 \n 1 4 \n 5 6 7 8\nSum = 1+2+3+4+5+8+1+4+5+6+7+8 =54\n\nInput :\n 1 2 3 \n 5 6 7 \n 1 2 3 \nOutput : 24\nExplanation:The boundary elements of the matrix\n 1 2 3 \n 5 7 \n 1 2 3 \nSum = 1+2+3+5+7+1+2+3 = 24" }, { "code": null, "e": 32915, "s": 32725, "text": "Approach: The idea is simple. Traverse the matrix and check for every element if that element lies on the boundary or not, if yes then add them to get the sum of all the boundary elements. " }, { "code": null, "e": 33256, "s": 32915, "text": "Algorithm : Create a variable to store the sum and Traverse the array from start to end.Assign the outer loop to point the row and the inner row to traverse the elements of row.If the element lies in the boundary of matrix then add the element to the sum, i.e. if the element lies in 1st row, 1st column, last row, last columnprint the sum." }, { "code": null, "e": 33585, "s": 33256, "text": "Create a variable to store the sum and Traverse the array from start to end.Assign the outer loop to point the row and the inner row to traverse the elements of row.If the element lies in the boundary of matrix then add the element to the sum, i.e. if the element lies in 1st row, 1st column, last row, last columnprint the sum." }, { "code": null, "e": 33662, "s": 33585, "text": "Create a variable to store the sum and Traverse the array from start to end." }, { "code": null, "e": 33752, "s": 33662, "text": "Assign the outer loop to point the row and the inner row to traverse the elements of row." }, { "code": null, "e": 33902, "s": 33752, "text": "If the element lies in the boundary of matrix then add the element to the sum, i.e. if the element lies in 1st row, 1st column, last row, last column" }, { "code": null, "e": 33917, "s": 33902, "text": "print the sum." }, { "code": null, "e": 33933, "s": 33917, "text": "Implementation:" }, { "code": null, "e": 33937, "s": 33933, "text": "C++" }, { "code": null, "e": 33942, "s": 33937, "text": "Java" }, { "code": null, "e": 33949, "s": 33942, "text": "Python" }, { "code": null, "e": 33952, "s": 33949, "text": "C#" }, { "code": null, "e": 33956, "s": 33952, "text": "PHP" }, { "code": null, "e": 33967, "s": 33956, "text": "Javascript" }, { "code": "// C++ program to find sum of boundary elements// of matrix.#include <bits/stdc++.h>using namespace std; const int MAX = 100; int getBoundarySum(int a[][MAX], int m, int n){ long long int sum = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0) sum += a[i][j]; else if (i == m - 1) sum += a[i][j]; else if (j == 0) sum += a[i][j]; else if (j == n - 1) sum += a[i][j]; } } return sum;} // Driver codeint main(){ int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; long long int sum = getBoundarySum(a, 4, 4); cout << \"Sum of boundary elements is \" << sum; return 0;}", "e": 34730, "s": 33967, "text": null }, { "code": "// JAVA Code for Finding sum of boundary elementsclass GFG { public static long getBoundarySum(int a[][], int m, int n) { long sum = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0) sum += a[i][j]; else if (i == m - 1) sum += a[i][j]; else if (j == 0) sum += a[i][j]; else if (j == n - 1) sum += a[i][j]; } } return sum; } /* Driver program to test above function */ public static void main(String[] args) { int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; long sum = getBoundarySum(a, 4, 4); System.out.println(\"Sum of boundary elements\" + \" is \" + sum); }}// This code is contributed by Arnav Kr. Mandal.", "e": 35687, "s": 34730, "text": null }, { "code": "# Python program to print boundary element# of the matrix. MAX = 100 def printBoundary(a, m, n): sum = 0 for i in range(m): for j in range(n): if (i == 0): sum += a[i][j] elif (i == m-1): sum += a[i][j] elif (j == 0): sum += a[i][j] elif (j == n-1): sum += a[i][j] return sum # Driver codea = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ]sum = printBoundary(a, 4, 4)print \"Sum of boundary elements is\", sum # This code is contributed by Sachin Bisht", "e": 36286, "s": 35687, "text": null }, { "code": "// C# Code for Finding sum// of boundary elementsusing System; class GFG { public static long getBoundarySum(int[, ] a, int m, int n) { long sum = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0) sum += a[i, j]; else if (i == m - 1) sum += a[i, j]; else if (j == 0) sum += a[i, j]; else if (j == n - 1) sum += a[i, j]; } } return sum; } // Driver Code static public void Main() { int[, ] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; long sum = getBoundarySum(a, 4, 4); Console.WriteLine(\"Sum of boundary\" + \" elements is \" + sum); }} // This code is contributed by ajit", "e": 37263, "s": 36286, "text": null }, { "code": "<?php// PHP program to find// sum of boundary// elements of matrix. function getBoundarySum($a, $m, $n){ $sum = 0; for ($i = 0; $i < $m; $i++) { for ( $j = 0; $j < $n; $j++) { if ($i == 0) $sum += $a[$i][$j]; else if ($i == $m - 1) $sum += $a[$i][$j]; else if ($j == 0) $sum += $a[$i][$j]; else if ($j == $n - 1) $sum += $a[$i][$j]; } } return $sum;} // Driver code$a = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(1, 2, 3, 4), array(5, 6, 7, 8)); $sum = getBoundarySum($a, 4, 4);echo \"Sum of boundary elements is \", $sum; // This code is contributed by ajit?>", "e": 38033, "s": 37263, "text": null }, { "code": "<script> // Javascript code for finding sum// of boundary elementsfunction getBoundarySum(a, m, n){ let sum = 0; for(let i = 0; i < m; i++) { for(let j = 0; j < n; j++) { if (i == 0) sum += a[i][j]; else if (i == m - 1) sum += a[i][j]; else if (j == 0) sum += a[i][j]; else if (j == n - 1) sum += a[i][j]; } } return sum;} // Driver codelet a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ] ];let sum = getBoundarySum(a, 4, 4); document.write(\"Sum of boundary elements\" + \" is \" + sum); // This code is contributed by rameshtravel07 </script>", "e": 38792, "s": 38033, "text": null }, { "code": null, "e": 38801, "s": 38792, "text": "Output: " }, { "code": null, "e": 38832, "s": 38801, "text": "Sum of boundary elements is 54" }, { "code": null, "e": 39021, "s": 38832, "text": "Complexity Analysis: Time Complexity: O(n*n), where n is the size of the array. This is achieved by single traversal of the matrix.Space Complexity: O(1). Since a constant space is needed." }, { "code": null, "e": 39132, "s": 39021, "text": "Time Complexity: O(n*n), where n is the size of the array. This is achieved by single traversal of the matrix." }, { "code": null, "e": 39190, "s": 39132, "text": "Space Complexity: O(1). Since a constant space is needed." }, { "code": null, "e": 39612, "s": 39190, "text": "This article is contributed by Sarthak Kohli. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39618, "s": 39612, "text": "jit_t" }, { "code": null, "e": 39629, "s": 39618, "text": "andrew1234" }, { "code": null, "e": 39642, "s": 39629, "text": "Akanksha_Rai" }, { "code": null, "e": 39657, "s": 39642, "text": "rameshtravel07" }, { "code": null, "e": 39666, "s": 39657, "text": "noob2000" }, { "code": null, "e": 39683, "s": 39666, "text": "surinderdawra388" }, { "code": null, "e": 39690, "s": 39683, "text": "Matrix" }, { "code": null, "e": 39709, "s": 39690, "text": "School Programming" }, { "code": null, "e": 39716, "s": 39709, "text": "Matrix" }, { "code": null, "e": 39814, "s": 39716, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39876, "s": 39814, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 39926, "s": 39876, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 39959, "s": 39926, "text": "Program to multiply two matrices" }, { "code": null, "e": 40030, "s": 39959, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 40072, "s": 40030, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 40090, "s": 40072, "text": "Python Dictionary" }, { "code": null, "e": 40106, "s": 40090, "text": "Arrays in C/C++" }, { "code": null, "e": 40125, "s": 40106, "text": "Inheritance in C++" }, { "code": null, "e": 40150, "s": 40125, "text": "Reverse a string in Java" } ]
How to create a custom callback in JavaScript? - GeeksforGeeks
07 Aug, 2019 A callback is a function that is invoked after a function has finished its execution. As JavaScript is an event-driven language, it does not wait for a function to finish its execution before moving on to the next one. Callbacks make it possible to make a function execute only after another function has finished executing. All functions in JavaScript are objects, hence like any other object, a JavaScript function can be passed another function as an argument. There are many inbuilt functions which use callbacks. A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. Syntax: function processThis(message, callback) { console.log("Running function first with message: " + message); if (typeof callback == "function") callback(); } processThis("Hello World", function callFunction() { console.log("This is a callback function.") }); Example: <!DOCTYPE html><html> <head> <title> How to create a custom callback in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to create a custom callback in JavaScript? </b> <p> See the console for output of the functions </p> <script type="text/javascript"> function processThis(message, callback) { console.log( "Running function first with message: " + message); if (typeof callback == "function") callback(); } processThis("Hello World", function callbackFunction() { console.log("This is a callback function.") }); </script></body> </html> Output: Non anonymous callback function:A callback function is not always required to be defined as an anonymous function. It may be defined elsewhere and this function can be used later as a callback. The parentheses are not used when passing the callback function. Example: <!DOCTYPE html><html> <head> <title> How to create a custom callback in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>How to create a custom callback in JavaScript? </b> <p>See the console for output of the functions</p> <script type="text/javascript"> function processThis(message, callback) { console.log("Running function first with message: " + message); if (typeof callback == "function") callback(); } function callbackFunction() { console.log( "Running callback function next"); } processThis("Hello World", callbackFunction); </script></body> </html> Output: Arguments in a callback function:The callback function can also have its own arguments and the values can be passed while invoking the callback function in the body of the calling function. Example: <!DOCTYPE html><html> <head> <title> How to create a custom callback in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>How to create a custom callback in JavaScript?</b> <p>See the console for output of the functions</p> <script type="text/javascript"> function processThis(message, callback) { console.log( "Running function first with message: " + message); if (typeof callback == "function") callback(9, "Hello!"); } function callbackFunction(num, str) { console.log("Running callback function next"); console.log("num value is: " + num); console.log("str value is: " + str); } processThis("Hello World", callbackFunction); </script></body> </html> Output: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25653, "s": 25625, "text": "\n07 Aug, 2019" }, { "code": null, "e": 25978, "s": 25653, "text": "A callback is a function that is invoked after a function has finished its execution. As JavaScript is an event-driven language, it does not wait for a function to finish its execution before moving on to the next one. Callbacks make it possible to make a function execute only after another function has finished executing." }, { "code": null, "e": 26171, "s": 25978, "text": "All functions in JavaScript are objects, hence like any other object, a JavaScript function can be passed another function as an argument. There are many inbuilt functions which use callbacks." }, { "code": null, "e": 26447, "s": 26171, "text": "A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function." }, { "code": null, "e": 26455, "s": 26447, "text": "Syntax:" }, { "code": "function processThis(message, callback) { console.log(\"Running function first with message: \" + message); if (typeof callback == \"function\") callback(); } processThis(\"Hello World\", function callFunction() { console.log(\"This is a callback function.\") });", "e": 26784, "s": 26455, "text": null }, { "code": null, "e": 26793, "s": 26784, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to create a custom callback in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to create a custom callback in JavaScript? </b> <p> See the console for output of the functions </p> <script type=\"text/javascript\"> function processThis(message, callback) { console.log( \"Running function first with message: \" + message); if (typeof callback == \"function\") callback(); } processThis(\"Hello World\", function callbackFunction() { console.log(\"This is a callback function.\") }); </script></body> </html>", "e": 27544, "s": 26793, "text": null }, { "code": null, "e": 27552, "s": 27544, "text": "Output:" }, { "code": null, "e": 27811, "s": 27552, "text": "Non anonymous callback function:A callback function is not always required to be defined as an anonymous function. It may be defined elsewhere and this function can be used later as a callback. The parentheses are not used when passing the callback function." }, { "code": null, "e": 27820, "s": 27811, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to create a custom callback in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>How to create a custom callback in JavaScript? </b> <p>See the console for output of the functions</p> <script type=\"text/javascript\"> function processThis(message, callback) { console.log(\"Running function first with message: \" + message); if (typeof callback == \"function\") callback(); } function callbackFunction() { console.log( \"Running callback function next\"); } processThis(\"Hello World\", callbackFunction); </script></body> </html>", "e": 28596, "s": 27820, "text": null }, { "code": null, "e": 28604, "s": 28596, "text": "Output:" }, { "code": null, "e": 28794, "s": 28604, "text": "Arguments in a callback function:The callback function can also have its own arguments and the values can be passed while invoking the callback function in the body of the calling function." }, { "code": null, "e": 28803, "s": 28794, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to create a custom callback in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>How to create a custom callback in JavaScript?</b> <p>See the console for output of the functions</p> <script type=\"text/javascript\"> function processThis(message, callback) { console.log( \"Running function first with message: \" + message); if (typeof callback == \"function\") callback(9, \"Hello!\"); } function callbackFunction(num, str) { console.log(\"Running callback function next\"); console.log(\"num value is: \" + num); console.log(\"str value is: \" + str); } processThis(\"Hello World\", callbackFunction); </script></body> </html>", "e": 29679, "s": 28803, "text": null }, { "code": null, "e": 29687, "s": 29679, "text": "Output:" }, { "code": null, "e": 29703, "s": 29687, "text": "JavaScript-Misc" }, { "code": null, "e": 29710, "s": 29703, "text": "Picked" }, { "code": null, "e": 29721, "s": 29710, "text": "JavaScript" }, { "code": null, "e": 29738, "s": 29721, "text": "Web Technologies" }, { "code": null, "e": 29765, "s": 29738, "text": "Web technologies Questions" }, { "code": null, "e": 29863, "s": 29765, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29903, "s": 29863, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29948, "s": 29903, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30009, "s": 29948, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30081, "s": 30009, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 30133, "s": 30081, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 30173, "s": 30133, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30206, "s": 30173, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30251, "s": 30206, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30294, "s": 30251, "text": "How to fetch data from an API in ReactJS ?" } ]
How to get values of an NumPy array at certain index positions? - GeeksforGeeks
25 Oct, 2020 Sometimes we need to remove values from the source Numpy array and add them at specific indices in the target array. In NumPy, we have this flexibility, we can remove values from one array and add them to another array. We can perform this operation using numpy.put() function and it can be applied to all forms of arrays like 1-D, 2-D, etc. Example 1: Python3 # Importing Numpy moduleimport numpy as np # Creating 1-D Numpy arraya1 = np.array([11, 10, 22, 30, 33])print("Array 1 :")print(a1) a2 = np.array([1, 15, 60])print("Array 2 :")print(a2) print("\nTake 1 and 15 from Array 2 and put them in\1st and 5th position of Array 1") a1.put([0, 4], a2) print("Resultant Array :")print(a1) Output: In the above example, we take two 1-D arrays and transfer values from one array to another at specific positions. Example 2: Python3 # Importing Numpy moduleimport numpy as np # Creating 2-D Numpy arraya1 = np.array([[11, 10, 22, 30], [14, 58, 88, 100]]) print("Array 1 :")print(a1) a2 = np.array([1, 15, 6, 40])print("Array 2 :")print(a2) print("\nTake 1, 15 and 6 from Array 2 and put them in 1st,\4th and 7th positions of Array 1") a1.put([0, 3, 6], a2) print("Resultant Array :")print(a1) Output: In the above example, we take two different arrays and transfer values from 1-D to 2-D array at specific positions. Example 3: Python3 # Importing Numpy moduleimport numpy as np # Creating 3-D Numpy arraya1 = np.array([[[11, 25, 7], [30, 45, 55], [20, 45, 7]], [[50, 65, 8], [70, 85, 10], [11, 22, 33]], [[19, 69, 36], [1, 5, 24], [4, 20, 9]]]) print("Array 1 :")print(a1) # Creating 2-D arraya2 = np.array([[1, 15, 10], [6, 40, 50], [11, 5, 10]]) print("\nArray 2 :")print(a2) print("\nTake 1, 15, 10, 6, 40 and 50 from Array 2 and put\them in 1st, 3rd, 5th, 9th, 11th and 15th positions of Array 1") a1.put([0, 2, 4, 8, 10, 14], a2) print("Resultant Array :")print(a1) Output: In the above example, we take two different arrays and transfer values from 2-D to 3-D array at specific positions. One question arises, what will happen if out-of-bounds indices occur. For this, we have 3 modes in numpy.put() function mode = {‘raise’, ‘wrap’, ‘clip’} ‘raise’ – raise an error (default) ‘wrap’ – wrap around ‘clip’ – clip to the range Example 4: Taking mode = ‘raise’ Python3 # Importing Numpy moduleimport numpy as np # Creating 2-D Numpy arraya1 = np.array([[11, 10, 22], [14, 58, 88]]) print("Array 1 :")print(a1) a2 = np.array([[1, 15, 6], [40, 50, 70]]) print("Array 2 :")print(a2) print("\nTake 1 and 15 from Array 2 and put them in 1st \and 5th positions of Array 1") print("by mistake we write the index which is out of bound,\now mode will play its role") a1.put([0, 15], a2, mode='raise') print("\nResultant Array :")print(a1) Output: In the above example mode=’raise’ generates an error when indices become out of bound. Example 5: Taking mode = ‘clip’ Python3 # Importing Numpy moduleimport numpy as np # Creating 2-D Numpy arraya1 = np.array([[11, 10, 22], [14, 58, 88]]) print("Array 1 :")print(a1) a2 = np.array([[1, 15, 6], [40, 50, 70]]) print("Array 2 :")print(a2) print("\nTake 1 and 15 from Array 2 and put them in 1st and\5th positions of Array 1") print("by mistake we write the index which is out of bound,\now mode will play its role") a1.put([0, 15], a2, mode = 'clip') print("\nResultant Array :")print(a1) Output: In the above example, mode=’clip’ replaces the last element along the axis instead of raising any error. Python numpy-Indexing Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25665, "s": 25637, "text": "\n25 Oct, 2020" }, { "code": null, "e": 26007, "s": 25665, "text": "Sometimes we need to remove values from the source Numpy array and add them at specific indices in the target array. In NumPy, we have this flexibility, we can remove values from one array and add them to another array. We can perform this operation using numpy.put() function and it can be applied to all forms of arrays like 1-D, 2-D, etc." }, { "code": null, "e": 26018, "s": 26007, "text": "Example 1:" }, { "code": null, "e": 26026, "s": 26018, "text": "Python3" }, { "code": "# Importing Numpy moduleimport numpy as np # Creating 1-D Numpy arraya1 = np.array([11, 10, 22, 30, 33])print(\"Array 1 :\")print(a1) a2 = np.array([1, 15, 60])print(\"Array 2 :\")print(a2) print(\"\\nTake 1 and 15 from Array 2 and put them in\\1st and 5th position of Array 1\") a1.put([0, 4], a2) print(\"Resultant Array :\")print(a1)", "e": 26358, "s": 26026, "text": null }, { "code": null, "e": 26366, "s": 26358, "text": "Output:" }, { "code": null, "e": 26482, "s": 26366, "text": "In the above example, we take two 1-D arrays and transfer values from one array to another at specific positions. " }, { "code": null, "e": 26493, "s": 26482, "text": "Example 2:" }, { "code": null, "e": 26501, "s": 26493, "text": "Python3" }, { "code": "# Importing Numpy moduleimport numpy as np # Creating 2-D Numpy arraya1 = np.array([[11, 10, 22, 30], [14, 58, 88, 100]]) print(\"Array 1 :\")print(a1) a2 = np.array([1, 15, 6, 40])print(\"Array 2 :\")print(a2) print(\"\\nTake 1, 15 and 6 from Array 2 and put them in 1st,\\4th and 7th positions of Array 1\") a1.put([0, 3, 6], a2) print(\"Resultant Array :\")print(a1)", "e": 26881, "s": 26501, "text": null }, { "code": null, "e": 26889, "s": 26881, "text": "Output:" }, { "code": null, "e": 27007, "s": 26889, "text": "In the above example, we take two different arrays and transfer values from 1-D to 2-D array at specific positions. " }, { "code": null, "e": 27018, "s": 27007, "text": "Example 3:" }, { "code": null, "e": 27026, "s": 27018, "text": "Python3" }, { "code": "# Importing Numpy moduleimport numpy as np # Creating 3-D Numpy arraya1 = np.array([[[11, 25, 7], [30, 45, 55], [20, 45, 7]], [[50, 65, 8], [70, 85, 10], [11, 22, 33]], [[19, 69, 36], [1, 5, 24], [4, 20, 9]]]) print(\"Array 1 :\")print(a1) # Creating 2-D arraya2 = np.array([[1, 15, 10], [6, 40, 50], [11, 5, 10]]) print(\"\\nArray 2 :\")print(a2) print(\"\\nTake 1, 15, 10, 6, 40 and 50 from Array 2 and put\\them in 1st, 3rd, 5th, 9th, 11th and 15th positions of Array 1\") a1.put([0, 2, 4, 8, 10, 14], a2) print(\"Resultant Array :\")print(a1)", "e": 27627, "s": 27026, "text": null }, { "code": null, "e": 27635, "s": 27627, "text": "Output:" }, { "code": null, "e": 27874, "s": 27635, "text": "In the above example, we take two different arrays and transfer values from 2-D to 3-D array at specific positions. One question arises, what will happen if out-of-bounds indices occur. For this, we have 3 modes in numpy.put() function " }, { "code": null, "e": 27907, "s": 27874, "text": "mode = {‘raise’, ‘wrap’, ‘clip’}" }, { "code": null, "e": 27942, "s": 27907, "text": "‘raise’ – raise an error (default)" }, { "code": null, "e": 27963, "s": 27942, "text": "‘wrap’ – wrap around" }, { "code": null, "e": 27990, "s": 27963, "text": "‘clip’ – clip to the range" }, { "code": null, "e": 28023, "s": 27990, "text": "Example 4: Taking mode = ‘raise’" }, { "code": null, "e": 28031, "s": 28023, "text": "Python3" }, { "code": "# Importing Numpy moduleimport numpy as np # Creating 2-D Numpy arraya1 = np.array([[11, 10, 22], [14, 58, 88]]) print(\"Array 1 :\")print(a1) a2 = np.array([[1, 15, 6], [40, 50, 70]]) print(\"Array 2 :\")print(a2) print(\"\\nTake 1 and 15 from Array 2 and put them in 1st \\and 5th positions of Array 1\") print(\"by mistake we write the index which is out of bound,\\now mode will play its role\") a1.put([0, 15], a2, mode='raise') print(\"\\nResultant Array :\")print(a1)", "e": 28528, "s": 28031, "text": null }, { "code": null, "e": 28536, "s": 28528, "text": "Output:" }, { "code": null, "e": 28623, "s": 28536, "text": "In the above example mode=’raise’ generates an error when indices become out of bound." }, { "code": null, "e": 28655, "s": 28623, "text": "Example 5: Taking mode = ‘clip’" }, { "code": null, "e": 28663, "s": 28655, "text": "Python3" }, { "code": "# Importing Numpy moduleimport numpy as np # Creating 2-D Numpy arraya1 = np.array([[11, 10, 22], [14, 58, 88]]) print(\"Array 1 :\")print(a1) a2 = np.array([[1, 15, 6], [40, 50, 70]]) print(\"Array 2 :\")print(a2) print(\"\\nTake 1 and 15 from Array 2 and put them in 1st and\\5th positions of Array 1\") print(\"by mistake we write the index which is out of bound,\\now mode will play its role\") a1.put([0, 15], a2, mode = 'clip') print(\"\\nResultant Array :\")print(a1)", "e": 29160, "s": 28663, "text": null }, { "code": null, "e": 29168, "s": 29160, "text": "Output:" }, { "code": null, "e": 29274, "s": 29168, "text": "In the above example, mode=’clip’ replaces the last element along the axis instead of raising any error. " }, { "code": null, "e": 29296, "s": 29274, "text": "Python numpy-Indexing" }, { "code": null, "e": 29309, "s": 29296, "text": "Python-numpy" }, { "code": null, "e": 29316, "s": 29309, "text": "Python" }, { "code": null, "e": 29414, "s": 29316, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29446, "s": 29414, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29488, "s": 29446, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29530, "s": 29488, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29586, "s": 29530, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29613, "s": 29586, "text": "Python Classes and Objects" }, { "code": null, "e": 29644, "s": 29613, "text": "Python | os.path.join() method" }, { "code": null, "e": 29673, "s": 29644, "text": "Create a directory in Python" }, { "code": null, "e": 29695, "s": 29673, "text": "Defaultdict in Python" }, { "code": null, "e": 29734, "s": 29695, "text": "Python | Get unique values from a list" } ]
Numpy | String Operations - GeeksforGeeks
19 Apr, 2020 This module is used to perform vectorized string operations for arrays of dtype numpy.string_ or numpy.unicode_. All of them are based on the standard string functions in Python’s built-in library. String Operations –numpy.lower() : This function returns the lowercase string from the given string. It converts all uppercase characters to lowercase. If no uppercase characters exist, it returns the original string. Output : ['geeks' 'for'] geeks numpy.split() : This function returns a list of strings after breaking the given string by the specified separator. Output : ['geeks', 'for', 'geeks'] ['geeks', 'for', 'geeks'] numpy.join() : This function is a string method and returns a string in which the elements of sequence have been joined by str separator. Output : g-e-e-k-s ['g-e-e-k-s', 'g:e:e:k:s'] String Information –numpy.count() : This function returns the number of occurrences of a substring in the given string. Output : [1, 0, 1] [0, 1, 0] numpy.rfind() : This function returns the highest index of the substring if found in given string. If not found then it returns -1. Output : [0, -1, 0] [-1, 0, -1] numpy.isnumeric() : This function returns “True” if all characters in the string are numeric characters, Otherwise, It returns “False”. Output : False False String Comparison –numpy.equal(): This function checks for string1 == string2 elementwise. Output : False numpy.not_equal(): This function checks whether two string is unequal or not. Output : True numpy.greater(): This function checks whether string1 is greater than string2 or not. Output : True Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Program for Breadth First Search or BFS for a Graph Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies How to calculate MOVING AVERAGE in a Pandas DataFrame? Session vs Token Based Authentication Difference Between Default VLAN and Native VLAN How to insert a pandas DataFrame to an existing PostgreSQL table? What is "network ID" and "host ID" in IP Addresses? Create a dictionary with list comprehension in Python What is Transmission Control Protocol (TCP)?
[ { "code": null, "e": 42909, "s": 42881, "text": "\n19 Apr, 2020" }, { "code": null, "e": 43107, "s": 42909, "text": "This module is used to perform vectorized string operations for arrays of dtype numpy.string_ or numpy.unicode_. All of them are based on the standard string functions in Python’s built-in library." }, { "code": null, "e": 43325, "s": 43107, "text": "String Operations –numpy.lower() : This function returns the lowercase string from the given string. It converts all uppercase characters to lowercase. If no uppercase characters exist, it returns the original string." }, { "code": null, "e": 43334, "s": 43325, "text": "Output :" }, { "code": null, "e": 43357, "s": 43334, "text": "['geeks' 'for']\ngeeks\n" }, { "code": null, "e": 43474, "s": 43357, "text": " numpy.split() : This function returns a list of strings after breaking the given string by the specified separator." }, { "code": null, "e": 43483, "s": 43474, "text": "Output :" }, { "code": null, "e": 43536, "s": 43483, "text": "['geeks', 'for', 'geeks']\n['geeks', 'for', 'geeks']\n" }, { "code": null, "e": 43675, "s": 43536, "text": " numpy.join() : This function is a string method and returns a string in which the elements of sequence have been joined by str separator." }, { "code": null, "e": 43684, "s": 43675, "text": "Output :" }, { "code": null, "e": 43722, "s": 43684, "text": "g-e-e-k-s\n['g-e-e-k-s', 'g:e:e:k:s']\n" }, { "code": null, "e": 43844, "s": 43724, "text": "String Information –numpy.count() : This function returns the number of occurrences of a substring in the given string." }, { "code": null, "e": 43853, "s": 43844, "text": "Output :" }, { "code": null, "e": 43874, "s": 43853, "text": "[1, 0, 1]\n[0, 1, 0]\n" }, { "code": null, "e": 44007, "s": 43874, "text": " numpy.rfind() : This function returns the highest index of the substring if found in given string. If not found then it returns -1." }, { "code": null, "e": 44016, "s": 44007, "text": "Output :" }, { "code": null, "e": 44040, "s": 44016, "text": "[0, -1, 0]\n[-1, 0, -1]\n" }, { "code": null, "e": 44177, "s": 44040, "text": " numpy.isnumeric() : This function returns “True” if all characters in the string are numeric characters, Otherwise, It returns “False”." }, { "code": null, "e": 44186, "s": 44177, "text": "Output :" }, { "code": null, "e": 44199, "s": 44186, "text": "False\nFalse\n" }, { "code": null, "e": 44292, "s": 44201, "text": "String Comparison –numpy.equal(): This function checks for string1 == string2 elementwise." }, { "code": null, "e": 44301, "s": 44292, "text": "Output :" }, { "code": null, "e": 44308, "s": 44301, "text": "False\n" }, { "code": null, "e": 44387, "s": 44308, "text": " numpy.not_equal(): This function checks whether two string is unequal or not." }, { "code": null, "e": 44396, "s": 44387, "text": "Output :" }, { "code": null, "e": 44402, "s": 44396, "text": "True\n" }, { "code": null, "e": 44489, "s": 44402, "text": " numpy.greater(): This function checks whether string1 is greater than string2 or not." }, { "code": null, "e": 44498, "s": 44489, "text": "Output :" }, { "code": null, "e": 44504, "s": 44498, "text": "True\n" }, { "code": null, "e": 44604, "s": 44506, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 44663, "s": 44604, "text": "Python Program for Breadth First Search or BFS for a Graph" }, { "code": null, "e": 44695, "s": 44663, "text": "Best Time to Buy and Sell Stock" }, { "code": null, "e": 44748, "s": 44695, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 44803, "s": 44748, "text": "How to calculate MOVING AVERAGE in a Pandas DataFrame?" }, { "code": null, "e": 44841, "s": 44803, "text": "Session vs Token Based Authentication" }, { "code": null, "e": 44889, "s": 44841, "text": "Difference Between Default VLAN and Native VLAN" }, { "code": null, "e": 44955, "s": 44889, "text": "How to insert a pandas DataFrame to an existing PostgreSQL table?" }, { "code": null, "e": 45007, "s": 44955, "text": "What is \"network ID\" and \"host ID\" in IP Addresses?" }, { "code": null, "e": 45061, "s": 45007, "text": "Create a dictionary with list comprehension in Python" } ]
Building modular javascript applications in ES6 with React, Webpack and Babel | by Tim Ermilov | Towards Data Science
So, you have decided to build your new javascript application using React and you also want to use that new fancy ES6 syntax in it. In addition you want to create reusable components and publish them to NPM. How exactly can you do this today? How do you publish ES6 to NPM and use it in your project later? It took me a while to nail all the bits and pieces, so I thought I’d share my knowledge here. If you don’t really want to read all the details and just want to see code — head straight to the last section. Let’s first figure out what exactly we want to do and how.Our main target is to have a React application that is written in ES6 and uses our custom React components. The tricky part comes with custom React components. Here are the requirements for them: Custom components should also be written in ES6Custom components should be completely self sufficient (usage should be as simple as “install, import, render”)Custom components should provide their own styles (because of 2)Custom components should be installable via NPM (because bower has a lot of issues)And finally — all custom components should have tests and code coverage reports.Bonus points — custom components should not depend on each other, but should be able to interact Custom components should also be written in ES6 Custom components should be completely self sufficient (usage should be as simple as “install, import, render”) Custom components should provide their own styles (because of 2) Custom components should be installable via NPM (because bower has a lot of issues) And finally — all custom components should have tests and code coverage reports. Bonus points — custom components should not depend on each other, but should be able to interact Additionally, we want to have nice things like code linting and source maps for debugging (since we have a compile step, this is actually a must). Now that we have all our requirements, we can start figuring out how exactly we can fulfill them. So, let’s decide on a toolset and libraries we’re going to use. Since we are going to use ES6 and browsers do not yet fully support it, we will need a compilation step. And because we want to manage our components using NPM, we want a CommonJS compatible toolset.There are two popular options available — Browserify and Webpack. Both will allow us to do most of the things we need, but we’re going to stick with Webpack since it’s quite much simpler to work with non-javascript files in it (e.g. styles, images, fonts). And working with styles was one of our requirements.We could stop here and just use a Webpack, but we are going to add Gulp.js on top just to have a bit more flexibility in tasks we can perform later (e.g. unit testing, test coverage, serving static assets). Now that we know how we will build our code, we need to figure out how to fulfill our first requirement — using ES6. There’s a number of ES6 transpilers we could use, most popular are: Traceur, Babel.js, TypeScript (well, kinda). But we’re going to stick with Babel.js since it has a better ecosystem (plugins, extensions, etc). Babel is a transpiler that allows you to use ES6+ code today and conveniently transpile it to ES5 that’s supported now by majority of browsers. If you haven’t heard about it, have a look at their docs — the project is pretty amazing. And as a bonus, in addition to ES6 syntax Babel also compiles JSX, so we can get rid of standard React JSX compiler in our compilation process.If you just want to use Babel.js, I’d recommend reading their usage docs. There’s as well a great post on using it from Dr. Axel Rauschmayer (I’d recommend his blog in general as well, if you are interested in javascript). Now that we have decided on the ES6 transpiler, let’s talk about being self sufficient. If we’re talking about pure React components — it’s relatively easy to make something that can work as a standalone thing (being reusable). There’s even an official guideline for that. But what happens when we need to provide default styles?Of course, we can take “pure JS” kind of approach and just inline styles into our JSX like so: The problem with this approach is that it’ll be almost impossible to change that style later from the parent application if we decide to.Plus, this approach won’t work if we would need to include images or something like custom fonts. So, what’s the better way then? Webpack to the rescue! Luckily for us Webpack allows requiring pretty much any types of files using loaders. Idea behind loaders is pretty simple — they are pluggable transformations that are applied to the files during loading. Essentially, they preprocess files. We will use a special babel-loader to transpile our ES6 code to ES5.But the cool part here is that the loaders can work on any files. So, if we want to include styles — we just need to add style-loader! I decided to go with LESS, so it’s a bit more complicated —I’d created a chain of loaders: First *.less files are processed by less-loader and converted to CSS Then compiled css is processed by css-loader and passed to next step Finally style-loader will include the final style into resulting code The code below shows the entry point of the component with LESS styling: As you can see, including styles is as easy as importing a file. Of course, that chain from less-loader, css-loader and style-loader must be already configured in our webpack configuration file (see example one in the next section). One of the issues with import styles from separate components is the fact that CSS uses global variables by default. Which means there’s no scoping. Which means that if you have two components that use similarly named classes, one of them will get overwritten. How do we evade this?The simplest way I could figure out was to create scopes artificially by using a component name as a topmost class in the markup and in the style file.Like so: That works pretty well since all the components will have unique names, which means there will be no conflict once they are assembled into one application. Plus, it’s quite easy to re-style the components using the component name as a class from the application level styles. So, how do you publish ES6 modules to NPM? Well, you actually don’t. At least not yet. It is possible to just push your code out there, but it is generally a bad idea and you will have a hard time importing that code into your main application (or other components) later. Of course, it’s possible to say to Webpack (and to Browserify as well) to compile the code on require. But then you’ll have problems running tests unless you use Webpack (and browser) for testing too. I usually try to run tests in cli since it’s usually faster and simpler to automate later (say, when you are setting up CI).The best way that worked for my projects so far was to ship both — original ES6 code and compiled ES5 code. Doing that is pretty easy: Add build command to your package.json Run build command as pre-publish step Use compiled ES5 code as main file Expose ES6 code through additional package.json fields Here’s how it looks: Using this approach gives us a couple of advantages: We can easily import or require() this module in any ES5 code and it will work!If we for some reason need access to the module’s source code, we can easily tell Webpack to use “es6” field for requiring and import the ES6 code We can easily import or require() this module in any ES5 code and it will work! If we for some reason need access to the module’s source code, we can easily tell Webpack to use “es6” field for requiring and import the ES6 code You’d be surprised how easy it is to set up tests and coverage for babel (great ecosystem, as I’d already mentioned).I’d always used mocha for all my testing needs, so I’ll be talking about it here. All you have to do to support ES6 code in mocha is to tell it to use babel pre-compiler by adding a compilers flag to mocha execution (or to mocha config file): --compilers: jsx?:babel/register And you are set, tests now can run directly on your ES6 code and of course can be written using that fancy ES6. And here comes the tricky part — we have React components and we want to run tests using mocha without having to open a browser (or to spin up a PhantomJS which is quite heavy). How do we do that?The answer is jsdom — a javascript implementation of the WHATWG DOM and HTML standards for iojs. It’s much lighter than Phantom and it gives pretty much all we need for testing React.Here’s how the test helper file that sets up a jsdom environment with React looks: Note that I’d used import statements for jsdom and localStorage, but used require() for React. This is because import statements are hoisted and we need to make sure that React is required after we have initialized jsdom. If you try to require React before having DOM, it’ll work OK until you try to interact with your components. Then you’ll run into various errors because React assumed non-browser environment and couldn’t work with DOM. And now that we have mocha test running properly, getting Istanbul test coverage is as easy as executing: istanbul cover _mocha -- -R spec And here’s our bonus requirement — interaction but without inter-dependency. This one is quite unique to one of the projects I’m working on, so if you are not curious, feel free to skip this section. If not, then let’s talk about ways of achieving this.So, we need to make several parts of system interact without coupling them together. In a perfect world we’d prefer that they don’t even know about each other and just respond to requests. That task sounds pretty familiar, doesn’t it?You’ve probably heard about microservices by now. Or maybe you even use them already. If not, I’d recommend watching fantastic talk on the topic by Fred George.If you are too lazy to watch (or want to do it later), the idea of microserivces is a simple one: microservices are small, independent entities communicating with each other using a common interface. That common interface can be a variety of things including: messaging bus, REST, RPC, etc. And since we’re doing client-side javascript application, we don’t really have too much of a choice for that interface. Luckily for us, there is an awesome library that feels like it was made specifically for this case — postal.js.Even though under the hood it still uses callbacks, it provides a great deal of flexibility by allowing to split messages into channels and topic. It’s easier to show how all this will work using an example.Imagine we have an app that requires some sort of authentication and URL signing for getting data. With postal we can define auth channel that will listen to those signing requests and return signed URL in different topic, like so: This works pretty well because we don’t need to know anything about other component — we only need to know about the channel and topics to use. On one hand this does means that burden of managing this falls on to developer. On other hand, this approach allows to swap the auth component with ease — today we’re using OAuth, tomorrow our custom token system, then something else, and all we need to do to support a new workflow is to swap that auth component for a different one. And the last tiny bit is adding code linting and enabling source maps.Since jshint does not plays well with ES6 and React code, we’re going to use eslint. It supports both of the syntaxes and can be extended with plugins.Using it with Webpack is quite easy, all you have to do is to add a couple of lines to your webpack config file. The snippet below shows the needed options: Note that node_modules folder is excluded from linting, so only your actual component code will get through the procedure.Webpack will output all the linting problems to the console after the compilation process is finished. After combining all of the things mentioned above, I’d created Turris.js — set of helper packages and a yeoman generators to easily scaffold ES6 React applications and standalone components. If you are not interested in generators and just want to see example code of the application and standalone component, you can find both in their github repositories: turris-example-application and turris-example-component. I’d tried to make creating new applications as simple as possible. Here’s what you need to do to create one: Make sure you have latest io.js and npm installed. Get yeoman and turris-generator from npm: $ npm install -g yo generator-turris Create a new folder for your app, enter it and execute turris generator: $ mkdir HelloWorld$ cd HelloWorld$ yo turris _-----_ | | .--------------------------. |--(o)--| | Welcome to the | `--------- ́ | breathtaking Turris | ( _ ́U`_ ) | generator! | /___A___\ '--------------------------' | ~ | __'.___.'__ ́ ` |° ́ Y `? Your project name: (HelloWorld) Answer a couple of questions and yeoman will do all the work for you! Start your new shiny app with “npm start” Navigate to http://localhost:8080, open your favourite editor and start changing it to your liking In addition to scaffolding a basic application, Turris generator provides three helper generators: Component generator — will generate a new component inside of your app. Handy for small components that you are not going to re-use.Page generator — will generate a new page and inject it into react-router for you. Nothing fancy here, just a little subgenerator to save your time.Docker generator — will generate a dockerfile that has all the needed things for running the app inside. Component generator — will generate a new component inside of your app. Handy for small components that you are not going to re-use. Page generator — will generate a new page and inject it into react-router for you. Nothing fancy here, just a little subgenerator to save your time. Docker generator — will generate a dockerfile that has all the needed things for running the app inside. For more information on usage, subgenerators, project structure and that other stuff — refer to readme in the project repository. Creating a component is not much harder. Here’s how to do it (requirements are the same as for the main generator): Get turris-generator-component from npm: $ npm install -g generator-turris-component Create a new folder for your component, enter it and execute turris component generator: $ mkdir HelloWorld-Component$ cd HelloWorld-Component$ yo turris-component _-----_ | | .--------------------------. |--(o)--| | Welcome to the | `--------- ́ | stupendous | ( _ ́U`_ ) | TurrisComponent | /___A___\ | generator! | | ~ | '--------------------------' __'.___.'__ ́ ` |° ́ Y `? Your component name: (HelloWorld-Component) Answer a couple of questions and yeoman will do all the work for you! Start your new shiny component in debug mode with “npm start” Navigate to http://localhost:8080, open your favourite editor and start changing it to your liking For more information on usage and project structure and other stuff — refer to readme in the project repository. I hope you have found something useful in this text. And maybe you even tried my generators. If not — give them a shot! If yes — I’d love to hear any feedback or issues you might have. And of course, pull requests are appreciated. No rights reserved by the author.
[ { "code": null, "e": 572, "s": 171, "text": "So, you have decided to build your new javascript application using React and you also want to use that new fancy ES6 syntax in it. In addition you want to create reusable components and publish them to NPM. How exactly can you do this today? How do you publish ES6 to NPM and use it in your project later? It took me a while to nail all the bits and pieces, so I thought I’d share my knowledge here." }, { "code": null, "e": 684, "s": 572, "text": "If you don’t really want to read all the details and just want to see code — head straight to the last section." }, { "code": null, "e": 938, "s": 684, "text": "Let’s first figure out what exactly we want to do and how.Our main target is to have a React application that is written in ES6 and uses our custom React components. The tricky part comes with custom React components. Here are the requirements for them:" }, { "code": null, "e": 1420, "s": 938, "text": "Custom components should also be written in ES6Custom components should be completely self sufficient (usage should be as simple as “install, import, render”)Custom components should provide their own styles (because of 2)Custom components should be installable via NPM (because bower has a lot of issues)And finally — all custom components should have tests and code coverage reports.Bonus points — custom components should not depend on each other, but should be able to interact" }, { "code": null, "e": 1468, "s": 1420, "text": "Custom components should also be written in ES6" }, { "code": null, "e": 1580, "s": 1468, "text": "Custom components should be completely self sufficient (usage should be as simple as “install, import, render”)" }, { "code": null, "e": 1645, "s": 1580, "text": "Custom components should provide their own styles (because of 2)" }, { "code": null, "e": 1729, "s": 1645, "text": "Custom components should be installable via NPM (because bower has a lot of issues)" }, { "code": null, "e": 1810, "s": 1729, "text": "And finally — all custom components should have tests and code coverage reports." }, { "code": null, "e": 1907, "s": 1810, "text": "Bonus points — custom components should not depend on each other, but should be able to interact" }, { "code": null, "e": 2054, "s": 1907, "text": "Additionally, we want to have nice things like code linting and source maps for debugging (since we have a compile step, this is actually a must)." }, { "code": null, "e": 2216, "s": 2054, "text": "Now that we have all our requirements, we can start figuring out how exactly we can fulfill them. So, let’s decide on a toolset and libraries we’re going to use." }, { "code": null, "e": 2931, "s": 2216, "text": "Since we are going to use ES6 and browsers do not yet fully support it, we will need a compilation step. And because we want to manage our components using NPM, we want a CommonJS compatible toolset.There are two popular options available — Browserify and Webpack. Both will allow us to do most of the things we need, but we’re going to stick with Webpack since it’s quite much simpler to work with non-javascript files in it (e.g. styles, images, fonts). And working with styles was one of our requirements.We could stop here and just use a Webpack, but we are going to add Gulp.js on top just to have a bit more flexibility in tasks we can perform later (e.g. unit testing, test coverage, serving static assets)." }, { "code": null, "e": 3860, "s": 2931, "text": "Now that we know how we will build our code, we need to figure out how to fulfill our first requirement — using ES6. There’s a number of ES6 transpilers we could use, most popular are: Traceur, Babel.js, TypeScript (well, kinda). But we’re going to stick with Babel.js since it has a better ecosystem (plugins, extensions, etc). Babel is a transpiler that allows you to use ES6+ code today and conveniently transpile it to ES5 that’s supported now by majority of browsers. If you haven’t heard about it, have a look at their docs — the project is pretty amazing. And as a bonus, in addition to ES6 syntax Babel also compiles JSX, so we can get rid of standard React JSX compiler in our compilation process.If you just want to use Babel.js, I’d recommend reading their usage docs. There’s as well a great post on using it from Dr. Axel Rauschmayer (I’d recommend his blog in general as well, if you are interested in javascript)." }, { "code": null, "e": 4284, "s": 3860, "text": "Now that we have decided on the ES6 transpiler, let’s talk about being self sufficient. If we’re talking about pure React components — it’s relatively easy to make something that can work as a standalone thing (being reusable). There’s even an official guideline for that. But what happens when we need to provide default styles?Of course, we can take “pure JS” kind of approach and just inline styles into our JSX like so:" }, { "code": null, "e": 4551, "s": 4284, "text": "The problem with this approach is that it’ll be almost impossible to change that style later from the parent application if we decide to.Plus, this approach won’t work if we would need to include images or something like custom fonts. So, what’s the better way then?" }, { "code": null, "e": 5110, "s": 4551, "text": "Webpack to the rescue! Luckily for us Webpack allows requiring pretty much any types of files using loaders. Idea behind loaders is pretty simple — they are pluggable transformations that are applied to the files during loading. Essentially, they preprocess files. We will use a special babel-loader to transpile our ES6 code to ES5.But the cool part here is that the loaders can work on any files. So, if we want to include styles — we just need to add style-loader! I decided to go with LESS, so it’s a bit more complicated —I’d created a chain of loaders:" }, { "code": null, "e": 5179, "s": 5110, "text": "First *.less files are processed by less-loader and converted to CSS" }, { "code": null, "e": 5248, "s": 5179, "text": "Then compiled css is processed by css-loader and passed to next step" }, { "code": null, "e": 5318, "s": 5248, "text": "Finally style-loader will include the final style into resulting code" }, { "code": null, "e": 5391, "s": 5318, "text": "The code below shows the entry point of the component with LESS styling:" }, { "code": null, "e": 5624, "s": 5391, "text": "As you can see, including styles is as easy as importing a file. Of course, that chain from less-loader, css-loader and style-loader must be already configured in our webpack configuration file (see example one in the next section)." }, { "code": null, "e": 6066, "s": 5624, "text": "One of the issues with import styles from separate components is the fact that CSS uses global variables by default. Which means there’s no scoping. Which means that if you have two components that use similarly named classes, one of them will get overwritten. How do we evade this?The simplest way I could figure out was to create scopes artificially by using a component name as a topmost class in the markup and in the style file.Like so:" }, { "code": null, "e": 6342, "s": 6066, "text": "That works pretty well since all the components will have unique names, which means there will be no conflict once they are assembled into one application. Plus, it’s quite easy to re-style the components using the component name as a class from the application level styles." }, { "code": null, "e": 7075, "s": 6342, "text": "So, how do you publish ES6 modules to NPM? Well, you actually don’t. At least not yet. It is possible to just push your code out there, but it is generally a bad idea and you will have a hard time importing that code into your main application (or other components) later. Of course, it’s possible to say to Webpack (and to Browserify as well) to compile the code on require. But then you’ll have problems running tests unless you use Webpack (and browser) for testing too. I usually try to run tests in cli since it’s usually faster and simpler to automate later (say, when you are setting up CI).The best way that worked for my projects so far was to ship both — original ES6 code and compiled ES5 code. Doing that is pretty easy:" }, { "code": null, "e": 7114, "s": 7075, "text": "Add build command to your package.json" }, { "code": null, "e": 7152, "s": 7114, "text": "Run build command as pre-publish step" }, { "code": null, "e": 7187, "s": 7152, "text": "Use compiled ES5 code as main file" }, { "code": null, "e": 7242, "s": 7187, "text": "Expose ES6 code through additional package.json fields" }, { "code": null, "e": 7263, "s": 7242, "text": "Here’s how it looks:" }, { "code": null, "e": 7316, "s": 7263, "text": "Using this approach gives us a couple of advantages:" }, { "code": null, "e": 7542, "s": 7316, "text": "We can easily import or require() this module in any ES5 code and it will work!If we for some reason need access to the module’s source code, we can easily tell Webpack to use “es6” field for requiring and import the ES6 code" }, { "code": null, "e": 7622, "s": 7542, "text": "We can easily import or require() this module in any ES5 code and it will work!" }, { "code": null, "e": 7769, "s": 7622, "text": "If we for some reason need access to the module’s source code, we can easily tell Webpack to use “es6” field for requiring and import the ES6 code" }, { "code": null, "e": 8129, "s": 7769, "text": "You’d be surprised how easy it is to set up tests and coverage for babel (great ecosystem, as I’d already mentioned).I’d always used mocha for all my testing needs, so I’ll be talking about it here. All you have to do to support ES6 code in mocha is to tell it to use babel pre-compiler by adding a compilers flag to mocha execution (or to mocha config file):" }, { "code": null, "e": 8162, "s": 8129, "text": "--compilers: jsx?:babel/register" }, { "code": null, "e": 8274, "s": 8162, "text": "And you are set, tests now can run directly on your ES6 code and of course can be written using that fancy ES6." }, { "code": null, "e": 8736, "s": 8274, "text": "And here comes the tricky part — we have React components and we want to run tests using mocha without having to open a browser (or to spin up a PhantomJS which is quite heavy). How do we do that?The answer is jsdom — a javascript implementation of the WHATWG DOM and HTML standards for iojs. It’s much lighter than Phantom and it gives pretty much all we need for testing React.Here’s how the test helper file that sets up a jsdom environment with React looks:" }, { "code": null, "e": 9177, "s": 8736, "text": "Note that I’d used import statements for jsdom and localStorage, but used require() for React. This is because import statements are hoisted and we need to make sure that React is required after we have initialized jsdom. If you try to require React before having DOM, it’ll work OK until you try to interact with your components. Then you’ll run into various errors because React assumed non-browser environment and couldn’t work with DOM." }, { "code": null, "e": 9283, "s": 9177, "text": "And now that we have mocha test running properly, getting Istanbul test coverage is as easy as executing:" }, { "code": null, "e": 9316, "s": 9283, "text": "istanbul cover _mocha -- -R spec" }, { "code": null, "e": 9516, "s": 9316, "text": "And here’s our bonus requirement — interaction but without inter-dependency. This one is quite unique to one of the projects I’m working on, so if you are not curious, feel free to skip this section." }, { "code": null, "e": 10254, "s": 9516, "text": "If not, then let’s talk about ways of achieving this.So, we need to make several parts of system interact without coupling them together. In a perfect world we’d prefer that they don’t even know about each other and just respond to requests. That task sounds pretty familiar, doesn’t it?You’ve probably heard about microservices by now. Or maybe you even use them already. If not, I’d recommend watching fantastic talk on the topic by Fred George.If you are too lazy to watch (or want to do it later), the idea of microserivces is a simple one: microservices are small, independent entities communicating with each other using a common interface. That common interface can be a variety of things including: messaging bus, REST, RPC, etc." }, { "code": null, "e": 10632, "s": 10254, "text": "And since we’re doing client-side javascript application, we don’t really have too much of a choice for that interface. Luckily for us, there is an awesome library that feels like it was made specifically for this case — postal.js.Even though under the hood it still uses callbacks, it provides a great deal of flexibility by allowing to split messages into channels and topic." }, { "code": null, "e": 10924, "s": 10632, "text": "It’s easier to show how all this will work using an example.Imagine we have an app that requires some sort of authentication and URL signing for getting data. With postal we can define auth channel that will listen to those signing requests and return signed URL in different topic, like so:" }, { "code": null, "e": 11403, "s": 10924, "text": "This works pretty well because we don’t need to know anything about other component — we only need to know about the channel and topics to use. On one hand this does means that burden of managing this falls on to developer. On other hand, this approach allows to swap the auth component with ease — today we’re using OAuth, tomorrow our custom token system, then something else, and all we need to do to support a new workflow is to swap that auth component for a different one." }, { "code": null, "e": 11781, "s": 11403, "text": "And the last tiny bit is adding code linting and enabling source maps.Since jshint does not plays well with ES6 and React code, we’re going to use eslint. It supports both of the syntaxes and can be extended with plugins.Using it with Webpack is quite easy, all you have to do is to add a couple of lines to your webpack config file. The snippet below shows the needed options:" }, { "code": null, "e": 12006, "s": 11781, "text": "Note that node_modules folder is excluded from linting, so only your actual component code will get through the procedure.Webpack will output all the linting problems to the console after the compilation process is finished." }, { "code": null, "e": 12197, "s": 12006, "text": "After combining all of the things mentioned above, I’d created Turris.js — set of helper packages and a yeoman generators to easily scaffold ES6 React applications and standalone components." }, { "code": null, "e": 12421, "s": 12197, "text": "If you are not interested in generators and just want to see example code of the application and standalone component, you can find both in their github repositories: turris-example-application and turris-example-component." }, { "code": null, "e": 12530, "s": 12421, "text": "I’d tried to make creating new applications as simple as possible. Here’s what you need to do to create one:" }, { "code": null, "e": 12581, "s": 12530, "text": "Make sure you have latest io.js and npm installed." }, { "code": null, "e": 12623, "s": 12581, "text": "Get yeoman and turris-generator from npm:" }, { "code": null, "e": 12660, "s": 12623, "text": "$ npm install -g yo generator-turris" }, { "code": null, "e": 12733, "s": 12660, "text": "Create a new folder for your app, enter it and execute turris generator:" }, { "code": null, "e": 13094, "s": 12733, "text": "$ mkdir HelloWorld$ cd HelloWorld$ yo turris _-----_ | | .--------------------------. |--(o)--| | Welcome to the | `--------- ́ | breathtaking Turris | ( _ ́U`_ ) | generator! | /___A___\\ '--------------------------' | ~ | __'.___.'__ ́ ` |° ́ Y `? Your project name: (HelloWorld)" }, { "code": null, "e": 13164, "s": 13094, "text": "Answer a couple of questions and yeoman will do all the work for you!" }, { "code": null, "e": 13206, "s": 13164, "text": "Start your new shiny app with “npm start”" }, { "code": null, "e": 13305, "s": 13206, "text": "Navigate to http://localhost:8080, open your favourite editor and start changing it to your liking" }, { "code": null, "e": 13404, "s": 13305, "text": "In addition to scaffolding a basic application, Turris generator provides three helper generators:" }, { "code": null, "e": 13789, "s": 13404, "text": "Component generator — will generate a new component inside of your app. Handy for small components that you are not going to re-use.Page generator — will generate a new page and inject it into react-router for you. Nothing fancy here, just a little subgenerator to save your time.Docker generator — will generate a dockerfile that has all the needed things for running the app inside." }, { "code": null, "e": 13922, "s": 13789, "text": "Component generator — will generate a new component inside of your app. Handy for small components that you are not going to re-use." }, { "code": null, "e": 14071, "s": 13922, "text": "Page generator — will generate a new page and inject it into react-router for you. Nothing fancy here, just a little subgenerator to save your time." }, { "code": null, "e": 14176, "s": 14071, "text": "Docker generator — will generate a dockerfile that has all the needed things for running the app inside." }, { "code": null, "e": 14306, "s": 14176, "text": "For more information on usage, subgenerators, project structure and that other stuff — refer to readme in the project repository." }, { "code": null, "e": 14422, "s": 14306, "text": "Creating a component is not much harder. Here’s how to do it (requirements are the same as for the main generator):" }, { "code": null, "e": 14463, "s": 14422, "text": "Get turris-generator-component from npm:" }, { "code": null, "e": 14507, "s": 14463, "text": "$ npm install -g generator-turris-component" }, { "code": null, "e": 14596, "s": 14507, "text": "Create a new folder for your component, enter it and execute turris component generator:" }, { "code": null, "e": 15032, "s": 14596, "text": "$ mkdir HelloWorld-Component$ cd HelloWorld-Component$ yo turris-component _-----_ | | .--------------------------. |--(o)--| | Welcome to the | `--------- ́ | stupendous | ( _ ́U`_ ) | TurrisComponent | /___A___\\ | generator! | | ~ | '--------------------------' __'.___.'__ ́ ` |° ́ Y `? Your component name: (HelloWorld-Component)" }, { "code": null, "e": 15102, "s": 15032, "text": "Answer a couple of questions and yeoman will do all the work for you!" }, { "code": null, "e": 15164, "s": 15102, "text": "Start your new shiny component in debug mode with “npm start”" }, { "code": null, "e": 15263, "s": 15164, "text": "Navigate to http://localhost:8080, open your favourite editor and start changing it to your liking" }, { "code": null, "e": 15376, "s": 15263, "text": "For more information on usage and project structure and other stuff — refer to readme in the project repository." }, { "code": null, "e": 15607, "s": 15376, "text": "I hope you have found something useful in this text. And maybe you even tried my generators. If not — give them a shot! If yes — I’d love to hear any feedback or issues you might have. And of course, pull requests are appreciated." }, { "code": null, "e": 15626, "s": 15607, "text": "No rights reserved" } ]
Model selection 101, using R. Quick and dirty markup of simple model... | by Peter Nistrup | Towards Data Science
Since this is a very introductory look at model selection we assume the data you’ve acquired has already been cleaned, scrubbed and ready to go. Data cleaning is a whole subject in and of itself and is actually the primary time-sink of any Data Scientist. Go to the end of this article if you want to download the data for yourself and follow along! Edit: I’ve made a “sequel” to this article about visualizing and plotting the model we find if you want to check that out after reading this one!: medium.com Make sure to follow my profile if you enjoy this article and want to see more! This is the skeleton I use for creating a simple LM or GLM: Create a base-model using all available variables and dataFactorize categorical variables if R didn’t do the jobAdd relevant power-transformationsAdd relevant variable interactionRemove insignificant variables with relevant testing criteria- Repeat step 3–5 until you’ve exhausted your optionsRemove any outlying datapointsEvaluate your modelVisualizing your findings Create a base-model using all available variables and data Factorize categorical variables if R didn’t do the job Add relevant power-transformations Add relevant variable interaction Remove insignificant variables with relevant testing criteria- Repeat step 3–5 until you’ve exhausted your options Remove any outlying datapoints Evaluate your model Visualizing your findings Lets start by setting up a workspace and loading our data. In this example we’re working on a dataset describing employment-status of women based on whether or not you’re a foreigner, the amount of government-entitled support (log-transformed), age, years of education and the number of children (spread in two categorical variables ‘young.children’ and ‘school.children’): rm(list=ls()) # “Clear current R environment”setwd(“C:/R/Workspace”) # Setting up your workspacedat <- read.table(“employment_data.txt”, header=T) # Load that datastr(dat)summary(dat) which outputs: The first thing we notice is that our response-variable is binomial (obviously) suggesting that we have a binomial distribution which means we’ll have to fit a GLM instead of a traditional LM: fit.1 <- glm(employed == "yes" ~ ., data = dat, family = binomial)summary(fit.1) This fit is the most general fit we can use by default, it fits a binomial model (family = binomial) with respect to the response-variable “employed” having a value “yes”, using every variable in the dataset (~ .) giving us the following output: Right, so a few problems right off the bat, we don’t like seeing p-values above 0.05, much less above 0.1, but before we recklessly remove them lets check for variable interactions and power-transformations first! Lets consider the possibility that there’s a categorical difference between not having any children and actually having any number of children larger than zero, thus we add the categorical variables for having 0 children: ‘factor(young.children == 0)’, ‘factor(school.children == 0)’ and a combined factor for not having any children at all ‘factor(young.children + school.children == 0)’ We can update our fit with the new variables: tempfit <- update(fit.1, .~. + factor(young.children == 0) + factor(school.children == 0) + factor(young.children + school.children == 0))summary(tempfit) So we’ve already improved our model a bit in terms of AIC from 1066.8 to 1050.2! Lets take a look at our continuous variables and watch for possible power-transformations: A neat way to look for potential power-transformations of a binomial distribution is using this custom function: logit.plot <- function(x, y, h, link=’logit’, xlab=deparse(substitute(x)), yname=deparse(substitute(y)), ylab, rug=T, data, ...){ if(!missing(data)){ call <- match.call() dataPos <- match(“data”,names(call)) return(invisible(with(data, eval(call[-dataPos])))) } if (length(levels(factor(y)))!=2) stop(‘y must be binary’) succes <- levels(factor(y))[2] if (missing(ylab)) ylab <- paste(binomial(link)$link,’ P{‘,yname,’=’,succes,’|’,xlab,’}’, sep=’’, collapse=’’) if (is.factor(y)) y <- as.numeric(y==levels(y)[2]) x.seq <- seq(min(x),max(x),length=101) smooth <- binomial(link)$linkfun(ksmooth(x, y, ’normal’, h, x.points=x.seq)$y) plot(smooth~x.seq, ylab=ylab, xlab=xlab, type=’l’,...) if (rug) rug(x) invisible(xy.coords(x = x.seq, y = smooth, xlab = xlab, ylab = ylab))} It’s actually decently simple, it plots the link(E[y|x]) against x with E[y|x] estimated using a Nadaraya-Watson kernel regression estimate: This take the following arguments:x — Your explanatory variablesy — The binary outcome variableh — Bandwidth for the Nadaraya-Watson kernel regression estimatedata — Self explanatory... — Whatever additional arguments you want to pass to plot() Using this function iterating over different bandwidths we get the following kinds of plot: for(i in seq(2.5,10,length.out = 6)) logit.plot(x = age, y = employed == ‘yes’, h = i, data = dat, main = paste0(“bandwidth = “,i)) In this example with ‘age’ we can see that the function begins smoothing around a bandwidth around 7, the graph could approximate a 2. or maybe 3. degree polynomial, the same is true for ‘education’ and ‘gov.support’ but for simplicity we’ll consider the case of all three taking shape as 2. degree polynomials: tempfit <- update(tempfit, .~. + I(age^2) + I(education^2) + I(gov.support^2))summary(tempfit) Quite the improvement in terms of AIC, from 1050.2 to 1017.7! Lots of insignificant variables though! This is our first attempt at a “full” model, so lets define this as our ‘fit.2’ and continue. fit.2 <- tempfit The easiest way to check for variable interaction is using the R-function ‘add1’, this is simply the case of defining a scope to test and which test to use when testing relative to the original model. F-tests are usually only relevant for LM and AOV models so we can ‘safely’ ignore that testing criteria, we’ll instead be using a χ2-test (Chisq or Chi2): add1(fit.2, scope = .~. + .^2, test=”Chisq”) This scope is simply asking to test the current model (.~.) plus interaction between existing variables (+ .^2), this will output a lot of interactions, some with statistically significant P-values, but it can be annoying to manually sort through, so lets sort the list so we get the lowest P-values on the top: add1.test <- add1(fit.2, scope = .~. + .^2, test=”Chisq”)add1.test[order(add1.test$’Pr(>Chi)’),] Right, so it seems like there might be an interaction between the foreigner and age variables. One thing to consider before simply adding the interaction with the lowest P-value is whether or not this makes sense in context of our current model, right now age2 is actually the most significant variable in our model so we might argue that adding the interaction between foreigner and age2 is more intuitive, for simplicity we’ll stick with the foreigner:age interaction. Lets test for more interactions after adding the variable interaction foreigner:age: add1.test <- add1(update(fit.2, .~. + foreigner:age), scope = .~. + .^2, test=”Chisq”)add1.test[order(add1.test$’Pr(>Chi)’),] Now it seems like there’s a significant interaction in foreigner:factor(young.children + school.children == 0) After a few rounds of this we end up seeing no new statistically significant interactions, by the end we’ve added the following interactions: + foreigner:age + foreigner:factor(young.children + school.children == 0) + age:school.children + gov.support:factor(young.children == 0) So lets update our fit with the new variable interactions as follows: fit.3 <- update(fit.2, .~. + foreigner:age + foreigner:factor(young.children + school.children == 0) + age:school.children + gov.support:factor(young.children == 0))summary(fit.3) A small improvement in AIC once more, from 1017.7 to 1006.9. This process is quite similar to the last one in step 4. We’ll simply be using the drop1 function in R now instead of add1, and due to us seeking to remove instead of appending variables we seek the highest P-value instead of the lowest (we’ll still use χ2-test as our criteria): drop1.test <- drop1(fit.3, test=”Chisq”)drop1.test[rev(order(drop1.test$’Pr(>Chi)’)),] This tells us mostly the same as our model-summary, gov.support2 definitely dosn’t seem to be statistically significant, so we’ll remove that first and so on and so forth, we end up removing the following variables:- gov.support2- young.children- education- education2 After those have been removed we see that all the remaining variables are statistically significant, so lets update our fit by removing the variables listed above: fit.4 <- update(fit.3, .~. — I(gov.support^2) — young.children — education — I(education^2))summary(fit.4) Nice, another improvement in AIC although marginal and insignificant, the main advantage of this model over our previous is the added simplicity inherent in the reduced number of explanatory variables! One might wonder “Why aren’t we removing the gov.support variable? It’s clearly insignificant when looking at the summary of our model!” this is due to the principle of marginality which prohibits us from removing an insignificant variable if said variable has a significant interaction with another, like gov.support:factor(young.children == 0). You might argue that removing gov.support would be beneficial to the simplicity of the model given that it’s clearly insignificant and that the interaction with the young.children == 0 variable is only marginally significant (p = 0.435), however upon further inspection when removing gov.support from the model the variable-interaction splits into two variables for TRUE and FALSE, thus not giving us any added simplicity, the AIC, all other coefficients as well as the null- and residual deviance stays the exact same and by that account I close to leave it in the model. Doing an add1 and a drop1 test on our new and improved model shows us there’re no new interactions that are significant and that all current variables are significant so we’re done! The final fit is: glm(employed == “yes” ~ foreigner + gov.support + age + school.children + factor(young.children == 0) + factor(school.children == 0) + factor(young.children + school.children == 0) + I(age^2) + foreigner:age + foreigner:factor(young.children + school.children == 0) + age:school.children + gov.support:factor(young.children == 0), family = binomial, data = dat) So now that we have a model we’re satisfied with we can look for outliers that negatively effect the model. Using the “car” package https://www.rdocumentation.org/packages/car/versions/1.0-2 we can use the influencePlot() and outlierTest() functions to find potential outlier: We see that the datapoint 416 is classified as an outlier in both tests, we can take a look at the point in a few of our plots to gauge whether or not to remove it: par(mfrow = c(2, 2)) # 2 row(s), 2 column(s)plot(fit.4, col=ifelse(as.integer(rownames(dat))==416, “red”, “black”), pch=20) It seems like this could very well be screwing a bit with our model, note that we should actually be using pearson residuals to gauge our models fit so the fact that we don’t have anything close to a straight line in the upper left plot is fine, Q-Q plots are irrelevant for this kind of model as well. Lets try removing the point and take a look at the new fit: final.fit <- update(fit.4, data = dat[-c(416),])summary(final.fit) Down to almost 1000 AIC from the original 1067, this isn’t really a relevant measure of performance when comparing the AIC of two different sets of data (since we removed point 416), we would actually have to conclude that 416 was an outlier in the initial model as well, remove it and then compare the AIC value of the initial model without point 416 to our final fit without point 416 as well. Looking at another round of influencePlot() and outlierTest() we find that datapoint 329 is acting out as well, however looking at the actual plots we see that we can’t really justify a removal of the data like we could with 416. This is our final fit. So now that we have a final fit where we can’t confidently add or remove any interactions variables and other transformations it’s time to evaluate if our model actually fits our data and if there’s even a statistically significant difference between our final fit and the first “naive” fit. Lets start by taking a look at our fitted values vs. the Pearson residuals: par(mfrow = c(1, 1)) # 2 row(s), 2 column(s)plot(p.resid ~ fit.val)lines(ksmooth(y = p.resid, x = fit.val, bandwidth=.1, kernel=’normal’), col=’blue’)abline(h=0) This is a pretty decent fit, lets take a look at the fit for the major explanatory variables as well: With the exception of ‘gov.support’ everything looks quite nice, also the reason for the bend in ‘gov.support’ seems to be a single outlier in which someone was granted a substantially lower amount of support compared to all our other points of data. Overfitting is the bane of all statistical modelling, how can you make sure your model isn’t just fitting to the exact data you fed it? The goal is to make a model which generalizes and doesn’t just cater to the current data at hand. So how do we test if our model is overfitting on our data? A popular metric to test is the delta value generated through Cross-Validation, we can calculated these by using the cv.glm function from the ‘boot’ package and compare our final fit to our first! cv.glm(dat[-c(416),], final.fit, K = 13)$deltacv.glm(dat[-c(416),], update(fit.1, data = dat[-c(416),]), K = 13)$delta In the code above we’re using k-fold cross-validation with k = 13 (since 13 is a factor of 871 which is the length of our data after removing the outlier) this means we’re splitting our data in 13 ‘chunks’. The delta values is a vector wherein the first component is the raw cross-validation estimate of prediction error and the second component is the adjusted cross-validation estimate (designed to compensate for the bias introduced by not using an exhaustive testing methods such as leave-one-out) Running the code above yields the following delta-values, note that these are subject to some random variance so you might not get the exact same values: The prediction error is lower for the final fit, even when testing with cross-validation. Thus we can assume that our model hasn’t been overfitting on our data! So now we’ve concluded that our model is actually a pretty decent fit for our data, but is it a statistically significant difference from the “naive” model without any transformations and variable interactions? We can use an ANOVA test for this, we just have to remove the same point of data in both fits: There’s definitely a significant difference between the two fits, we can happily conclude that our hard work has paid off! Now that we’ve gotten ourselves a model, how do we actually visualize and interpret what it says about the relationships in our data? Take a look at the following walk-trough which uses the same data and model as this article!: medium.com Please keep in mind that this is purely introductory and that this isn’t an exhaustive analysis or conclusion! If we were more rigorous in our pursuit we would’ve incorporated Cross-Validation tests and ANOVA tests on each new iteration of our model, ie. whenever we add a new variable, interaction or power-transformation. Feel free to message me if you have any questions and please correct me if you feel like I missed something or did something wrong, do keep in mind that this is suppose to serve as an introduction to modelling in R, I’m well aware that this process is highly simplified compared to more advanced methods! If you want to try your luck with this same dataset give it a go here: https://github.com/pela15ae/statmod/blob/master/employment_data.txt The data is Danish so to convert the headers and categorical values to English run this piece of code: names(dat) <- c(“employed”, “foreigner”, “gov.support”, “age”, “education”, “young.children”, “school.children”)levels(dat$employed)[1] <- “yes”levels(dat$employed)[2] <- “no”levels(dat$foreigner)[1] <- “yes”levels(dat$foreigner)[2] <- “no” If you want to see and learn more, be sure to follow me on Medium🔍 and Twitter 🐦
[ { "code": null, "e": 522, "s": 172, "text": "Since this is a very introductory look at model selection we assume the data you’ve acquired has already been cleaned, scrubbed and ready to go. Data cleaning is a whole subject in and of itself and is actually the primary time-sink of any Data Scientist. Go to the end of this article if you want to download the data for yourself and follow along!" }, { "code": null, "e": 669, "s": 522, "text": "Edit: I’ve made a “sequel” to this article about visualizing and plotting the model we find if you want to check that out after reading this one!:" }, { "code": null, "e": 680, "s": 669, "text": "medium.com" }, { "code": null, "e": 759, "s": 680, "text": "Make sure to follow my profile if you enjoy this article and want to see more!" }, { "code": null, "e": 819, "s": 759, "text": "This is the skeleton I use for creating a simple LM or GLM:" }, { "code": null, "e": 1187, "s": 819, "text": "Create a base-model using all available variables and dataFactorize categorical variables if R didn’t do the jobAdd relevant power-transformationsAdd relevant variable interactionRemove insignificant variables with relevant testing criteria- Repeat step 3–5 until you’ve exhausted your optionsRemove any outlying datapointsEvaluate your modelVisualizing your findings" }, { "code": null, "e": 1246, "s": 1187, "text": "Create a base-model using all available variables and data" }, { "code": null, "e": 1301, "s": 1246, "text": "Factorize categorical variables if R didn’t do the job" }, { "code": null, "e": 1336, "s": 1301, "text": "Add relevant power-transformations" }, { "code": null, "e": 1370, "s": 1336, "text": "Add relevant variable interaction" }, { "code": null, "e": 1485, "s": 1370, "text": "Remove insignificant variables with relevant testing criteria- Repeat step 3–5 until you’ve exhausted your options" }, { "code": null, "e": 1516, "s": 1485, "text": "Remove any outlying datapoints" }, { "code": null, "e": 1536, "s": 1516, "text": "Evaluate your model" }, { "code": null, "e": 1562, "s": 1536, "text": "Visualizing your findings" }, { "code": null, "e": 1936, "s": 1562, "text": "Lets start by setting up a workspace and loading our data. In this example we’re working on a dataset describing employment-status of women based on whether or not you’re a foreigner, the amount of government-entitled support (log-transformed), age, years of education and the number of children (spread in two categorical variables ‘young.children’ and ‘school.children’):" }, { "code": null, "e": 2120, "s": 1936, "text": "rm(list=ls()) # “Clear current R environment”setwd(“C:/R/Workspace”) # Setting up your workspacedat <- read.table(“employment_data.txt”, header=T) # Load that datastr(dat)summary(dat)" }, { "code": null, "e": 2135, "s": 2120, "text": "which outputs:" }, { "code": null, "e": 2328, "s": 2135, "text": "The first thing we notice is that our response-variable is binomial (obviously) suggesting that we have a binomial distribution which means we’ll have to fit a GLM instead of a traditional LM:" }, { "code": null, "e": 2409, "s": 2328, "text": "fit.1 <- glm(employed == \"yes\" ~ ., data = dat, family = binomial)summary(fit.1)" }, { "code": null, "e": 2655, "s": 2409, "text": "This fit is the most general fit we can use by default, it fits a binomial model (family = binomial) with respect to the response-variable “employed” having a value “yes”, using every variable in the dataset (~ .) giving us the following output:" }, { "code": null, "e": 2869, "s": 2655, "text": "Right, so a few problems right off the bat, we don’t like seeing p-values above 0.05, much less above 0.1, but before we recklessly remove them lets check for variable interactions and power-transformations first!" }, { "code": null, "e": 3258, "s": 2869, "text": "Lets consider the possibility that there’s a categorical difference between not having any children and actually having any number of children larger than zero, thus we add the categorical variables for having 0 children: ‘factor(young.children == 0)’, ‘factor(school.children == 0)’ and a combined factor for not having any children at all ‘factor(young.children + school.children == 0)’" }, { "code": null, "e": 3304, "s": 3258, "text": "We can update our fit with the new variables:" }, { "code": null, "e": 3547, "s": 3304, "text": "tempfit <- update(fit.1, .~. + factor(young.children == 0) + factor(school.children == 0) + factor(young.children + school.children == 0))summary(tempfit)" }, { "code": null, "e": 3719, "s": 3547, "text": "So we’ve already improved our model a bit in terms of AIC from 1066.8 to 1050.2! Lets take a look at our continuous variables and watch for possible power-transformations:" }, { "code": null, "e": 3832, "s": 3719, "text": "A neat way to look for potential power-transformations of a binomial distribution is using this custom function:" }, { "code": null, "e": 4660, "s": 3832, "text": "logit.plot <- function(x, y, h, link=’logit’, xlab=deparse(substitute(x)), yname=deparse(substitute(y)), ylab, rug=T, data, ...){ if(!missing(data)){ call <- match.call() dataPos <- match(“data”,names(call)) return(invisible(with(data, eval(call[-dataPos])))) } if (length(levels(factor(y)))!=2) stop(‘y must be binary’) succes <- levels(factor(y))[2] if (missing(ylab)) ylab <- paste(binomial(link)$link,’ P{‘,yname,’=’,succes,’|’,xlab,’}’, sep=’’, collapse=’’) if (is.factor(y)) y <- as.numeric(y==levels(y)[2]) x.seq <- seq(min(x),max(x),length=101) smooth <- binomial(link)$linkfun(ksmooth(x, y, ’normal’, h, x.points=x.seq)$y) plot(smooth~x.seq, ylab=ylab, xlab=xlab, type=’l’,...) if (rug) rug(x) invisible(xy.coords(x = x.seq, y = smooth, xlab = xlab, ylab = ylab))}" }, { "code": null, "e": 4801, "s": 4660, "text": "It’s actually decently simple, it plots the link(E[y|x]) against x with E[y|x] estimated using a Nadaraya-Watson kernel regression estimate:" }, { "code": null, "e": 5046, "s": 4801, "text": "This take the following arguments:x — Your explanatory variablesy — The binary outcome variableh — Bandwidth for the Nadaraya-Watson kernel regression estimatedata — Self explanatory... — Whatever additional arguments you want to pass to plot()" }, { "code": null, "e": 5138, "s": 5046, "text": "Using this function iterating over different bandwidths we get the following kinds of plot:" }, { "code": null, "e": 5273, "s": 5138, "text": "for(i in seq(2.5,10,length.out = 6)) logit.plot(x = age, y = employed == ‘yes’, h = i, data = dat, main = paste0(“bandwidth = “,i))" }, { "code": null, "e": 5585, "s": 5273, "text": "In this example with ‘age’ we can see that the function begins smoothing around a bandwidth around 7, the graph could approximate a 2. or maybe 3. degree polynomial, the same is true for ‘education’ and ‘gov.support’ but for simplicity we’ll consider the case of all three taking shape as 2. degree polynomials:" }, { "code": null, "e": 5741, "s": 5585, "text": "tempfit <- update(tempfit, .~. + I(age^2) + I(education^2) + I(gov.support^2))summary(tempfit)" }, { "code": null, "e": 5843, "s": 5741, "text": "Quite the improvement in terms of AIC, from 1050.2 to 1017.7! Lots of insignificant variables though!" }, { "code": null, "e": 5937, "s": 5843, "text": "This is our first attempt at a “full” model, so lets define this as our ‘fit.2’ and continue." }, { "code": null, "e": 5954, "s": 5937, "text": "fit.2 <- tempfit" }, { "code": null, "e": 6310, "s": 5954, "text": "The easiest way to check for variable interaction is using the R-function ‘add1’, this is simply the case of defining a scope to test and which test to use when testing relative to the original model. F-tests are usually only relevant for LM and AOV models so we can ‘safely’ ignore that testing criteria, we’ll instead be using a χ2-test (Chisq or Chi2):" }, { "code": null, "e": 6355, "s": 6310, "text": "add1(fit.2, scope = .~. + .^2, test=”Chisq”)" }, { "code": null, "e": 6667, "s": 6355, "text": "This scope is simply asking to test the current model (.~.) plus interaction between existing variables (+ .^2), this will output a lot of interactions, some with statistically significant P-values, but it can be annoying to manually sort through, so lets sort the list so we get the lowest P-values on the top:" }, { "code": null, "e": 6764, "s": 6667, "text": "add1.test <- add1(fit.2, scope = .~. + .^2, test=”Chisq”)add1.test[order(add1.test$’Pr(>Chi)’),]" }, { "code": null, "e": 7235, "s": 6764, "text": "Right, so it seems like there might be an interaction between the foreigner and age variables. One thing to consider before simply adding the interaction with the lowest P-value is whether or not this makes sense in context of our current model, right now age2 is actually the most significant variable in our model so we might argue that adding the interaction between foreigner and age2 is more intuitive, for simplicity we’ll stick with the foreigner:age interaction." }, { "code": null, "e": 7320, "s": 7235, "text": "Lets test for more interactions after adding the variable interaction foreigner:age:" }, { "code": null, "e": 7446, "s": 7320, "text": "add1.test <- add1(update(fit.2, .~. + foreigner:age), scope = .~. + .^2, test=”Chisq”)add1.test[order(add1.test$’Pr(>Chi)’),]" }, { "code": null, "e": 7557, "s": 7446, "text": "Now it seems like there’s a significant interaction in foreigner:factor(young.children + school.children == 0)" }, { "code": null, "e": 7837, "s": 7557, "text": "After a few rounds of this we end up seeing no new statistically significant interactions, by the end we’ve added the following interactions: + foreigner:age + foreigner:factor(young.children + school.children == 0) + age:school.children + gov.support:factor(young.children == 0)" }, { "code": null, "e": 7907, "s": 7837, "text": "So lets update our fit with the new variable interactions as follows:" }, { "code": null, "e": 8087, "s": 7907, "text": "fit.3 <- update(fit.2, .~. + foreigner:age + foreigner:factor(young.children + school.children == 0) + age:school.children + gov.support:factor(young.children == 0))summary(fit.3)" }, { "code": null, "e": 8148, "s": 8087, "text": "A small improvement in AIC once more, from 1017.7 to 1006.9." }, { "code": null, "e": 8428, "s": 8148, "text": "This process is quite similar to the last one in step 4. We’ll simply be using the drop1 function in R now instead of add1, and due to us seeking to remove instead of appending variables we seek the highest P-value instead of the lowest (we’ll still use χ2-test as our criteria):" }, { "code": null, "e": 8515, "s": 8428, "text": "drop1.test <- drop1(fit.3, test=”Chisq”)drop1.test[rev(order(drop1.test$’Pr(>Chi)’)),]" }, { "code": null, "e": 8784, "s": 8515, "text": "This tells us mostly the same as our model-summary, gov.support2 definitely dosn’t seem to be statistically significant, so we’ll remove that first and so on and so forth, we end up removing the following variables:- gov.support2- young.children- education- education2" }, { "code": null, "e": 8948, "s": 8784, "text": "After those have been removed we see that all the remaining variables are statistically significant, so lets update our fit by removing the variables listed above:" }, { "code": null, "e": 9055, "s": 8948, "text": "fit.4 <- update(fit.3, .~. — I(gov.support^2) — young.children — education — I(education^2))summary(fit.4)" }, { "code": null, "e": 9257, "s": 9055, "text": "Nice, another improvement in AIC although marginal and insignificant, the main advantage of this model over our previous is the added simplicity inherent in the reduced number of explanatory variables!" }, { "code": null, "e": 9604, "s": 9257, "text": "One might wonder “Why aren’t we removing the gov.support variable? It’s clearly insignificant when looking at the summary of our model!” this is due to the principle of marginality which prohibits us from removing an insignificant variable if said variable has a significant interaction with another, like gov.support:factor(young.children == 0)." }, { "code": null, "e": 10177, "s": 9604, "text": "You might argue that removing gov.support would be beneficial to the simplicity of the model given that it’s clearly insignificant and that the interaction with the young.children == 0 variable is only marginally significant (p = 0.435), however upon further inspection when removing gov.support from the model the variable-interaction splits into two variables for TRUE and FALSE, thus not giving us any added simplicity, the AIC, all other coefficients as well as the null- and residual deviance stays the exact same and by that account I close to leave it in the model." }, { "code": null, "e": 10377, "s": 10177, "text": "Doing an add1 and a drop1 test on our new and improved model shows us there’re no new interactions that are significant and that all current variables are significant so we’re done! The final fit is:" }, { "code": null, "e": 10739, "s": 10377, "text": "glm(employed == “yes” ~ foreigner + gov.support + age + school.children + factor(young.children == 0) + factor(school.children == 0) + factor(young.children + school.children == 0) + I(age^2) + foreigner:age + foreigner:factor(young.children + school.children == 0) + age:school.children + gov.support:factor(young.children == 0), family = binomial, data = dat)" }, { "code": null, "e": 10847, "s": 10739, "text": "So now that we have a model we’re satisfied with we can look for outliers that negatively effect the model." }, { "code": null, "e": 11016, "s": 10847, "text": "Using the “car” package https://www.rdocumentation.org/packages/car/versions/1.0-2 we can use the influencePlot() and outlierTest() functions to find potential outlier:" }, { "code": null, "e": 11181, "s": 11016, "text": "We see that the datapoint 416 is classified as an outlier in both tests, we can take a look at the point in a few of our plots to gauge whether or not to remove it:" }, { "code": null, "e": 11305, "s": 11181, "text": "par(mfrow = c(2, 2)) # 2 row(s), 2 column(s)plot(fit.4, col=ifelse(as.integer(rownames(dat))==416, “red”, “black”), pch=20)" }, { "code": null, "e": 11608, "s": 11305, "text": "It seems like this could very well be screwing a bit with our model, note that we should actually be using pearson residuals to gauge our models fit so the fact that we don’t have anything close to a straight line in the upper left plot is fine, Q-Q plots are irrelevant for this kind of model as well." }, { "code": null, "e": 11668, "s": 11608, "text": "Lets try removing the point and take a look at the new fit:" }, { "code": null, "e": 11735, "s": 11668, "text": "final.fit <- update(fit.4, data = dat[-c(416),])summary(final.fit)" }, { "code": null, "e": 12131, "s": 11735, "text": "Down to almost 1000 AIC from the original 1067, this isn’t really a relevant measure of performance when comparing the AIC of two different sets of data (since we removed point 416), we would actually have to conclude that 416 was an outlier in the initial model as well, remove it and then compare the AIC value of the initial model without point 416 to our final fit without point 416 as well." }, { "code": null, "e": 12384, "s": 12131, "text": "Looking at another round of influencePlot() and outlierTest() we find that datapoint 329 is acting out as well, however looking at the actual plots we see that we can’t really justify a removal of the data like we could with 416. This is our final fit." }, { "code": null, "e": 12676, "s": 12384, "text": "So now that we have a final fit where we can’t confidently add or remove any interactions variables and other transformations it’s time to evaluate if our model actually fits our data and if there’s even a statistically significant difference between our final fit and the first “naive” fit." }, { "code": null, "e": 12752, "s": 12676, "text": "Lets start by taking a look at our fitted values vs. the Pearson residuals:" }, { "code": null, "e": 12914, "s": 12752, "text": "par(mfrow = c(1, 1)) # 2 row(s), 2 column(s)plot(p.resid ~ fit.val)lines(ksmooth(y = p.resid, x = fit.val, bandwidth=.1, kernel=’normal’), col=’blue’)abline(h=0)" }, { "code": null, "e": 13016, "s": 12914, "text": "This is a pretty decent fit, lets take a look at the fit for the major explanatory variables as well:" }, { "code": null, "e": 13267, "s": 13016, "text": "With the exception of ‘gov.support’ everything looks quite nice, also the reason for the bend in ‘gov.support’ seems to be a single outlier in which someone was granted a substantially lower amount of support compared to all our other points of data." }, { "code": null, "e": 13560, "s": 13267, "text": "Overfitting is the bane of all statistical modelling, how can you make sure your model isn’t just fitting to the exact data you fed it? The goal is to make a model which generalizes and doesn’t just cater to the current data at hand. So how do we test if our model is overfitting on our data?" }, { "code": null, "e": 13757, "s": 13560, "text": "A popular metric to test is the delta value generated through Cross-Validation, we can calculated these by using the cv.glm function from the ‘boot’ package and compare our final fit to our first!" }, { "code": null, "e": 13876, "s": 13757, "text": "cv.glm(dat[-c(416),], final.fit, K = 13)$deltacv.glm(dat[-c(416),], update(fit.1, data = dat[-c(416),]), K = 13)$delta" }, { "code": null, "e": 14083, "s": 13876, "text": "In the code above we’re using k-fold cross-validation with k = 13 (since 13 is a factor of 871 which is the length of our data after removing the outlier) this means we’re splitting our data in 13 ‘chunks’." }, { "code": null, "e": 14378, "s": 14083, "text": "The delta values is a vector wherein the first component is the raw cross-validation estimate of prediction error and the second component is the adjusted cross-validation estimate (designed to compensate for the bias introduced by not using an exhaustive testing methods such as leave-one-out)" }, { "code": null, "e": 14532, "s": 14378, "text": "Running the code above yields the following delta-values, note that these are subject to some random variance so you might not get the exact same values:" }, { "code": null, "e": 14693, "s": 14532, "text": "The prediction error is lower for the final fit, even when testing with cross-validation. Thus we can assume that our model hasn’t been overfitting on our data!" }, { "code": null, "e": 14999, "s": 14693, "text": "So now we’ve concluded that our model is actually a pretty decent fit for our data, but is it a statistically significant difference from the “naive” model without any transformations and variable interactions? We can use an ANOVA test for this, we just have to remove the same point of data in both fits:" }, { "code": null, "e": 15122, "s": 14999, "text": "There’s definitely a significant difference between the two fits, we can happily conclude that our hard work has paid off!" }, { "code": null, "e": 15256, "s": 15122, "text": "Now that we’ve gotten ourselves a model, how do we actually visualize and interpret what it says about the relationships in our data?" }, { "code": null, "e": 15350, "s": 15256, "text": "Take a look at the following walk-trough which uses the same data and model as this article!:" }, { "code": null, "e": 15361, "s": 15350, "text": "medium.com" }, { "code": null, "e": 15685, "s": 15361, "text": "Please keep in mind that this is purely introductory and that this isn’t an exhaustive analysis or conclusion! If we were more rigorous in our pursuit we would’ve incorporated Cross-Validation tests and ANOVA tests on each new iteration of our model, ie. whenever we add a new variable, interaction or power-transformation." }, { "code": null, "e": 15990, "s": 15685, "text": "Feel free to message me if you have any questions and please correct me if you feel like I missed something or did something wrong, do keep in mind that this is suppose to serve as an introduction to modelling in R, I’m well aware that this process is highly simplified compared to more advanced methods!" }, { "code": null, "e": 16129, "s": 15990, "text": "If you want to try your luck with this same dataset give it a go here: https://github.com/pela15ae/statmod/blob/master/employment_data.txt" }, { "code": null, "e": 16232, "s": 16129, "text": "The data is Danish so to convert the headers and categorical values to English run this piece of code:" }, { "code": null, "e": 16473, "s": 16232, "text": "names(dat) <- c(“employed”, “foreigner”, “gov.support”, “age”, “education”, “young.children”, “school.children”)levels(dat$employed)[1] <- “yes”levels(dat$employed)[2] <- “no”levels(dat$foreigner)[1] <- “yes”levels(dat$foreigner)[2] <- “no”" } ]
How to use Pandas to analyze numeric data? | by WY Fok | Towards Data Science
Python already becomes a popular programming language in the data science area. Pandas, one of many popular libraries in data science, provides lots of great functions that help us transform, analyze and interpret data. I am sure that there are already too many tutorials and materials to teach you how to use Pandas. However, in this article, I am not solely teaching you how to use Pandas. Instead, I would like to use an example to demonstrate how to interpret your data correctly and smoothly, with the help of Pandas. Panda VS Pandas Prepare a python environmentDownload dataset from KaggleImport pandas Prepare a python environment Download dataset from Kaggle Import pandas Prepare a python environment Prepare a python environment Since we use Python to analyze data, of course first we need to install Python. For a beginner, I strongly recommend you to install Anaconda, since Anaconda will already pre-install a list of libraries that are very useful for data science. And you don’t need to concern about compiler or IDE. Here is the link for downloading Anaconda Distribution which is free Go to download Jupyter Notebook is a great tool to do data analysis as you can see the result part by part so that you can know if the result is what you predict and you can also know if you make any error immediately. After launching Jupyter Notebook, a webpage will pop out and you will see a page like this. You can select and create a path for storing your files. On the right side, there is a “New” button. Click this to create a folder or Python file. There are too many useful functions and shortcuts provided by Jupyter Notebook. I am not here to describe and explain in detail. Also, I hope you already have some basic knowledge of coding Python since this is not an introduction to Python. Either way, if you have any questions feel free to comment and I will resolve your problem. 2. Download dataset from Kaggle The dataset that will be used in this article is from Kaggle. The dataset includes suicide rates from 1985 to 2016 across different countries with their socio-economic information. Download link 3. Import pandas Last preparation, import pandas Normally we will give an abbreviation for each library. You can skip this but then each time when you want to use any function you have to type in the whole name. So why not give it a short abbreviation. Although this article focuses on using pandas, we still need some helps from numpy so we will also import numpy. The first step is to import the dataset that we download from Kaggle. Although you can import the data from any path, my suggestion is that put all data and codes together so that you don’t need to type the exact path but just the file name. The file name downloaded is “master.csv”. So we know the dataset is in a csv file type. Other common file types include excel file and json. The first pandas function we use by pandas is read_csv. A dataframe called data is created by: data= pd.read_csv('master.csv') We can use this to import a csv file to python and store it as a dataframe. Dataframe is like an excel table. Normally pandas automatically interprets the dataset and identifies all necessary parameters in order to import the dataset properly. However, if you find out the output is not as expected as you desire, you can manually change parameters. Below are some common parameters which you can modify whey you use read_csv : sep: Delimiter used to separate values across variables. Default is using comma ‘,’ . You can change the sep similar to below sep: Delimiter used to separate values across variables. Default is using comma ‘,’ . You can change the sep similar to below data = pd.read_csv('master.csv', sep = ';') 2. header: Normally a csv file has the first row showing the names of all variables. However, if there is no such name row in the csv file, it is better to tell pandas that there is no header by header = None Now you already import the dataset. As said before, you can see the result directly after running your code. So let’s see the dataset data I hope you will get the same result as mine. Now as you scrolling down, you can see a number but not all records. If you don’s want to show so many records, you can show some top or bottom records by typing data.head(5) # showing top 5 records from the dataframe# ordata.tail(5) # showing bottom 5 records from the dataframe Knowing the dataset is necessary before carrying any analysis as first this will give you a brief understanding and second this will prevent you from misinterpreting when you analyze. The first question you may ask after importing is how many numbers of records in the dataset. Luckily you can get the answer with a line of code. data.shape The first number (index 0, python starts from zero) shows the numbers of row s and the second number (index 1) shows the numbers of columns. So the dataset has 27,820 rows and 12 columns. The second you may ask is what these 12 columns are. There are plenty of methods to shows column names. But my favorite is to use data.info() info() doesn’t only provide you with all column names in the dataframe but it also provides you with the type of data stored in this dataframe. Also, you can know if there is a missing value in the dataframe. As shown above, the number column shows how many non-null counts in that variable. All show 27,820 except HDI for the year. So at least we know there are missing values in the dataset that we import. Now you want to know what data is inside this dataframe. For example, how many countries are there in those almost 28k records? You want to get a list of all countries. You can get values of each column by data['country'] But this will return you all values without deduplication. If you want to get a unique country, my favorite method is to use set function. Set function will only return a list of unique values without duplication. So how many countries in total? There are in total of 101 countries. Then you want to know the number of suicides for each year. In Excel, you can perform this by pivot table. There is also a similar function for pandas called pivot_table. Imagine you are now using an excel pivot table to get the number of suicides. You will drag year to row label and drag suicide_no to Values If you are familiar with the excel pivot table, then remember the same format as pandas pivot_table. data.pivot_table(index='year',values='suicides_no',aggfunc='sum') Oh, you want to break down into sex also? data.pivot_table(index='year',columns='sex',values='suicides_no',aggfunc='max') Here ‘index’ represents the variable to be placed in row label; ‘columns’ represents columns; ‘values’ represents the number in the pivot table. Just like excel, you can calculate sum, mean, max or min. data.pivot_table(index='year',columns='sex',values='suicides_no',aggfunc=['sum','mean','max','min']) You can also perform multi-index on row or column. data.pivot_table(index=['country','year'],columns='sex',values='suicides_no',aggfunc=['sum']) By using a pivot table, we can know a general breakdown of the dataset in terms of different variables. You can also spot any abnormalities in the dataset which may help you further analysis. Just like below: data.pivot_table(index=['year'],columns='sex',values='suicides_no',aggfunc=['sum']) What happened in 2016? Why was there a sudden drop? Now you want to check the dataset and see what happens for 2016. In pandas, you need to specify which row and column you want to return. This can be done by providing index numbers or names or criteria. Now the criteria is that year has to be 2016. You can get the result by data[data['year']==2016] How to interpret this line of code? There are two parts. The inner part “ data[‘year’]==2016 ” is a condition that needs to fulfill. Here means the year column in the data must be 2016. Be cautious that there are two equal signs, representing a comparison. Similarly, you can have a condition with larger, smaller, or not equal data['year'] >= 2016 # larger than or equal to data['year']!=2016 # not equal to More conditions, no problem. But make sure that you specify clearly if you want to fulfill all or either one condition. # year must be larger than 2010 and smaller than 2015(data['year'] > 2010) & (data['year']<2015)# year can be larger than 2010 or smaller than 2000(data['year'] > 2010) | (data['year']<2000) The outer part “ data[...] ” means to return all rows that fulfill the criteria in the inner part. Back to the example, we want to return all rows with year equal to 2016. Seems no problem. But if we count the number of countries in 2016 and 2015, the problem arises. Now we want to get the column country from the dataset which the year must be 2016. The easy way is to extend the previous line of code with data[data['year']==2016]['country'] And then use set and len functions again to calculate the number of countries in 2016. len(set(data[data['year']==2016]['country'])) Do the same thing for 2015. Here we come The data in 2016 is clearly incomplete and so we should not compare 2016 with other years. So we should better remove all records for 2016. As said, we can apply a condition to filter records from 2016 as below: data2= data[data['year']!=2016] Now we create another dataframe called ‘data2’ for further analysis. Finding which variables are related to the dataset is crucial as this can help you discover which variables can cause the change of the results. For example, in the dataset there are some categorical variables: country, year, sex, and generation Pick a simple one, sex, as for example. You can make a comparison of the number of total suicides for each sex. If there is a large difference, it is safe that sex is a factor causing the difference in term of suicide Of course, we can use pivot_table function to do so. But I am here to introduce another function, groupby. If you have experience in using SQL, I am sure you are familiar with the group by. data2.groupby('sex').agg({'suicides_no':'sum'}) In term of SQL, the above statement is equivalent to: select sex, sum(suicides_no) from data2 group by sex Python will first group all records based on the values in ‘sex’ columns. After that, python will calculate the total number of suicides for each group of ‘sex’. Male suicides are much higher than female suicides. At this moment, we can quite sure that sex is a factor affecting the number of suicides. Brillant thing about groupby is that you can again split the dataset into more levels. Remember when you include more than one level, you need to use a square bracket [ ] to provide a list to pandas. data2.groupby(['sex','generation']).agg({'suicides_no':'sum'}) Also, just like SQL, you can perform multiple aggregations here in groupby function. data2.groupby(['sex']).agg({'suicides_no':['sum','max']}) or data2.groupby(['sex']).agg({'suicides_no':'sum', 'population':'mean'}) Now we know sex is a factor. Then how about age? data2.groupby(['age']).agg({'suicides_no':'sum'}) So the most popular age range for suicide is 35–54. Right? Not quite. Not like sex which is around half-half, the population for each age group is not even. This is a common misinterpretation when compare with different categories when they have different sizes of population or base. As a result, in order to have a better comparison, we should better compare suicide numbers with each total population. To do this in pandas, first create another dataframe to store suicide_no and population at each age level. Then calculate a division to get the average number of suicide for each age group. # create a dataframe called data_age for age groupby data_age = data2.groupby([‘age’]).agg({‘suicides_no’:’sum’,’population’:’sum’})# calculate average of suicide number for each age group data_age[‘suicides_no’]/data_age[‘population’] The first part of the code is similar as before. The second part is to perform a division. The good thing for python is that you can perform a calculation as a whole column instead of each by each cell like excel. So we divide the suicide_no column from population column. Now the result is different. The suicidal situation gets worse as the age increases. At this moment, you may say the ranking is not clear and you want to order the result in terms of the average suicide number. Then it is time to introduce sort_values function. (data_age['suicides_no']/data_age['population']).sort_values() Here because there is only one column, we do not need to specify which column to sort by. However, you have to specify which column if there is more than one column in the dataframe. Also, the default order is ascending and you can change it by adding ascending = False inside the bracket. Just like below: (data_age['suicides_no']/data_age['population']).sort_values(ascending=False) Now you can easily see the increasing trend by age. We have already studied the impacts of sex and age. Now we move on to the country. We can find which country is more popular with suicide. The first step is to create a table including numbers of suicides and population by country level. This can be done by using groupby function. data_country = data2.groupby(['country']).agg({'suicides_no':'sum','population':'sum'}) Here we don’t care if all countries have the same number of records as we are calculating the average number over the period. Then we calculate the average suicide by dividing suicides_no from population. data_country['average_suicide'] = data_country['suicides_no']/data_country['population'] Here we create a new column called ‘average_suicide’ which will store the division result. Later use sort_values function to get the results in descending order. Instead of showing all countries, we can just show top N countries by using the head function data_country.sort_values(by='average_suicide',ascending=False).head(10) From the result, we can see most countries are in Eastern Europe. Then you can say the geolocation is also an indicator of affecting suicide. That’s all for today. I hope you will not only learn how to use Python but also how to handle your dataset to draw better and more accurate conclusions. Welcome to give comment so I know how to improve and write a better blog. If you like, give a clap and share it to people who are also in need like you. See you next time.
[ { "code": null, "e": 695, "s": 172, "text": "Python already becomes a popular programming language in the data science area. Pandas, one of many popular libraries in data science, provides lots of great functions that help us transform, analyze and interpret data. I am sure that there are already too many tutorials and materials to teach you how to use Pandas. However, in this article, I am not solely teaching you how to use Pandas. Instead, I would like to use an example to demonstrate how to interpret your data correctly and smoothly, with the help of Pandas." }, { "code": null, "e": 711, "s": 695, "text": "Panda VS Pandas" }, { "code": null, "e": 781, "s": 711, "text": "Prepare a python environmentDownload dataset from KaggleImport pandas" }, { "code": null, "e": 810, "s": 781, "text": "Prepare a python environment" }, { "code": null, "e": 839, "s": 810, "text": "Download dataset from Kaggle" }, { "code": null, "e": 853, "s": 839, "text": "Import pandas" }, { "code": null, "e": 882, "s": 853, "text": "Prepare a python environment" }, { "code": null, "e": 911, "s": 882, "text": "Prepare a python environment" }, { "code": null, "e": 1205, "s": 911, "text": "Since we use Python to analyze data, of course first we need to install Python. For a beginner, I strongly recommend you to install Anaconda, since Anaconda will already pre-install a list of libraries that are very useful for data science. And you don’t need to concern about compiler or IDE." }, { "code": null, "e": 1274, "s": 1205, "text": "Here is the link for downloading Anaconda Distribution which is free" }, { "code": null, "e": 1289, "s": 1274, "text": "Go to download" }, { "code": null, "e": 1493, "s": 1289, "text": "Jupyter Notebook is a great tool to do data analysis as you can see the result part by part so that you can know if the result is what you predict and you can also know if you make any error immediately." }, { "code": null, "e": 1732, "s": 1493, "text": "After launching Jupyter Notebook, a webpage will pop out and you will see a page like this. You can select and create a path for storing your files. On the right side, there is a “New” button. Click this to create a folder or Python file." }, { "code": null, "e": 2066, "s": 1732, "text": "There are too many useful functions and shortcuts provided by Jupyter Notebook. I am not here to describe and explain in detail. Also, I hope you already have some basic knowledge of coding Python since this is not an introduction to Python. Either way, if you have any questions feel free to comment and I will resolve your problem." }, { "code": null, "e": 2098, "s": 2066, "text": "2. Download dataset from Kaggle" }, { "code": null, "e": 2279, "s": 2098, "text": "The dataset that will be used in this article is from Kaggle. The dataset includes suicide rates from 1985 to 2016 across different countries with their socio-economic information." }, { "code": null, "e": 2293, "s": 2279, "text": "Download link" }, { "code": null, "e": 2310, "s": 2293, "text": "3. Import pandas" }, { "code": null, "e": 2342, "s": 2310, "text": "Last preparation, import pandas" }, { "code": null, "e": 2546, "s": 2342, "text": "Normally we will give an abbreviation for each library. You can skip this but then each time when you want to use any function you have to type in the whole name. So why not give it a short abbreviation." }, { "code": null, "e": 2659, "s": 2546, "text": "Although this article focuses on using pandas, we still need some helps from numpy so we will also import numpy." }, { "code": null, "e": 3042, "s": 2659, "text": "The first step is to import the dataset that we download from Kaggle. Although you can import the data from any path, my suggestion is that put all data and codes together so that you don’t need to type the exact path but just the file name. The file name downloaded is “master.csv”. So we know the dataset is in a csv file type. Other common file types include excel file and json." }, { "code": null, "e": 3137, "s": 3042, "text": "The first pandas function we use by pandas is read_csv. A dataframe called data is created by:" }, { "code": null, "e": 3169, "s": 3137, "text": "data= pd.read_csv('master.csv')" }, { "code": null, "e": 3279, "s": 3169, "text": "We can use this to import a csv file to python and store it as a dataframe. Dataframe is like an excel table." }, { "code": null, "e": 3597, "s": 3279, "text": "Normally pandas automatically interprets the dataset and identifies all necessary parameters in order to import the dataset properly. However, if you find out the output is not as expected as you desire, you can manually change parameters. Below are some common parameters which you can modify whey you use read_csv :" }, { "code": null, "e": 3723, "s": 3597, "text": "sep: Delimiter used to separate values across variables. Default is using comma ‘,’ . You can change the sep similar to below" }, { "code": null, "e": 3849, "s": 3723, "text": "sep: Delimiter used to separate values across variables. Default is using comma ‘,’ . You can change the sep similar to below" }, { "code": null, "e": 3893, "s": 3849, "text": "data = pd.read_csv('master.csv', sep = ';')" }, { "code": null, "e": 4088, "s": 3893, "text": "2. header: Normally a csv file has the first row showing the names of all variables. However, if there is no such name row in the csv file, it is better to tell pandas that there is no header by" }, { "code": null, "e": 4102, "s": 4088, "text": "header = None" }, { "code": null, "e": 4236, "s": 4102, "text": "Now you already import the dataset. As said before, you can see the result directly after running your code. So let’s see the dataset" }, { "code": null, "e": 4241, "s": 4236, "text": "data" }, { "code": null, "e": 4448, "s": 4241, "text": "I hope you will get the same result as mine. Now as you scrolling down, you can see a number but not all records. If you don’s want to show so many records, you can show some top or bottom records by typing" }, { "code": null, "e": 4566, "s": 4448, "text": "data.head(5) # showing top 5 records from the dataframe# ordata.tail(5) # showing bottom 5 records from the dataframe" }, { "code": null, "e": 4750, "s": 4566, "text": "Knowing the dataset is necessary before carrying any analysis as first this will give you a brief understanding and second this will prevent you from misinterpreting when you analyze." }, { "code": null, "e": 4896, "s": 4750, "text": "The first question you may ask after importing is how many numbers of records in the dataset. Luckily you can get the answer with a line of code." }, { "code": null, "e": 4907, "s": 4896, "text": "data.shape" }, { "code": null, "e": 5095, "s": 4907, "text": "The first number (index 0, python starts from zero) shows the numbers of row s and the second number (index 1) shows the numbers of columns. So the dataset has 27,820 rows and 12 columns." }, { "code": null, "e": 5225, "s": 5095, "text": "The second you may ask is what these 12 columns are. There are plenty of methods to shows column names. But my favorite is to use" }, { "code": null, "e": 5237, "s": 5225, "text": "data.info()" }, { "code": null, "e": 5646, "s": 5237, "text": "info() doesn’t only provide you with all column names in the dataframe but it also provides you with the type of data stored in this dataframe. Also, you can know if there is a missing value in the dataframe. As shown above, the number column shows how many non-null counts in that variable. All show 27,820 except HDI for the year. So at least we know there are missing values in the dataset that we import." }, { "code": null, "e": 5852, "s": 5646, "text": "Now you want to know what data is inside this dataframe. For example, how many countries are there in those almost 28k records? You want to get a list of all countries. You can get values of each column by" }, { "code": null, "e": 5868, "s": 5852, "text": "data['country']" }, { "code": null, "e": 6082, "s": 5868, "text": "But this will return you all values without deduplication. If you want to get a unique country, my favorite method is to use set function. Set function will only return a list of unique values without duplication." }, { "code": null, "e": 6114, "s": 6082, "text": "So how many countries in total?" }, { "code": null, "e": 6151, "s": 6114, "text": "There are in total of 101 countries." }, { "code": null, "e": 6462, "s": 6151, "text": "Then you want to know the number of suicides for each year. In Excel, you can perform this by pivot table. There is also a similar function for pandas called pivot_table. Imagine you are now using an excel pivot table to get the number of suicides. You will drag year to row label and drag suicide_no to Values" }, { "code": null, "e": 6563, "s": 6462, "text": "If you are familiar with the excel pivot table, then remember the same format as pandas pivot_table." }, { "code": null, "e": 6629, "s": 6563, "text": "data.pivot_table(index='year',values='suicides_no',aggfunc='sum')" }, { "code": null, "e": 6671, "s": 6629, "text": "Oh, you want to break down into sex also?" }, { "code": null, "e": 6751, "s": 6671, "text": "data.pivot_table(index='year',columns='sex',values='suicides_no',aggfunc='max')" }, { "code": null, "e": 6954, "s": 6751, "text": "Here ‘index’ represents the variable to be placed in row label; ‘columns’ represents columns; ‘values’ represents the number in the pivot table. Just like excel, you can calculate sum, mean, max or min." }, { "code": null, "e": 7055, "s": 6954, "text": "data.pivot_table(index='year',columns='sex',values='suicides_no',aggfunc=['sum','mean','max','min'])" }, { "code": null, "e": 7106, "s": 7055, "text": "You can also perform multi-index on row or column." }, { "code": null, "e": 7200, "s": 7106, "text": "data.pivot_table(index=['country','year'],columns='sex',values='suicides_no',aggfunc=['sum'])" }, { "code": null, "e": 7409, "s": 7200, "text": "By using a pivot table, we can know a general breakdown of the dataset in terms of different variables. You can also spot any abnormalities in the dataset which may help you further analysis. Just like below:" }, { "code": null, "e": 7493, "s": 7409, "text": "data.pivot_table(index=['year'],columns='sex',values='suicides_no',aggfunc=['sum'])" }, { "code": null, "e": 7545, "s": 7493, "text": "What happened in 2016? Why was there a sudden drop?" }, { "code": null, "e": 7820, "s": 7545, "text": "Now you want to check the dataset and see what happens for 2016. In pandas, you need to specify which row and column you want to return. This can be done by providing index numbers or names or criteria. Now the criteria is that year has to be 2016. You can get the result by" }, { "code": null, "e": 7845, "s": 7820, "text": "data[data['year']==2016]" }, { "code": null, "e": 7881, "s": 7845, "text": "How to interpret this line of code?" }, { "code": null, "e": 8173, "s": 7881, "text": "There are two parts. The inner part “ data[‘year’]==2016 ” is a condition that needs to fulfill. Here means the year column in the data must be 2016. Be cautious that there are two equal signs, representing a comparison. Similarly, you can have a condition with larger, smaller, or not equal" }, { "code": null, "e": 8254, "s": 8173, "text": "data['year'] >= 2016 # larger than or equal to data['year']!=2016 # not equal to" }, { "code": null, "e": 8374, "s": 8254, "text": "More conditions, no problem. But make sure that you specify clearly if you want to fulfill all or either one condition." }, { "code": null, "e": 8565, "s": 8374, "text": "# year must be larger than 2010 and smaller than 2015(data['year'] > 2010) & (data['year']<2015)# year can be larger than 2010 or smaller than 2000(data['year'] > 2010) | (data['year']<2000)" }, { "code": null, "e": 8737, "s": 8565, "text": "The outer part “ data[...] ” means to return all rows that fulfill the criteria in the inner part. Back to the example, we want to return all rows with year equal to 2016." }, { "code": null, "e": 8833, "s": 8737, "text": "Seems no problem. But if we count the number of countries in 2016 and 2015, the problem arises." }, { "code": null, "e": 8974, "s": 8833, "text": "Now we want to get the column country from the dataset which the year must be 2016. The easy way is to extend the previous line of code with" }, { "code": null, "e": 9010, "s": 8974, "text": "data[data['year']==2016]['country']" }, { "code": null, "e": 9097, "s": 9010, "text": "And then use set and len functions again to calculate the number of countries in 2016." }, { "code": null, "e": 9143, "s": 9097, "text": "len(set(data[data['year']==2016]['country']))" }, { "code": null, "e": 9184, "s": 9143, "text": "Do the same thing for 2015. Here we come" }, { "code": null, "e": 9324, "s": 9184, "text": "The data in 2016 is clearly incomplete and so we should not compare 2016 with other years. So we should better remove all records for 2016." }, { "code": null, "e": 9396, "s": 9324, "text": "As said, we can apply a condition to filter records from 2016 as below:" }, { "code": null, "e": 9428, "s": 9396, "text": "data2= data[data['year']!=2016]" }, { "code": null, "e": 9497, "s": 9428, "text": "Now we create another dataframe called ‘data2’ for further analysis." }, { "code": null, "e": 9708, "s": 9497, "text": "Finding which variables are related to the dataset is crucial as this can help you discover which variables can cause the change of the results. For example, in the dataset there are some categorical variables:" }, { "code": null, "e": 9743, "s": 9708, "text": "country, year, sex, and generation" }, { "code": null, "e": 9961, "s": 9743, "text": "Pick a simple one, sex, as for example. You can make a comparison of the number of total suicides for each sex. If there is a large difference, it is safe that sex is a factor causing the difference in term of suicide" }, { "code": null, "e": 10151, "s": 9961, "text": "Of course, we can use pivot_table function to do so. But I am here to introduce another function, groupby. If you have experience in using SQL, I am sure you are familiar with the group by." }, { "code": null, "e": 10199, "s": 10151, "text": "data2.groupby('sex').agg({'suicides_no':'sum'})" }, { "code": null, "e": 10253, "s": 10199, "text": "In term of SQL, the above statement is equivalent to:" }, { "code": null, "e": 10306, "s": 10253, "text": "select sex, sum(suicides_no) from data2 group by sex" }, { "code": null, "e": 10468, "s": 10306, "text": "Python will first group all records based on the values in ‘sex’ columns. After that, python will calculate the total number of suicides for each group of ‘sex’." }, { "code": null, "e": 10609, "s": 10468, "text": "Male suicides are much higher than female suicides. At this moment, we can quite sure that sex is a factor affecting the number of suicides." }, { "code": null, "e": 10809, "s": 10609, "text": "Brillant thing about groupby is that you can again split the dataset into more levels. Remember when you include more than one level, you need to use a square bracket [ ] to provide a list to pandas." }, { "code": null, "e": 10872, "s": 10809, "text": "data2.groupby(['sex','generation']).agg({'suicides_no':'sum'})" }, { "code": null, "e": 10957, "s": 10872, "text": "Also, just like SQL, you can perform multiple aggregations here in groupby function." }, { "code": null, "e": 11015, "s": 10957, "text": "data2.groupby(['sex']).agg({'suicides_no':['sum','max']})" }, { "code": null, "e": 11018, "s": 11015, "text": "or" }, { "code": null, "e": 11089, "s": 11018, "text": "data2.groupby(['sex']).agg({'suicides_no':'sum', 'population':'mean'})" }, { "code": null, "e": 11138, "s": 11089, "text": "Now we know sex is a factor. Then how about age?" }, { "code": null, "e": 11188, "s": 11138, "text": "data2.groupby(['age']).agg({'suicides_no':'sum'})" }, { "code": null, "e": 11247, "s": 11188, "text": "So the most popular age range for suicide is 35–54. Right?" }, { "code": null, "e": 11473, "s": 11247, "text": "Not quite. Not like sex which is around half-half, the population for each age group is not even. This is a common misinterpretation when compare with different categories when they have different sizes of population or base." }, { "code": null, "e": 11783, "s": 11473, "text": "As a result, in order to have a better comparison, we should better compare suicide numbers with each total population. To do this in pandas, first create another dataframe to store suicide_no and population at each age level. Then calculate a division to get the average number of suicide for each age group." }, { "code": null, "e": 12019, "s": 11783, "text": "# create a dataframe called data_age for age groupby data_age = data2.groupby([‘age’]).agg({‘suicides_no’:’sum’,’population’:’sum’})# calculate average of suicide number for each age group data_age[‘suicides_no’]/data_age[‘population’]" }, { "code": null, "e": 12292, "s": 12019, "text": "The first part of the code is similar as before. The second part is to perform a division. The good thing for python is that you can perform a calculation as a whole column instead of each by each cell like excel. So we divide the suicide_no column from population column." }, { "code": null, "e": 12377, "s": 12292, "text": "Now the result is different. The suicidal situation gets worse as the age increases." }, { "code": null, "e": 12554, "s": 12377, "text": "At this moment, you may say the ranking is not clear and you want to order the result in terms of the average suicide number. Then it is time to introduce sort_values function." }, { "code": null, "e": 12617, "s": 12554, "text": "(data_age['suicides_no']/data_age['population']).sort_values()" }, { "code": null, "e": 12924, "s": 12617, "text": "Here because there is only one column, we do not need to specify which column to sort by. However, you have to specify which column if there is more than one column in the dataframe. Also, the default order is ascending and you can change it by adding ascending = False inside the bracket. Just like below:" }, { "code": null, "e": 13002, "s": 12924, "text": "(data_age['suicides_no']/data_age['population']).sort_values(ascending=False)" }, { "code": null, "e": 13054, "s": 13002, "text": "Now you can easily see the increasing trend by age." }, { "code": null, "e": 13193, "s": 13054, "text": "We have already studied the impacts of sex and age. Now we move on to the country. We can find which country is more popular with suicide." }, { "code": null, "e": 13336, "s": 13193, "text": "The first step is to create a table including numbers of suicides and population by country level. This can be done by using groupby function." }, { "code": null, "e": 13424, "s": 13336, "text": "data_country = data2.groupby(['country']).agg({'suicides_no':'sum','population':'sum'})" }, { "code": null, "e": 13550, "s": 13424, "text": "Here we don’t care if all countries have the same number of records as we are calculating the average number over the period." }, { "code": null, "e": 13629, "s": 13550, "text": "Then we calculate the average suicide by dividing suicides_no from population." }, { "code": null, "e": 13718, "s": 13629, "text": "data_country['average_suicide'] = data_country['suicides_no']/data_country['population']" }, { "code": null, "e": 13974, "s": 13718, "text": "Here we create a new column called ‘average_suicide’ which will store the division result. Later use sort_values function to get the results in descending order. Instead of showing all countries, we can just show top N countries by using the head function" }, { "code": null, "e": 14046, "s": 13974, "text": "data_country.sort_values(by='average_suicide',ascending=False).head(10)" }, { "code": null, "e": 14188, "s": 14046, "text": "From the result, we can see most countries are in Eastern Europe. Then you can say the geolocation is also an indicator of affecting suicide." }, { "code": null, "e": 14341, "s": 14188, "text": "That’s all for today. I hope you will not only learn how to use Python but also how to handle your dataset to draw better and more accurate conclusions." } ]
Creating an Interactive Data app using Plotly’s Dash | by Kyle | Towards Data Science
Let’s make an app to automatically plot data files. This is a walkthrough of creating a web app in python using plotly’s Dash, with an example we created at Kyso — the live version can be found here: dash-app-dx9g2r0la6-8000.cloud.kyso.io It’s an app for uploading any file with xy, xyyy, etc. coordinates and then automatically generating a plot. Dash is a Python framework for building web applications. It is built on top of Flask, Plotly.js, React and React Js., enabling you to build dashboards & applications using pure Python. In this tutorial, I will introduce you to the fundamentals and will assume that you have prior experience with Plotly. If you are new to plotly, check out these beginner guides: https://kyso.io/KyleOS/plotly-intro https://kyso.io/KyleOS/cufflinks-intro In order to start using Dash, you’ll need to install several packages. The core dash backend.Dash front-endDash HTML componentsDash core componentsPlotly The core dash backend. Dash front-end Dash HTML components Dash core components Plotly Note that all of these are already pre-installed on Kyso’s workspaces if you would like to launch your app from Kyso! pip install dash==0.21.1 pip install dash-renderer==0.13.0 pip install dash-html-components==0.11.0pip install dash-core-components==0.23.0 pip install plotly --upgrade Dash apps are composed of two parts. The first part is the “layout” of the app and it describes what the application looks like. Dash provides Python classes for all of the visual components of the application, i.e to generate HTML content with Python. To use these classes, let’s import the dash_core_components and the dash_html_components libraries. Create a file named app.py with the following code: import dashimport dash_core_components as dccimport dash_html_components as html Like with Flask we can initialize Dash by calling the Dash class of dash. Once that is done we can create the layout for our application, using the Div class from the dash_html_components to create HTML Divs. Note that dash_html_componentsincludes all HTML tags for you to style the layout of your app. In order to create a graph within our layout, we use the Graph class from dash_core_components. Graph renders interactive data visualizations using plotly.js. The Graph class expects a figure object with the data to be plotted and the layout details. Dash also allows you to do stylings such as changing the background color and text color. You can change the background by using the style attribute and passing an object with your specific color. external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']app = dash.Dash(__name__, external_stylesheets=external_stylesheets)colors = { "graphBackground": "#F5F5F5", "background": "#ffffff", "text": "#000000"}app.layout = html.Div([ dcc.Upload( id='upload-data', children=html.Div([ 'Drag and Drop or ', html.A('Select Files') ]), style={ 'width': '100%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px' }, # Allow multiple files to be uploaded multiple=True ), dcc.Graph(id='Mygraph'), html.Div(id='output-data-upload')]) Take note that we’re setting ids for each component we’re creating, we’ll go through these in just a sec. The Dash upload component allows your app’s viewers to upload files. The app can access the contents of an uploaded file by listening to the content’s property of the dcc.Upload component, which is a base64 encoded string that contains the file’s contents, regardless of file-type. So we’ve created the layout above; the upload box with some styling as well as the Graph that will be created when we drop in a file. Ok so now there are a few things we need to do, we need to create functions for: Reading in any file, whether it be csv, an excel file or tsv, and convert it into a Pandas DataFrame.Creating the graph when a new file is dropped.Printing the table of the data. Reading in any file, whether it be csv, an excel file or tsv, and convert it into a Pandas DataFrame. Creating the graph when a new file is dropped. Printing the table of the data. There are a few libraries we need for this: import base64import datetimeimport ioimport plotly.graph_objs as goimport cufflinks as cfimport pandas as pdimport dash_table So, to parse our targeted data file types: def parse_data(contents, filename): content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) try: if 'csv' in filename: # Assume that the user uploaded a CSV or TXT file df = pd.read_csv( io.StringIO(decoded.decode('utf-8'))) elif 'xls' in filename: # Assume that the user uploaded an excel file df = pd.read_excel(io.BytesIO(decoded)) elif 'txt' or 'tsv' in filename: # Assume that the user upl, delimiter = r'\s+'oaded an excel file df = pd.read_csv( io.StringIO(decoded.decode('utf-8')), delimiter = r'\s+') except Exception as e: print(e) return html.Div([ 'There was an error processing this file.' ]) return df Using cufflinks, a wrapper for easing plotting with pandas and plotly, to plot our scalar graphs: def update_graph(contents, filename): fig = { 'layout': go.Layout( plot_bgcolor=colors["graphBackground"], paper_bgcolor=colors["graphBackground"]) } if contents: contents = contents[0] filename = filename[0] df = parse_data(contents, filename) df = df.set_index(df.columns[0]) fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1) table = html.Div([ html.H5(filename), dash_table.DataTable( data=df.to_dict('rows'), columns=[{'name': i, 'id': i} for i in df.columns] ), html.Hr(), html.Div('Raw Content'), html.Pre(contents[0:200] + '...', style={ 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all' }) ]) And finally creating a table for each time a file is dropped in: def update_table(contents, filename): table = html.Div() if contents: contents = contents[0] filename = filename[0] df = parse_data(contents, filename) table = html.Div([ html.H5(filename), dash_table.DataTable( data=df.to_dict('rows'), columns=[{'name': i, 'id': i} for i in df.columns] ), html.Hr(), html.Div('Raw Content'), html.Pre(contents[0:200] + '...', style={ 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all' }) ]) return table The second part of a Dash application involves callbacks that define the application’s interactivity. In order to do this, we need to import Input and Output from dash.dependencies: from dash.dependencies import Input, Output, State In this application we have 2 callbacks: @app.callback(Output('Mygraph', 'figure'), [ Input('upload-data', 'contents'), Input('upload-data', 'filename') ]) So above, our input is the upload component we created at the beginning and have bound it to a callback such that whenever a file is selected, it updates Mygraph which is our Graph component in real time. Dash provides a decorator @app which makes it possible to bind a callback function to our components. You'll notice in the full app.py that we use the decorator before we declare the update_graph function. And below is our second callback with the same input (i.e. the files that are uploaded to our Upload component, and this time the output is the HTML Div containing our printed table version of the file’s data. Again, the decorator is called before we declare the update_table function. @app.callback(Output('output-data-upload', 'children'), [ Input('upload-data', 'contents'), Input('upload-data', 'filename') ]) In order to view our visualization, we need to run our web server just like in Flask. Remember Dash is built on top of Flask. Dash includes “hot-reloading”, this features is activated by default when you run your app with app.run_server(debug=True). This means that Dash will automatically refresh your browser when you make a change in your code. if __name__ == '__main__': app.run_server(debug=True, host='0.0.0.0', port=8000) Next, move to the terminal and start the server by typing the code below: python app.py - this will start a new web server at http://localhost:8000/. Now, putting everything together: import base64import datetimeimport ioimport plotly.graph_objs as goimport cufflinks as cfimport dashfrom dash.dependencies import Input, Output, Stateimport dash_core_components as dccimport dash_html_components as htmlimport dash_tableimport pandas as pdexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']app = dash.Dash(__name__, external_stylesheets=external_stylesheets)server = app.servercolors = { "graphBackground": "#F5F5F5", "background": "#ffffff", "text": "#000000"}app.layout = html.Div([ dcc.Upload( id='upload-data', children=html.Div([ 'Drag and Drop or ', html.A('Select Files') ]), style={ 'width': '100%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px' }, # Allow multiple files to be uploaded multiple=True ), dcc.Graph(id='Mygraph'), html.Div(id='output-data-upload')])def parse_data(contents, filename): content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) try: if 'csv' in filename: # Assume that the user uploaded a CSV or TXT file df = pd.read_csv( io.StringIO(decoded.decode('utf-8'))) elif 'xls' in filename: # Assume that the user uploaded an excel file df = pd.read_excel(io.BytesIO(decoded)) elif 'txt' or 'tsv' in filename: # Assume that the user upl, delimiter = r'\s+'oaded an excel file df = pd.read_csv( io.StringIO(decoded.decode('utf-8')), delimiter = r'\s+') except Exception as e: print(e) return html.Div([ 'There was an error processing this file.' ]) return df@app.callback(Output('Mygraph', 'figure'), [ Input('upload-data', 'contents'), Input('upload-data', 'filename') ])def update_graph(contents, filename): fig = { 'layout': go.Layout( plot_bgcolor=colors["graphBackground"], paper_bgcolor=colors["graphBackground"]) } if contents: contents = contents[0] filename = filename[0] df = parse_data(contents, filename) df = df.set_index(df.columns[0]) fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1) return fig@app.callback(Output('output-data-upload', 'children'), [ Input('upload-data', 'contents'), Input('upload-data', 'filename') ])def update_table(contents, filename): table = html.Div() if contents: contents = contents[0] filename = filename[0] df = parse_data(contents, filename) table = html.Div([ html.H5(filename), dash_table.DataTable( data=df.to_dict('rows'), columns=[{'name': i, 'id': i} for i in df.columns] ), html.Hr(), html.Div('Raw Content'), html.Pre(contents[0:200] + '...', style={ 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all' }) ]) return tableif __name__ == '__main__': app.run_server(debug=True) To run the app yourself, simply copy & paste the code above into your app.py file and from the terminal run python app.py Go to http://localhost:8000/ ... Launch a workspace (see guide here) and enter Jupyterlab. You can either run it from the notebook (simply execute the cell) or create an app.py file and run from the terminal. To view your running app, copy and paste your workspace’s URL into a separate tab. Remove the lab? and append -8000 (the public port on which we've launched the app above) to the workspace id number, before .cloud.kyso.io. For example, if my workspace is running at https://live-aymycm9bst.cloud.kyso.io/lab? In a separate tab, I can go to https://live-aymycm9bst-8000.cloud.kyso.io/, where my app will be running.
[ { "code": null, "e": 371, "s": 171, "text": "Let’s make an app to automatically plot data files. This is a walkthrough of creating a web app in python using plotly’s Dash, with an example we created at Kyso — the live version can be found here:" }, { "code": null, "e": 410, "s": 371, "text": "dash-app-dx9g2r0la6-8000.cloud.kyso.io" }, { "code": null, "e": 519, "s": 410, "text": "It’s an app for uploading any file with xy, xyyy, etc. coordinates and then automatically generating a plot." }, { "code": null, "e": 883, "s": 519, "text": "Dash is a Python framework for building web applications. It is built on top of Flask, Plotly.js, React and React Js., enabling you to build dashboards & applications using pure Python. In this tutorial, I will introduce you to the fundamentals and will assume that you have prior experience with Plotly. If you are new to plotly, check out these beginner guides:" }, { "code": null, "e": 919, "s": 883, "text": "https://kyso.io/KyleOS/plotly-intro" }, { "code": null, "e": 958, "s": 919, "text": "https://kyso.io/KyleOS/cufflinks-intro" }, { "code": null, "e": 1029, "s": 958, "text": "In order to start using Dash, you’ll need to install several packages." }, { "code": null, "e": 1112, "s": 1029, "text": "The core dash backend.Dash front-endDash HTML componentsDash core componentsPlotly" }, { "code": null, "e": 1135, "s": 1112, "text": "The core dash backend." }, { "code": null, "e": 1150, "s": 1135, "text": "Dash front-end" }, { "code": null, "e": 1171, "s": 1150, "text": "Dash HTML components" }, { "code": null, "e": 1192, "s": 1171, "text": "Dash core components" }, { "code": null, "e": 1199, "s": 1192, "text": "Plotly" }, { "code": null, "e": 1317, "s": 1199, "text": "Note that all of these are already pre-installed on Kyso’s workspaces if you would like to launch your app from Kyso!" }, { "code": null, "e": 1489, "s": 1317, "text": "pip install dash==0.21.1 pip install dash-renderer==0.13.0 pip install dash-html-components==0.11.0pip install dash-core-components==0.23.0 pip install plotly --upgrade" }, { "code": null, "e": 1894, "s": 1489, "text": "Dash apps are composed of two parts. The first part is the “layout” of the app and it describes what the application looks like. Dash provides Python classes for all of the visual components of the application, i.e to generate HTML content with Python. To use these classes, let’s import the dash_core_components and the dash_html_components libraries. Create a file named app.py with the following code:" }, { "code": null, "e": 1975, "s": 1894, "text": "import dashimport dash_core_components as dccimport dash_html_components as html" }, { "code": null, "e": 2278, "s": 1975, "text": "Like with Flask we can initialize Dash by calling the Dash class of dash. Once that is done we can create the layout for our application, using the Div class from the dash_html_components to create HTML Divs. Note that dash_html_componentsincludes all HTML tags for you to style the layout of your app." }, { "code": null, "e": 2726, "s": 2278, "text": "In order to create a graph within our layout, we use the Graph class from dash_core_components. Graph renders interactive data visualizations using plotly.js. The Graph class expects a figure object with the data to be plotted and the layout details. Dash also allows you to do stylings such as changing the background color and text color. You can change the background by using the style attribute and passing an object with your specific color." }, { "code": null, "e": 3543, "s": 2726, "text": "external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']app = dash.Dash(__name__, external_stylesheets=external_stylesheets)colors = { \"graphBackground\": \"#F5F5F5\", \"background\": \"#ffffff\", \"text\": \"#000000\"}app.layout = html.Div([ dcc.Upload( id='upload-data', children=html.Div([ 'Drag and Drop or ', html.A('Select Files') ]), style={ 'width': '100%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px' }, # Allow multiple files to be uploaded multiple=True ), dcc.Graph(id='Mygraph'), html.Div(id='output-data-upload')])" }, { "code": null, "e": 3931, "s": 3543, "text": "Take note that we’re setting ids for each component we’re creating, we’ll go through these in just a sec. The Dash upload component allows your app’s viewers to upload files. The app can access the contents of an uploaded file by listening to the content’s property of the dcc.Upload component, which is a base64 encoded string that contains the file’s contents, regardless of file-type." }, { "code": null, "e": 4065, "s": 3931, "text": "So we’ve created the layout above; the upload box with some styling as well as the Graph that will be created when we drop in a file." }, { "code": null, "e": 4146, "s": 4065, "text": "Ok so now there are a few things we need to do, we need to create functions for:" }, { "code": null, "e": 4325, "s": 4146, "text": "Reading in any file, whether it be csv, an excel file or tsv, and convert it into a Pandas DataFrame.Creating the graph when a new file is dropped.Printing the table of the data." }, { "code": null, "e": 4427, "s": 4325, "text": "Reading in any file, whether it be csv, an excel file or tsv, and convert it into a Pandas DataFrame." }, { "code": null, "e": 4474, "s": 4427, "text": "Creating the graph when a new file is dropped." }, { "code": null, "e": 4506, "s": 4474, "text": "Printing the table of the data." }, { "code": null, "e": 4550, "s": 4506, "text": "There are a few libraries we need for this:" }, { "code": null, "e": 4676, "s": 4550, "text": "import base64import datetimeimport ioimport plotly.graph_objs as goimport cufflinks as cfimport pandas as pdimport dash_table" }, { "code": null, "e": 4719, "s": 4676, "text": "So, to parse our targeted data file types:" }, { "code": null, "e": 5537, "s": 4719, "text": "def parse_data(contents, filename): content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) try: if 'csv' in filename: # Assume that the user uploaded a CSV or TXT file df = pd.read_csv( io.StringIO(decoded.decode('utf-8'))) elif 'xls' in filename: # Assume that the user uploaded an excel file df = pd.read_excel(io.BytesIO(decoded)) elif 'txt' or 'tsv' in filename: # Assume that the user upl, delimiter = r'\\s+'oaded an excel file df = pd.read_csv( io.StringIO(decoded.decode('utf-8')), delimiter = r'\\s+') except Exception as e: print(e) return html.Div([ 'There was an error processing this file.' ]) return df" }, { "code": null, "e": 5635, "s": 5537, "text": "Using cufflinks, a wrapper for easing plotting with pandas and plotly, to plot our scalar graphs:" }, { "code": null, "e": 6495, "s": 5635, "text": "def update_graph(contents, filename): fig = { 'layout': go.Layout( plot_bgcolor=colors[\"graphBackground\"], paper_bgcolor=colors[\"graphBackground\"]) } if contents: contents = contents[0] filename = filename[0] df = parse_data(contents, filename) df = df.set_index(df.columns[0]) fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1) table = html.Div([ html.H5(filename), dash_table.DataTable( data=df.to_dict('rows'), columns=[{'name': i, 'id': i} for i in df.columns] ), html.Hr(), html.Div('Raw Content'), html.Pre(contents[0:200] + '...', style={ 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all' }) ])" }, { "code": null, "e": 6560, "s": 6495, "text": "And finally creating a table for each time a file is dropped in:" }, { "code": null, "e": 7180, "s": 6560, "text": "def update_table(contents, filename): table = html.Div() if contents: contents = contents[0] filename = filename[0] df = parse_data(contents, filename) table = html.Div([ html.H5(filename), dash_table.DataTable( data=df.to_dict('rows'), columns=[{'name': i, 'id': i} for i in df.columns] ), html.Hr(), html.Div('Raw Content'), html.Pre(contents[0:200] + '...', style={ 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all' }) ]) return table" }, { "code": null, "e": 7362, "s": 7180, "text": "The second part of a Dash application involves callbacks that define the application’s interactivity. In order to do this, we need to import Input and Output from dash.dependencies:" }, { "code": null, "e": 7413, "s": 7362, "text": "from dash.dependencies import Input, Output, State" }, { "code": null, "e": 7454, "s": 7413, "text": "In this application we have 2 callbacks:" }, { "code": null, "e": 7621, "s": 7454, "text": "@app.callback(Output('Mygraph', 'figure'), [ Input('upload-data', 'contents'), Input('upload-data', 'filename') ])" }, { "code": null, "e": 8032, "s": 7621, "text": "So above, our input is the upload component we created at the beginning and have bound it to a callback such that whenever a file is selected, it updates Mygraph which is our Graph component in real time. Dash provides a decorator @app which makes it possible to bind a callback function to our components. You'll notice in the full app.py that we use the decorator before we declare the update_graph function." }, { "code": null, "e": 8318, "s": 8032, "text": "And below is our second callback with the same input (i.e. the files that are uploaded to our Upload component, and this time the output is the HTML Div containing our printed table version of the file’s data. Again, the decorator is called before we declare the update_table function." }, { "code": null, "e": 8498, "s": 8318, "text": "@app.callback(Output('output-data-upload', 'children'), [ Input('upload-data', 'contents'), Input('upload-data', 'filename') ])" }, { "code": null, "e": 8846, "s": 8498, "text": "In order to view our visualization, we need to run our web server just like in Flask. Remember Dash is built on top of Flask. Dash includes “hot-reloading”, this features is activated by default when you run your app with app.run_server(debug=True). This means that Dash will automatically refresh your browser when you make a change in your code." }, { "code": null, "e": 8930, "s": 8846, "text": "if __name__ == '__main__': app.run_server(debug=True, host='0.0.0.0', port=8000)" }, { "code": null, "e": 9080, "s": 8930, "text": "Next, move to the terminal and start the server by typing the code below: python app.py - this will start a new web server at http://localhost:8000/." }, { "code": null, "e": 9114, "s": 9080, "text": "Now, putting everything together:" }, { "code": null, "e": 12490, "s": 9114, "text": "import base64import datetimeimport ioimport plotly.graph_objs as goimport cufflinks as cfimport dashfrom dash.dependencies import Input, Output, Stateimport dash_core_components as dccimport dash_html_components as htmlimport dash_tableimport pandas as pdexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']app = dash.Dash(__name__, external_stylesheets=external_stylesheets)server = app.servercolors = { \"graphBackground\": \"#F5F5F5\", \"background\": \"#ffffff\", \"text\": \"#000000\"}app.layout = html.Div([ dcc.Upload( id='upload-data', children=html.Div([ 'Drag and Drop or ', html.A('Select Files') ]), style={ 'width': '100%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px' }, # Allow multiple files to be uploaded multiple=True ), dcc.Graph(id='Mygraph'), html.Div(id='output-data-upload')])def parse_data(contents, filename): content_type, content_string = contents.split(',') decoded = base64.b64decode(content_string) try: if 'csv' in filename: # Assume that the user uploaded a CSV or TXT file df = pd.read_csv( io.StringIO(decoded.decode('utf-8'))) elif 'xls' in filename: # Assume that the user uploaded an excel file df = pd.read_excel(io.BytesIO(decoded)) elif 'txt' or 'tsv' in filename: # Assume that the user upl, delimiter = r'\\s+'oaded an excel file df = pd.read_csv( io.StringIO(decoded.decode('utf-8')), delimiter = r'\\s+') except Exception as e: print(e) return html.Div([ 'There was an error processing this file.' ]) return df@app.callback(Output('Mygraph', 'figure'), [ Input('upload-data', 'contents'), Input('upload-data', 'filename') ])def update_graph(contents, filename): fig = { 'layout': go.Layout( plot_bgcolor=colors[\"graphBackground\"], paper_bgcolor=colors[\"graphBackground\"]) } if contents: contents = contents[0] filename = filename[0] df = parse_data(contents, filename) df = df.set_index(df.columns[0]) fig['data'] = df.iplot(asFigure=True, kind='scatter', mode='lines+markers', size=1) return fig@app.callback(Output('output-data-upload', 'children'), [ Input('upload-data', 'contents'), Input('upload-data', 'filename') ])def update_table(contents, filename): table = html.Div() if contents: contents = contents[0] filename = filename[0] df = parse_data(contents, filename) table = html.Div([ html.H5(filename), dash_table.DataTable( data=df.to_dict('rows'), columns=[{'name': i, 'id': i} for i in df.columns] ), html.Hr(), html.Div('Raw Content'), html.Pre(contents[0:200] + '...', style={ 'whiteSpace': 'pre-wrap', 'wordBreak': 'break-all' }) ]) return tableif __name__ == '__main__': app.run_server(debug=True)" }, { "code": null, "e": 12598, "s": 12490, "text": "To run the app yourself, simply copy & paste the code above into your app.py file and from the terminal run" }, { "code": null, "e": 12612, "s": 12598, "text": "python app.py" }, { "code": null, "e": 12641, "s": 12612, "text": "Go to http://localhost:8000/" }, { "code": null, "e": 12645, "s": 12641, "text": "..." }, { "code": null, "e": 12821, "s": 12645, "text": "Launch a workspace (see guide here) and enter Jupyterlab. You can either run it from the notebook (simply execute the cell) or create an app.py file and run from the terminal." }, { "code": null, "e": 13130, "s": 12821, "text": "To view your running app, copy and paste your workspace’s URL into a separate tab. Remove the lab? and append -8000 (the public port on which we've launched the app above) to the workspace id number, before .cloud.kyso.io. For example, if my workspace is running at https://live-aymycm9bst.cloud.kyso.io/lab?" } ]
Vectors in Julia - GeeksforGeeks
12 Oct, 2021 Vectors in Julia are a collection of elements just like other collections like Array, Sets, Dictionaries, etc. Vector are different from Sets because vectors are ordered collection of elements, and can hold duplicate values, unlike sets which require all the elements to be unique. Vectors are one-dimensional arrays, and support mostly the same interface as their multi-dimensional counterparts. Syntax: vector_name = [value1, value2, value3,..] vector_name = Vector{DataType}([value1, value2, value3,..]) Note: Vector{T} where T is some type means the same as Array{T,1}. Vector{Int} Array{Int64,1} # Vector{Int} = one-dimensional Vector of Int64. Vector{Float64} Array{Float64,1} A 1D Vector or 1-dimensional Vector is a linear representation of elements. A 1D Vector can only have either a row or a column. It represents a type of list that can be accessed by subsequent memory locations. Vectors can be resized. Elements can be added or removed from the front or back of the vector. Julia A = [1, 2, 3]3-element Array{Int64,1}: 1 2 3 A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..]) Julia # Julia program to illustrate # the use of Vector # Creating a 1D Vectorvector = [1, 2, 3, 4] println(vector) # Vector{T}(undef, n)Vector{Float64}(undef, 3) Output: julia> vector = [1, 2, 3, 4] 4-element Array{Int64,1}: 1 2 3 4 julia> Vector{Float64}(undef, 3) 3-element Array{Float64,1}: 6.90966e-310 6.90966e-310 6.90966e-310 Elements of a vector can be accessed by passing the index of the value in the vector as a parameter to the vector_name. This index is passed within ‘[ ]’. A range of vector elements can be accessed by passing the index range with the use of ‘:’. Example: Accessing elements in a Vector Julia # Julia program to illustrate # the use of Vector # Creating a Vector vector = [1, 2, 3, "Geeks", "tutorial", "Geeks"] # Passing index value println(vector[2]) # Accessing last value println(vector[end]) # Passing a range of indices println(vector[2:3]) # selects the second and third elements # Access every other elementprintln(vector[1:2:end]) Output: 2 Geeks Any[2, 3] Any[1, 3, "tutorial"] It pushes the elements into a vector from the rear end. This push operation is performed with the use of a predefined push!() function. Julia # Julia program to illustrate # the use of Vector # Creating a 1D VectorV = [1, 2, 3, 4] # push 5 in vectorpush!(V, 5) # return length of vectorprintln(length(V)) # print vectorprintln(V) Output: 5 1 2 3 4 5 It is used to pop or remove elements from a vector from the rear end. This pop operation is performed with the use of pop!() function. Julia # Julia program to illustrate # the use of Vector # Creating a 1D VectorV = [1, 2, 3, 4, 5] # remove 5 from vectorpop!(V) # Printing vectorprintln(V) Output: 1 2 3 4 Julia provides a predefined function called unshift!() to push the elements into a vector from the front end. Julia # Julia program to illustrate # the use of Vector # Creating a 1D VectorV = [1, 2, 3, 4] # push 5 in vector at frontunshift!(V, 5) # Printing vectorprintln(V) Output: 5 1 2 3 4 Julia provides a predefined function called shift!() which is used to pop or remove elements from a vector from the front. Julia # Julia program to illustrate # the use of Vector # Creating a 1D VectorV = [1, 2, 3, 4, 5] # remove 1 from vectorshift!(V) # Printing Vectorprintln(V) Output: 2 3 4 5 To add a list of items into a vector, julia provides a predefined function append!(). Julia # Julia program to illustrate # the use of Vector # Creating a 1D VectorV = Vector{Int64}([1, 2, 3, 4]) # append a list of items in a vectorappend!(V, [5, 6, 7]) # Printing Vectorprintln(V) Output: 1 2 3 4 5 6 7 Sum of vector elements can be calculated with the use of Julia’s predefined function sum(). Julia # Julia program to illustrate # the use of Vector # Creating a 1D VectorV = Vector{Int64}([1, 2, 3, 4]) # print sum of vector elementprintln(sum(V)) Output: 10 To compute the average of vector elements, Julia provides a predefined function mean() to calculate the average of elements. Julia # Julia program to illustrate # the use of Vector # Creating a 1D VectorV = Vector{Int64}([1, 2, 3, 4]) # print average of vector elementprintln(mean(V)) Output: 2 Vector addition uses ‘+’ and vector subtraction uses ‘ -‘. The arrays must have the same length Julia # Julia program to illustrate # the use of Vector # Creating a 1D VectorV1 = [1, 2, 3, 4, 5] V2 = [6, 7, 8, 9, 10] # Addition of Vectorprintln(V1 + V2) # Subtraction of Vectorprintln(V2 - V1) Output: Any[7, 9, 11, 13, 15] Any[5, 5, 5, 5, 5] The scalar is added to each entry of the vector. Scalar-vector multiplication uses * Julia # Julia program to illustrate # the use of Vector # Creating a 1D VectorV1 = [1, 2, 3, 4, 5] # Addition of scaler-Vectorprintln(V1 + 5) # Multiplication of Vectorprintln(V1 * 2) Output: Any[6, 7, 8, 9, 10] Any[2, 4, 6, 8, 10] sweetyty Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Getting the maximum value from a list in Julia - max() Method Get array dimensions and size of a dimension in Julia - size() Method Find maximum element along with its index in Julia - findmax() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Functions in Julia Searching in Array for a given element in Julia Join an array of strings into a single string in Julia - join() Method Working with Date and Time in Julia Exception handling in Julia Getting last element of an array in Julia - last() Method
[ { "code": null, "e": 24430, "s": 24402, "text": "\n12 Oct, 2021" }, { "code": null, "e": 24828, "s": 24430, "text": "Vectors in Julia are a collection of elements just like other collections like Array, Sets, Dictionaries, etc. Vector are different from Sets because vectors are ordered collection of elements, and can hold duplicate values, unlike sets which require all the elements to be unique. Vectors are one-dimensional arrays, and support mostly the same interface as their multi-dimensional counterparts. " }, { "code": null, "e": 24836, "s": 24828, "text": "Syntax:" }, { "code": null, "e": 24878, "s": 24836, "text": "vector_name = [value1, value2, value3,..]" }, { "code": null, "e": 24938, "s": 24878, "text": "vector_name = Vector{DataType}([value1, value2, value3,..])" }, { "code": null, "e": 25005, "s": 24938, "text": "Note: Vector{T} where T is some type means the same as Array{T,1}." }, { "code": null, "e": 25017, "s": 25005, "text": "Vector{Int}" }, { "code": null, "e": 25032, "s": 25017, "text": "Array{Int64,1}" }, { "code": null, "e": 25081, "s": 25032, "text": "# Vector{Int} = one-dimensional Vector of Int64." }, { "code": null, "e": 25097, "s": 25081, "text": "Vector{Float64}" }, { "code": null, "e": 25114, "s": 25097, "text": "Array{Float64,1}" }, { "code": null, "e": 25419, "s": 25114, "text": "A 1D Vector or 1-dimensional Vector is a linear representation of elements. A 1D Vector can only have either a row or a column. It represents a type of list that can be accessed by subsequent memory locations. Vectors can be resized. Elements can be added or removed from the front or back of the vector." }, { "code": null, "e": 25425, "s": 25419, "text": "Julia" }, { "code": "A = [1, 2, 3]3-element Array{Int64,1}: 1 2 3", "e": 25470, "s": 25425, "text": null }, { "code": null, "e": 25660, "s": 25470, "text": "A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector." }, { "code": null, "e": 25765, "s": 25660, "text": "vector_name = [value1, value2, value3,..]\nor\nvector_name = Vector{Datatype}([value1, value2, value3,..])" }, { "code": null, "e": 25771, "s": 25765, "text": "Julia" }, { "code": "# Julia program to illustrate # the use of Vector # Creating a 1D Vectorvector = [1, 2, 3, 4] println(vector) # Vector{T}(undef, n)Vector{Float64}(undef, 3)", "e": 25933, "s": 25771, "text": null }, { "code": null, "e": 25941, "s": 25933, "text": "Output:" }, { "code": null, "e": 26113, "s": 25941, "text": "julia> vector = [1, 2, 3, 4]\n4-element Array{Int64,1}:\n 1\n 2\n 3\n 4\n \njulia> Vector{Float64}(undef, 3)\n3-element Array{Float64,1}:\n 6.90966e-310\n 6.90966e-310\n 6.90966e-310" }, { "code": null, "e": 26359, "s": 26113, "text": "Elements of a vector can be accessed by passing the index of the value in the vector as a parameter to the vector_name. This index is passed within ‘[ ]’. A range of vector elements can be accessed by passing the index range with the use of ‘:’." }, { "code": null, "e": 26399, "s": 26359, "text": "Example: Accessing elements in a Vector" }, { "code": null, "e": 26405, "s": 26399, "text": "Julia" }, { "code": "# Julia program to illustrate # the use of Vector # Creating a Vector vector = [1, 2, 3, \"Geeks\", \"tutorial\", \"Geeks\"] # Passing index value println(vector[2]) # Accessing last value println(vector[end]) # Passing a range of indices println(vector[2:3]) # selects the second and third elements # Access every other elementprintln(vector[1:2:end])", "e": 26764, "s": 26405, "text": null }, { "code": null, "e": 26772, "s": 26764, "text": "Output:" }, { "code": null, "e": 26812, "s": 26772, "text": "2\nGeeks\nAny[2, 3]\nAny[1, 3, \"tutorial\"]" }, { "code": null, "e": 26948, "s": 26812, "text": "It pushes the elements into a vector from the rear end. This push operation is performed with the use of a predefined push!() function." }, { "code": null, "e": 26954, "s": 26948, "text": "Julia" }, { "code": "# Julia program to illustrate # the use of Vector # Creating a 1D VectorV = [1, 2, 3, 4] # push 5 in vectorpush!(V, 5) # return length of vectorprintln(length(V)) # print vectorprintln(V)", "e": 27150, "s": 26954, "text": null }, { "code": null, "e": 27158, "s": 27150, "text": "Output:" }, { "code": null, "e": 27170, "s": 27158, "text": "5\n1\n2\n3\n4\n5" }, { "code": null, "e": 27305, "s": 27170, "text": "It is used to pop or remove elements from a vector from the rear end. This pop operation is performed with the use of pop!() function." }, { "code": null, "e": 27311, "s": 27305, "text": "Julia" }, { "code": "# Julia program to illustrate # the use of Vector # Creating a 1D VectorV = [1, 2, 3, 4, 5] # remove 5 from vectorpop!(V) # Printing vectorprintln(V)", "e": 27468, "s": 27311, "text": null }, { "code": null, "e": 27476, "s": 27468, "text": "Output:" }, { "code": null, "e": 27484, "s": 27476, "text": "1\n2\n3\n4" }, { "code": null, "e": 27594, "s": 27484, "text": "Julia provides a predefined function called unshift!() to push the elements into a vector from the front end." }, { "code": null, "e": 27600, "s": 27594, "text": "Julia" }, { "code": "# Julia program to illustrate # the use of Vector # Creating a 1D VectorV = [1, 2, 3, 4] # push 5 in vector at frontunshift!(V, 5) # Printing vectorprintln(V)", "e": 27766, "s": 27600, "text": null }, { "code": null, "e": 27774, "s": 27766, "text": "Output:" }, { "code": null, "e": 27784, "s": 27774, "text": "5\n1\n2\n3\n4" }, { "code": null, "e": 27907, "s": 27784, "text": "Julia provides a predefined function called shift!() which is used to pop or remove elements from a vector from the front." }, { "code": null, "e": 27913, "s": 27907, "text": "Julia" }, { "code": "# Julia program to illustrate # the use of Vector # Creating a 1D VectorV = [1, 2, 3, 4, 5] # remove 1 from vectorshift!(V) # Printing Vectorprintln(V)", "e": 28072, "s": 27913, "text": null }, { "code": null, "e": 28080, "s": 28072, "text": "Output:" }, { "code": null, "e": 28088, "s": 28080, "text": "2\n3\n4\n5" }, { "code": null, "e": 28174, "s": 28088, "text": "To add a list of items into a vector, julia provides a predefined function append!()." }, { "code": null, "e": 28180, "s": 28174, "text": "Julia" }, { "code": "# Julia program to illustrate # the use of Vector # Creating a 1D VectorV = Vector{Int64}([1, 2, 3, 4]) # append a list of items in a vectorappend!(V, [5, 6, 7]) # Printing Vectorprintln(V)", "e": 28377, "s": 28180, "text": null }, { "code": null, "e": 28385, "s": 28377, "text": "Output:" }, { "code": null, "e": 28399, "s": 28385, "text": "1\n2\n3\n4\n5\n6\n7" }, { "code": null, "e": 28491, "s": 28399, "text": "Sum of vector elements can be calculated with the use of Julia’s predefined function sum()." }, { "code": null, "e": 28497, "s": 28491, "text": "Julia" }, { "code": "# Julia program to illustrate # the use of Vector # Creating a 1D VectorV = Vector{Int64}([1, 2, 3, 4]) # print sum of vector elementprintln(sum(V))", "e": 28652, "s": 28497, "text": null }, { "code": null, "e": 28660, "s": 28652, "text": "Output:" }, { "code": null, "e": 28663, "s": 28660, "text": "10" }, { "code": null, "e": 28788, "s": 28663, "text": "To compute the average of vector elements, Julia provides a predefined function mean() to calculate the average of elements." }, { "code": null, "e": 28794, "s": 28788, "text": "Julia" }, { "code": "# Julia program to illustrate # the use of Vector # Creating a 1D VectorV = Vector{Int64}([1, 2, 3, 4]) # print average of vector elementprintln(mean(V))", "e": 28954, "s": 28794, "text": null }, { "code": null, "e": 28962, "s": 28954, "text": "Output:" }, { "code": null, "e": 28964, "s": 28962, "text": "2" }, { "code": null, "e": 29023, "s": 28964, "text": "Vector addition uses ‘+’ and vector subtraction uses ‘ -‘." }, { "code": null, "e": 29060, "s": 29023, "text": "The arrays must have the same length" }, { "code": null, "e": 29066, "s": 29060, "text": "Julia" }, { "code": "# Julia program to illustrate # the use of Vector # Creating a 1D VectorV1 = [1, 2, 3, 4, 5] V2 = [6, 7, 8, 9, 10] # Addition of Vectorprintln(V1 + V2) # Subtraction of Vectorprintln(V2 - V1)", "e": 29264, "s": 29066, "text": null }, { "code": null, "e": 29272, "s": 29264, "text": "Output:" }, { "code": null, "e": 29313, "s": 29272, "text": "Any[7, 9, 11, 13, 15]\nAny[5, 5, 5, 5, 5]" }, { "code": null, "e": 29362, "s": 29313, "text": "The scalar is added to each entry of the vector." }, { "code": null, "e": 29398, "s": 29362, "text": "Scalar-vector multiplication uses *" }, { "code": null, "e": 29404, "s": 29398, "text": "Julia" }, { "code": "# Julia program to illustrate # the use of Vector # Creating a 1D VectorV1 = [1, 2, 3, 4, 5] # Addition of scaler-Vectorprintln(V1 + 5) # Multiplication of Vectorprintln(V1 * 2)", "e": 29589, "s": 29404, "text": null }, { "code": null, "e": 29597, "s": 29589, "text": "Output:" }, { "code": null, "e": 29637, "s": 29597, "text": "Any[6, 7, 8, 9, 10]\nAny[2, 4, 6, 8, 10]" }, { "code": null, "e": 29646, "s": 29637, "text": "sweetyty" }, { "code": null, "e": 29653, "s": 29646, "text": "Picked" }, { "code": null, "e": 29659, "s": 29653, "text": "Julia" }, { "code": null, "e": 29757, "s": 29659, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29766, "s": 29757, "text": "Comments" }, { "code": null, "e": 29779, "s": 29766, "text": "Old Comments" }, { "code": null, "e": 29841, "s": 29779, "text": "Getting the maximum value from a list in Julia - max() Method" }, { "code": null, "e": 29911, "s": 29841, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 29981, "s": 29911, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 30054, "s": 29981, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 30073, "s": 30054, "text": "Functions in Julia" }, { "code": null, "e": 30121, "s": 30073, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 30192, "s": 30121, "text": "Join an array of strings into a single string in Julia - join() Method" }, { "code": null, "e": 30228, "s": 30192, "text": "Working with Date and Time in Julia" }, { "code": null, "e": 30256, "s": 30228, "text": "Exception handling in Julia" } ]
PyQt5 - setCheckState() method for Check Box - GeeksforGeeks
22 Apr, 2020 When we create a check box it has only two states that are checked and un-checked, although we can add an intermediate state using setTristate method. We can set check box to be checked or un-checked using setChecked but with this method we are unable to set check box to intermediate state. setCheckState method is used to set the state of the check box it can be checked or un-checked even it can set intermediate state, it takes CheckState object as argument. Syntax : checkbox.setCheckState(1) Argument : It takes CheckState object as argument. Action performed:If we pass 0 to it, it set un-checked state to check boxIf we pass 1 to it, it set intermediate state to check boxIf we pass any other integer to it, it set checked state to check box Below is the implementation. # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box checkbox = QCheckBox('Geek ?', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 40) # making check box as tristate checkbox.setTristate(True) # setting check box state checkbox.setCheckState(1) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Python | Get dictionary keys as a list Bar Plot in Matplotlib Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method loops in python Python - Call function from another file Ways to filter Pandas DataFrame by column values Python | Convert set into a list Python program to find number of days between two given dates
[ { "code": null, "e": 23901, "s": 23873, "text": "\n22 Apr, 2020" }, { "code": null, "e": 24193, "s": 23901, "text": "When we create a check box it has only two states that are checked and un-checked, although we can add an intermediate state using setTristate method. We can set check box to be checked or un-checked using setChecked but with this method we are unable to set check box to intermediate state." }, { "code": null, "e": 24364, "s": 24193, "text": "setCheckState method is used to set the state of the check box it can be checked or un-checked even it can set intermediate state, it takes CheckState object as argument." }, { "code": null, "e": 24399, "s": 24364, "text": "Syntax : checkbox.setCheckState(1)" }, { "code": null, "e": 24450, "s": 24399, "text": "Argument : It takes CheckState object as argument." }, { "code": null, "e": 24651, "s": 24450, "text": "Action performed:If we pass 0 to it, it set un-checked state to check boxIf we pass 1 to it, it set intermediate state to check boxIf we pass any other integer to it, it set checked state to check box" }, { "code": null, "e": 24680, "s": 24651, "text": "Below is the implementation." }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box checkbox = QCheckBox('Geek ?', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 40) # making check box as tristate checkbox.setTristate(True) # setting check box state checkbox.setCheckState(1) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 25651, "s": 24680, "text": null }, { "code": null, "e": 25660, "s": 25651, "text": "Output :" }, { "code": null, "e": 25671, "s": 25660, "text": "Python-gui" }, { "code": null, "e": 25683, "s": 25671, "text": "Python-PyQt" }, { "code": null, "e": 25690, "s": 25683, "text": "Python" }, { "code": null, "e": 25788, "s": 25690, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25797, "s": 25788, "text": "Comments" }, { "code": null, "e": 25810, "s": 25797, "text": "Old Comments" }, { "code": null, "e": 25846, "s": 25810, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25885, "s": 25846, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25908, "s": 25885, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25959, "s": 25908, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 25991, "s": 25959, "text": "Python Dictionary keys() method" }, { "code": null, "e": 26007, "s": 25991, "text": "loops in python" }, { "code": null, "e": 26048, "s": 26007, "text": "Python - Call function from another file" }, { "code": null, "e": 26097, "s": 26048, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 26130, "s": 26097, "text": "Python | Convert set into a list" } ]
Python program to search an element in a doubly linked list
When it is required to search for an element in a doubly linked list, a ‘Node’ class needs to be created. In this class, there are three attributes, the data that is present in the node, the access to the next node of the linked list, and the access to the previous node of the linked list. Another class needs to be created that would have an initialization function, and the head of the node would be initialized to ‘None’ inside this. Multiple methods are defined by the user to add node to the linked list, to display the nodes it and to search for a specific node in the linked list. In a doubly linked list, the nodes have pointers. The current node would have a pointer to the next node as well as the previous node. The last value in the list will have ‘NULL’ value in the next pointer. It can be traversed in both the directions. Below is a demonstration for the same − Live Demo class Node: def __init__(self, my_data): self.previous = None self.data = my_data self.next = None class double_list: def __init__(self): self.head = None self.tail = None def add_data(self, my_data): new_node = Node(my_data) if(self.head == None): self.head = self.tail = new_node self.head.previous = None self.tail.next = None else: self.tail.next = new_node new_node.previous = self.tail self.tail = new_node self.tail.next = None def print_it(self): curr = self.head if (self.head == None): print("The list is empty") return print("The nodes in the doubly linked list are :") while curr != None: print(curr.data) curr = curr.next def search_node(self, val_to_search): i = 1; flag_val = False; curr = self.head; if(self.head == None): print("List is empty") return while(curr != None): if(curr.data == val_to_search): flag_val = True break curr = curr.next i = i + 1 if(flag_val): print("The node is present in the list at position : ") print(i) else: print("The node isn't present in the list") my_instance = double_list() print("Elements are being added to the doubly linked list") my_instance.add_data(10) my_instance.add_data(24) my_instance.add_data(54) my_instance.add_data(77) my_instance.add_data(24) my_instance.add_data(0) my_instance.print_it() print("The element 77 is being searched... ") my_instance.search_node(77) print("The element 7 is being searched... ") my_instance.search_node(7) Elements are being added to the doubly linked list The nodes in the doubly linked list are : 10 24 54 77 24 0 The element 77 is being searched... The node is present in the list at position : 4 The element 7 is being searched... The node isn't present in the list The ‘Node’ class is created. Another class with required attributes is created. Another method named ‘add_data’ is defined, that is used to add data to the circular linked list. Another method named ‘search_node’ is defined, that takes a parameter that needs to be searched for in the doubly linked list. It searches for the element and returns the index Another method named ‘print_it’ is defined that is used to display the linked list data on the console. An object of the ‘double_list’ class is created, and the methods are called on it to add data. The ‘search_node’ method is called. It iterates through the nodes in the linked list, and gives the index of the element if found. This is displayed on the console using the ‘print_it’ method.
[ { "code": null, "e": 1353, "s": 1062, "text": "When it is required to search for an element in a doubly linked list, a ‘Node’ class needs to be created. In this class, there are three attributes, the data that is present in the node, the access to the next node of the linked list, and the access to the previous node of the linked list." }, { "code": null, "e": 1500, "s": 1353, "text": "Another class needs to be created that would have an initialization function, and the head of the node would be initialized to ‘None’ inside this." }, { "code": null, "e": 1651, "s": 1500, "text": "Multiple methods are defined by the user to add node to the linked list, to display the nodes it and to search for a specific node in the linked list." }, { "code": null, "e": 1901, "s": 1651, "text": "In a doubly linked list, the nodes have pointers. The current node would have a pointer to the next node as well as the previous node. The last value in the list will have ‘NULL’ value in the next pointer. It can be traversed in both the directions." }, { "code": null, "e": 1941, "s": 1901, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1952, "s": 1941, "text": " Live Demo" }, { "code": null, "e": 3682, "s": 1952, "text": "class Node:\n def __init__(self, my_data):\n self.previous = None\n self.data = my_data\n self.next = None\nclass double_list:\n def __init__(self):\n self.head = None\n self.tail = None\n def add_data(self, my_data):\n new_node = Node(my_data)\n if(self.head == None):\n self.head = self.tail = new_node\n self.head.previous = None\n self.tail.next = None\n else:\n self.tail.next = new_node\n new_node.previous = self.tail\n self.tail = new_node\n self.tail.next = None\n def print_it(self):\n curr = self.head\n if (self.head == None):\n print(\"The list is empty\")\n return\n print(\"The nodes in the doubly linked list are :\")\n while curr != None:\n print(curr.data)\n curr = curr.next\n def search_node(self, val_to_search):\n i = 1;\n flag_val = False;\n curr = self.head;\n if(self.head == None):\n print(\"List is empty\")\n return\n while(curr != None):\n if(curr.data == val_to_search):\n flag_val = True\n break\n curr = curr.next\n i = i + 1\n if(flag_val):\n print(\"The node is present in the list at position : \")\n print(i)\n else:\n print(\"The node isn't present in the list\")\nmy_instance = double_list()\nprint(\"Elements are being added to the doubly linked list\")\nmy_instance.add_data(10)\nmy_instance.add_data(24)\nmy_instance.add_data(54)\nmy_instance.add_data(77)\nmy_instance.add_data(24)\nmy_instance.add_data(0)\nmy_instance.print_it()\nprint(\"The element 77 is being searched... \")\nmy_instance.search_node(77)\nprint(\"The element 7 is being searched... \")\nmy_instance.search_node(7)" }, { "code": null, "e": 3946, "s": 3682, "text": "Elements are being added to the doubly linked list\nThe nodes in the doubly linked list are :\n10\n24\n54\n77\n24\n0\nThe element 77 is being searched...\nThe node is present in the list at position :\n4\nThe element 7 is being searched...\nThe node isn't present in the list" }, { "code": null, "e": 3975, "s": 3946, "text": "The ‘Node’ class is created." }, { "code": null, "e": 4026, "s": 3975, "text": "Another class with required attributes is created." }, { "code": null, "e": 4124, "s": 4026, "text": "Another method named ‘add_data’ is defined, that is used to add data to the circular linked list." }, { "code": null, "e": 4251, "s": 4124, "text": "Another method named ‘search_node’ is defined, that takes a parameter that needs to be searched for in the doubly linked list." }, { "code": null, "e": 4301, "s": 4251, "text": "It searches for the element and returns the index" }, { "code": null, "e": 4405, "s": 4301, "text": "Another method named ‘print_it’ is defined that is used to display the linked list data on the console." }, { "code": null, "e": 4500, "s": 4405, "text": "An object of the ‘double_list’ class is created, and the methods are called on it to add data." }, { "code": null, "e": 4536, "s": 4500, "text": "The ‘search_node’ method is called." }, { "code": null, "e": 4631, "s": 4536, "text": "It iterates through the nodes in the linked list, and gives the index of the element if found." }, { "code": null, "e": 4693, "s": 4631, "text": "This is displayed on the console using the ‘print_it’ method." } ]
Sum of Two or Multiple DataFrame Columns in R - GeeksforGeeks
23 Sep, 2021 In this article, we will discuss how to perform some of two and multiple dataframes columns in R programming language. Database in use: The columns whose sum has to be calculated can be called through the $ operator and then we can perform the sum of two dataframe columns by using “+” operator. Syntax: dataframe$column1 + dataframe$column2 where dataframe is the input dataframe column1 is one column in the dataframe column2 is another column in the dataframe Example: R program to add two columns in dataframe R # create a dataframe with subjects marksdata=data.frame(sub1=c(90,89,78,89), sub2=c(100,90,86,84), sub3=c(89,90,98,99), sub4=c(86,78,87,99)) # add column1 and column2print(data$sub1 + data$sub2) # add column1 and column3print(data$sub1 + data$sub3) # add column1 and column4print(data$sub1 + data$sub4) # add column2 and column4print(data$sub2 + data$sub4) Output: [1] 190 179 164 173 [1] 179 179 176 188 [1] 176 167 165 188 [1] 186 168 173 183 We can calculate the sum of multiple columns by using rowSums() and c() Function. we simply have to pass the name of the columns. Syntax: rowSums(dataframe[ , c(“column1”, “column2”, “column n”)]) where dataframe is the input dataframe c() represents the number of columns to be specified to add Example: R program to add multiple columns Python3 # create a dataframe with subjects marksdata = data.frame(sub1=c(90, 89, 78, 89), sub2=c(100, 90, 86, 84), sub3=c(89, 90, 98, 99), sub4=c(86, 78, 87, 99)) # add column1, column2 and column 4print(rowSums(data[, c("sub1", "sub2", "sub4")])) # add column1, column2 and column 3print(rowSums(data[, c("sub1", "sub2", "sub3")])) # add column4, column2 and column 3print(rowSums(data[, c("sub4", "sub2", "sub3")])) Output: [1] 276 257 251 272 [1] 279 269 262 272 [1] 275 258 271 282 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Count Unique Values in R How to Split Column Into Multiple Columns in R DataFrame? Count Number of Characters in String in R Drop column(s) by name from a given DataFrame in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n23 Sep, 2021" }, { "code": null, "e": 24970, "s": 24851, "text": "In this article, we will discuss how to perform some of two and multiple dataframes columns in R programming language." }, { "code": null, "e": 24987, "s": 24970, "text": "Database in use:" }, { "code": null, "e": 25147, "s": 24987, "text": "The columns whose sum has to be calculated can be called through the $ operator and then we can perform the sum of two dataframe columns by using “+” operator." }, { "code": null, "e": 25155, "s": 25147, "text": "Syntax:" }, { "code": null, "e": 25193, "s": 25155, "text": "dataframe$column1 + dataframe$column2" }, { "code": null, "e": 25199, "s": 25193, "text": "where" }, { "code": null, "e": 25232, "s": 25199, "text": "dataframe is the input dataframe" }, { "code": null, "e": 25271, "s": 25232, "text": "column1 is one column in the dataframe" }, { "code": null, "e": 25314, "s": 25271, "text": "column2 is another column in the dataframe" }, { "code": null, "e": 25365, "s": 25314, "text": "Example: R program to add two columns in dataframe" }, { "code": null, "e": 25367, "s": 25365, "text": "R" }, { "code": "# create a dataframe with subjects marksdata=data.frame(sub1=c(90,89,78,89), sub2=c(100,90,86,84), sub3=c(89,90,98,99), sub4=c(86,78,87,99)) # add column1 and column2print(data$sub1 + data$sub2) # add column1 and column3print(data$sub1 + data$sub3) # add column1 and column4print(data$sub1 + data$sub4) # add column2 and column4print(data$sub2 + data$sub4)", "e": 25773, "s": 25367, "text": null }, { "code": null, "e": 25781, "s": 25773, "text": "Output:" }, { "code": null, "e": 25861, "s": 25781, "text": "[1] 190 179 164 173\n[1] 179 179 176 188\n[1] 176 167 165 188\n[1] 186 168 173 183" }, { "code": null, "e": 25991, "s": 25861, "text": "We can calculate the sum of multiple columns by using rowSums() and c() Function. we simply have to pass the name of the columns." }, { "code": null, "e": 25999, "s": 25991, "text": "Syntax:" }, { "code": null, "e": 26058, "s": 25999, "text": "rowSums(dataframe[ , c(“column1”, “column2”, “column n”)])" }, { "code": null, "e": 26064, "s": 26058, "text": "where" }, { "code": null, "e": 26097, "s": 26064, "text": "dataframe is the input dataframe" }, { "code": null, "e": 26157, "s": 26097, "text": "c() represents the number of columns to be specified to add" }, { "code": null, "e": 26200, "s": 26157, "text": "Example: R program to add multiple columns" }, { "code": null, "e": 26208, "s": 26200, "text": "Python3" }, { "code": "# create a dataframe with subjects marksdata = data.frame(sub1=c(90, 89, 78, 89), sub2=c(100, 90, 86, 84), sub3=c(89, 90, 98, 99), sub4=c(86, 78, 87, 99)) # add column1, column2 and column 4print(rowSums(data[, c(\"sub1\", \"sub2\", \"sub4\")])) # add column1, column2 and column 3print(rowSums(data[, c(\"sub1\", \"sub2\", \"sub3\")])) # add column4, column2 and column 3print(rowSums(data[, c(\"sub4\", \"sub2\", \"sub3\")]))", "e": 26674, "s": 26208, "text": null }, { "code": null, "e": 26682, "s": 26674, "text": "Output:" }, { "code": null, "e": 26742, "s": 26682, "text": "[1] 276 257 251 272\n[1] 279 269 262 272\n[1] 275 258 271 282" }, { "code": null, "e": 26749, "s": 26742, "text": "Picked" }, { "code": null, "e": 26770, "s": 26749, "text": "R DataFrame-Programs" }, { "code": null, "e": 26782, "s": 26770, "text": "R-DataFrame" }, { "code": null, "e": 26793, "s": 26782, "text": "R Language" }, { "code": null, "e": 26804, "s": 26793, "text": "R Programs" }, { "code": null, "e": 26902, "s": 26804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26911, "s": 26902, "text": "Comments" }, { "code": null, "e": 26924, "s": 26911, "text": "Old Comments" }, { "code": null, "e": 26976, "s": 26924, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27014, "s": 26976, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27049, "s": 27014, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27107, "s": 27049, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27156, "s": 27107, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27206, "s": 27156, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27231, "s": 27206, "text": "Count Unique Values in R" }, { "code": null, "e": 27289, "s": 27231, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27331, "s": 27289, "text": "Count Number of Characters in String in R" } ]
How do I get the background color of a Tkinter Canvas widget?
Tkinter canvas widget is used for many different purposes such as adding objects, drawing shapes, images and complex visuals to a graphical interface in an application. We can also configure its style such as background color, foreground color, and other properties using the configure properties or passing attributes. Suppose we want to inherit the background color of the Canvas widget in another widget or in some part of the application. This can be achieved by using my_canvas["background"] property. Further, we can use canvas["background"] to fetch the background color of the canvas widget. # Import the required library from tkinter import * from tkinter import ttk # Create an instance of tkinter frame win = Tk() win.geometry("700x350") # Add a Canvas widget canvas = Canvas(win, background= "white") # Draw a rectangle in Canvas and inherit the background color of Canvas canvas.create_rectangle(50,50,350,190, outline="black", fill= canvas["background"]) canvas.pack() win.mainloop() Executing the above code will display a window with a rectangle having the same background color as the canvas.
[ { "code": null, "e": 1382, "s": 1062, "text": "Tkinter canvas widget is used for many different purposes such as adding objects, drawing shapes, images and complex visuals to a graphical interface in an application. We can also configure its style such as background color, foreground color, and other properties using the configure properties or passing attributes." }, { "code": null, "e": 1662, "s": 1382, "text": "Suppose we want to inherit the background color of the Canvas widget in another widget or in some part of the application. This can be achieved by using my_canvas[\"background\"] property. Further, we can use canvas[\"background\"] to fetch the background color of the canvas widget." }, { "code": null, "e": 2063, "s": 1662, "text": "# Import the required library\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame\nwin = Tk()\nwin.geometry(\"700x350\")\n\n# Add a Canvas widget\ncanvas = Canvas(win, background= \"white\")\n\n# Draw a rectangle in Canvas and inherit the background color of Canvas\ncanvas.create_rectangle(50,50,350,190, outline=\"black\", fill= canvas[\"background\"])\ncanvas.pack()\nwin.mainloop()" }, { "code": null, "e": 2175, "s": 2063, "text": "Executing the above code will display a window with a rectangle having the same background color as the canvas." } ]
How do I convert a char to an int in C and C++?
In C language, there are three methods to convert a char type variable to an int. These are given as follows − sscanf() atoi() Typecasting Here is an example of converting char to int in C language, Live Demo #include<stdio.h> #include<stdlib.h> int main() { const char *str = "12345"; char c = 's'; int x, y, z; sscanf(str, "%d", &x); // Using sscanf printf("\nThe value of x : %d", x); y = atoi(str); // Using atoi() printf("\nThe value of y : %d", y); z = (int)(c); // Using typecasting printf("\nThe value of z : %d", z); return 0; } Here is the output: The value of x : 12345 The value of y : 12345 The value of z : 115 In C++ language, there are two following methods to convert a char type variable into an int − stoi() Typecasting Here is an example of converting char to int in C++ language, Live Demo #include <iostream> #include <string> using namespace std; int main() { char s1[] = "45"; char c = 's'; int x = stoi(s1); cout << "The value of x : " << x; int y = (int)(c); cout << "\nThe value of y : " << y; return 0; } Here is the output The value of x : 45 The value of y : 115
[ { "code": null, "e": 1173, "s": 1062, "text": "In C language, there are three methods to convert a char type variable to an int. These are given as follows −" }, { "code": null, "e": 1182, "s": 1173, "text": "sscanf()" }, { "code": null, "e": 1189, "s": 1182, "text": "atoi()" }, { "code": null, "e": 1201, "s": 1189, "text": "Typecasting" }, { "code": null, "e": 1261, "s": 1201, "text": "Here is an example of converting char to int in C language," }, { "code": null, "e": 1272, "s": 1261, "text": " Live Demo" }, { "code": null, "e": 1635, "s": 1272, "text": "#include<stdio.h>\n#include<stdlib.h>\nint main() {\n const char *str = \"12345\";\n char c = 's';\n int x, y, z;\n\n sscanf(str, \"%d\", &x); // Using sscanf\n printf(\"\\nThe value of x : %d\", x);\n\n y = atoi(str); // Using atoi()\n printf(\"\\nThe value of y : %d\", y);\n\n z = (int)(c); // Using typecasting\n printf(\"\\nThe value of z : %d\", z);\n\n return 0;\n}" }, { "code": null, "e": 1655, "s": 1635, "text": "Here is the output:" }, { "code": null, "e": 1722, "s": 1655, "text": "The value of x : 12345\nThe value of y : 12345\nThe value of z : 115" }, { "code": null, "e": 1817, "s": 1722, "text": "In C++ language, there are two following methods to convert a char type variable into an int −" }, { "code": null, "e": 1824, "s": 1817, "text": "stoi()" }, { "code": null, "e": 1836, "s": 1824, "text": "Typecasting" }, { "code": null, "e": 1898, "s": 1836, "text": "Here is an example of converting char to int in C++ language," }, { "code": null, "e": 1909, "s": 1898, "text": " Live Demo" }, { "code": null, "e": 2155, "s": 1909, "text": "#include <iostream>\n#include <string>\nusing namespace std;\nint main() {\n char s1[] = \"45\";\n char c = 's';\n\n int x = stoi(s1);\n cout << \"The value of x : \" << x;\n\n int y = (int)(c);\n cout << \"\\nThe value of y : \" << y;\n\n return 0;\n}" }, { "code": null, "e": 2174, "s": 2155, "text": "Here is the output" }, { "code": null, "e": 2215, "s": 2174, "text": "The value of x : 45\nThe value of y : 115" } ]
How to get the size of a Directory in Python ?
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Let’s see how to get the size of a directory in python. The Python os package gives the flexibility to access the file/directory structure so that we can walk through each file in a directory and get the size of them. os.walk() function takes the directory path as a parameter and it walks through the directory. os.path.getsize() function takes the file name as a parameter and gives the size of it. So the sum of each file size in a directory gives us the total size of the directory. import os import sys if __name__ == '__main__': try: directory = input("Enter the directory which you want to get the size : ") except IndexError: sys.exit("Invalid directory") dir_size = 0 readable_sizes = {'B': 1, 'KB': float(1) / 1024, 'MB': float(1) / (1024 * 1024), 'GB': float(1) / (1024 * 1024 * 1024) } for (path, dirs, files) in os.walk(directory): for file in files: filename = os.path.join(path, file) dir_size += os.path.getsize(filename) readable_sizes_list = [str(round(readable_sizes[key] * dir_size, 2)) + " " + key for key in readable_sizes] if dir_size == 0: print("File Empty") else: for units in sorted(readable_sizes_list)[::-1]: print("Folder Size: " + units) Output: Enter the directory which you want to get the size : C:\Users\cgoka\Desktop\mylibs Folder Size: 733160003 B Folder Size: 715976.57 KB Folder Size: 699.2 MB Folder Size: 0.68 GB Python walk() Happy Learning 🙂 How to check whether a file exists python ? Python TypeCasting for Different Types Python How to read input from keyboard Java 8 walk How to Read all files in a folder How install Python on Windows 10 How to Search a file in a Directory using Java Python – How to remove duplicate elements from List Python – Print different vowels present in a String Python – Find the biggest of 2 given numbers How to Remove Spaces from String in Python How to get Words Count in Python from a File How to get Characters Count in Python from a File How to merge two lists in Python How to Read CSV File in Python How to Create or Delete Directories in Python ? How to check whether a file exists python ? Python TypeCasting for Different Types Python How to read input from keyboard Java 8 walk How to Read all files in a folder How install Python on Windows 10 How to Search a file in a Directory using Java Python – How to remove duplicate elements from List Python – Print different vowels present in a String Python – Find the biggest of 2 given numbers How to Remove Spaces from String in Python How to get Words Count in Python from a File How to get Characters Count in Python from a File How to merge two lists in Python How to Read CSV File in Python How to Create or Delete Directories in Python ? Δ Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 454, "s": 398, "text": "Let’s see how to get the size of a directory in python." }, { "code": null, "e": 616, "s": 454, "text": "The Python os package gives the flexibility to access the file/directory structure so that we can walk through each file in a directory and get the size of them." }, { "code": null, "e": 711, "s": 616, "text": "os.walk() function takes the directory path as a parameter and it walks through the directory." }, { "code": null, "e": 799, "s": 711, "text": "os.path.getsize() function takes the file name as a parameter and gives the size of it." }, { "code": null, "e": 885, "s": 799, "text": "So the sum of each file size in a directory gives us the total size of the directory." }, { "code": null, "e": 1751, "s": 885, "text": "import os\nimport sys\n\nif __name__ == '__main__':\n try:\n directory = input(\"Enter the directory which you want to get the size : \")\n except IndexError:\n sys.exit(\"Invalid directory\")\n\n dir_size = 0\n readable_sizes = {'B': 1,\n 'KB': float(1) / 1024,\n 'MB': float(1) / (1024 * 1024),\n 'GB': float(1) / (1024 * 1024 * 1024)\n }\n for (path, dirs, files) in os.walk(directory):\n for file in files:\n filename = os.path.join(path, file)\n dir_size += os.path.getsize(filename)\n readable_sizes_list = [str(round(readable_sizes[key] * dir_size, 2)) + \" \" + key for key in readable_sizes]\n\n if dir_size == 0:\n print(\"File Empty\")\n else:\n for units in sorted(readable_sizes_list)[::-1]:\n print(\"Folder Size: \" + units)" }, { "code": null, "e": 1759, "s": 1751, "text": "Output:" }, { "code": null, "e": 1936, "s": 1759, "text": "Enter the directory which you want to get the size : C:\\Users\\cgoka\\Desktop\\mylibs\nFolder Size: 733160003 B\nFolder Size: 715976.57 KB\nFolder Size: 699.2 MB\nFolder Size: 0.68 GB" }, { "code": null, "e": 1950, "s": 1936, "text": "Python walk()" }, { "code": null, "e": 1967, "s": 1950, "text": "Happy Learning 🙂" }, { "code": null, "e": 2616, "s": 1967, "text": "\nHow to check whether a file exists python ?\nPython TypeCasting for Different Types\nPython How to read input from keyboard\nJava 8 walk How to Read all files in a folder\nHow install Python on Windows 10\nHow to Search a file in a Directory using Java\nPython – How to remove duplicate elements from List\nPython – Print different vowels present in a String\nPython – Find the biggest of 2 given numbers\nHow to Remove Spaces from String in Python\nHow to get Words Count in Python from a File\nHow to get Characters Count in Python from a File\nHow to merge two lists in Python\nHow to Read CSV File in Python\nHow to Create or Delete Directories in Python ?\n" }, { "code": null, "e": 2660, "s": 2616, "text": "How to check whether a file exists python ?" }, { "code": null, "e": 2699, "s": 2660, "text": "Python TypeCasting for Different Types" }, { "code": null, "e": 2738, "s": 2699, "text": "Python How to read input from keyboard" }, { "code": null, "e": 2784, "s": 2738, "text": "Java 8 walk How to Read all files in a folder" }, { "code": null, "e": 2817, "s": 2784, "text": "How install Python on Windows 10" }, { "code": null, "e": 2864, "s": 2817, "text": "How to Search a file in a Directory using Java" }, { "code": null, "e": 2916, "s": 2864, "text": "Python – How to remove duplicate elements from List" }, { "code": null, "e": 2968, "s": 2916, "text": "Python – Print different vowels present in a String" }, { "code": null, "e": 3013, "s": 2968, "text": "Python – Find the biggest of 2 given numbers" }, { "code": null, "e": 3056, "s": 3013, "text": "How to Remove Spaces from String in Python" }, { "code": null, "e": 3101, "s": 3056, "text": "How to get Words Count in Python from a File" }, { "code": null, "e": 3151, "s": 3101, "text": "How to get Characters Count in Python from a File" }, { "code": null, "e": 3184, "s": 3151, "text": "How to merge two lists in Python" }, { "code": null, "e": 3215, "s": 3184, "text": "How to Read CSV File in Python" }, { "code": null, "e": 3263, "s": 3215, "text": "How to Create or Delete Directories in Python ?" }, { "code": null, "e": 3269, "s": 3267, "text": "Δ" }, { "code": null, "e": 3292, "s": 3269, "text": " Python – Introduction" }, { "code": null, "e": 3311, "s": 3292, "text": " Python – Features" }, { "code": null, "e": 3340, "s": 3311, "text": " Python – Install on Windows" }, { "code": null, "e": 3367, "s": 3340, "text": " Python – Modes of Program" }, { "code": null, "e": 3391, "s": 3367, "text": " Python – Number System" }, { "code": null, "e": 3413, "s": 3391, "text": " Python – Identifiers" }, { "code": null, "e": 3433, "s": 3413, "text": " Python – Operators" }, { "code": null, "e": 3460, "s": 3433, "text": " Python – Ternary Operator" }, { "code": null, "e": 3493, "s": 3460, "text": " Python – Command Line Arguments" }, { "code": null, "e": 3512, "s": 3493, "text": " Python – Keywords" }, { "code": null, "e": 3533, "s": 3512, "text": " Python – Data Types" }, { "code": null, "e": 3562, "s": 3533, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 3592, "s": 3562, "text": " Python – Virtual Environment" }, { "code": null, "e": 3615, "s": 3592, "text": " Pyhton – Type Casting" }, { "code": null, "e": 3639, "s": 3615, "text": " Python – String to Int" }, { "code": null, "e": 3672, "s": 3639, "text": " Python – Conditional Statements" }, { "code": null, "e": 3695, "s": 3672, "text": " Python – if statement" }, { "code": null, "e": 3724, "s": 3695, "text": " Python – *args and **kwargs" }, { "code": null, "e": 3750, "s": 3724, "text": " Python – Date Formatting" }, { "code": null, "e": 3785, "s": 3750, "text": " Python – Read input from keyboard" }, { "code": null, "e": 3805, "s": 3785, "text": " Python – raw_input" }, { "code": null, "e": 3829, "s": 3805, "text": " Python – List In Depth" }, { "code": null, "e": 3858, "s": 3829, "text": " Python – List Comprehension" }, { "code": null, "e": 3881, "s": 3858, "text": " Python – Set in Depth" }, { "code": null, "e": 3911, "s": 3881, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 3936, "s": 3911, "text": " Python – Tuple in Depth" }, { "code": null, "e": 3966, "s": 3936, "text": " Python – Stack Datastructure" }, { "code": null, "e": 3996, "s": 3966, "text": " Python – Classes and Objects" }, { "code": null, "e": 4019, "s": 3996, "text": " Python – Constructors" }, { "code": null, "e": 4050, "s": 4019, "text": " Python – Object Introspection" }, { "code": null, "e": 4072, "s": 4050, "text": " Python – Inheritance" }, { "code": null, "e": 4093, "s": 4072, "text": " Python – Decorators" }, { "code": null, "e": 4129, "s": 4093, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 4159, "s": 4129, "text": " Python – Exceptions Handling" }, { "code": null, "e": 4193, "s": 4159, "text": " Python – User defined Exceptions" }, { "code": null, "e": 4219, "s": 4193, "text": " Python – Multiprocessing" }, { "code": null, "e": 4257, "s": 4219, "text": " Python – Default function parameters" }, { "code": null, "e": 4285, "s": 4257, "text": " Python – Lambdas Functions" }, { "code": null, "e": 4309, "s": 4285, "text": " Python – NumPy Library" }, { "code": null, "e": 4335, "s": 4309, "text": " Python – MySQL Connector" }, { "code": null, "e": 4367, "s": 4335, "text": " Python – MySQL Create Database" }, { "code": null, "e": 4393, "s": 4367, "text": " Python – MySQL Read Data" }, { "code": null, "e": 4421, "s": 4393, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 4452, "s": 4421, "text": " Python – MySQL Update Records" }, { "code": null, "e": 4483, "s": 4452, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 4516, "s": 4483, "text": " Python – String Case Conversion" }, { "code": null, "e": 4551, "s": 4516, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 4588, "s": 4551, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 4626, "s": 4588, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 4652, "s": 4626, "text": " Howto – Merge two Lists" }, { "code": null, "e": 4677, "s": 4652, "text": " Howto – Merge two dicts" }, { "code": null, "e": 4717, "s": 4677, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 4752, "s": 4717, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 4787, "s": 4752, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 4816, "s": 4787, "text": " Howto – Read Env variables" }, { "code": null, "e": 4842, "s": 4816, "text": " Howto – Read a text File" }, { "code": null, "e": 4868, "s": 4842, "text": " Howto – Read a JSON File" }, { "code": null, "e": 4900, "s": 4868, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 4928, "s": 4900, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 4968, "s": 4928, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 5002, "s": 4968, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 5027, "s": 5002, "text": " Howto – create Zip File" }, { "code": null, "e": 5048, "s": 5027, "text": " Howto – Get OS info" }, { "code": null, "e": 5079, "s": 5048, "text": " Howto – Get size of Directory" }, { "code": null, "e": 5116, "s": 5079, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 5153, "s": 5116, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 5175, "s": 5153, "text": " Howto – Sort Objects" }, { "code": null, "e": 5213, "s": 5175, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 5236, "s": 5213, "text": " Howto – Read CSV File" }, { "code": null, "e": 5274, "s": 5236, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 5305, "s": 5274, "text": " Howto – Access for loop index" }, { "code": null, "e": 5343, "s": 5305, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 5383, "s": 5343, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 5430, "s": 5383, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 5462, "s": 5430, "text": " Howto – Sort dictionary by key" } ]
Converting a string to a date in JavaScript
The best format to represent a date is yyyy-mm-dd as this causes no confusion and is pretty straight forward. In order to parse dates from this string format to Date objects in JS, all you need to do is pass this string to the Date constructor. For example, let a = '2019-08-10'; console.log(new Date(a)) This will give the output − Sat Aug 10 2019 05:30:00 GMT+0530 (India Standard Time) Note that the new date is created at 0000 hrs UTC. If you need to parse any other date formats, you can check out https://developer.mozilla.org as it provides details about using different formats to parse dates.
[ { "code": null, "e": 1320, "s": 1062, "text": "The best format to represent a date is yyyy-mm-dd as this causes no\nconfusion and is pretty straight forward. In order to parse dates from\nthis string format to Date objects in JS, all you need to do is pass this\nstring to the Date constructor. For example," }, { "code": null, "e": 1367, "s": 1320, "text": "let a = '2019-08-10';\nconsole.log(new Date(a))" }, { "code": null, "e": 1395, "s": 1367, "text": "This will give the output −" }, { "code": null, "e": 1451, "s": 1395, "text": "Sat Aug 10 2019 05:30:00 GMT+0530 (India Standard Time)" }, { "code": null, "e": 1502, "s": 1451, "text": "Note that the new date is created at 0000 hrs UTC." }, { "code": null, "e": 1664, "s": 1502, "text": "If you need to parse any other date formats, you can check out https://developer.mozilla.org as it provides details about using different formats to parse dates." } ]
How to create text file and insert data to that file on Android?
This example demonstrates how to create text file and insert data to that file on Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:background="#008080" android:padding="5dp" android:text="Android Write Text to a File" android:textColor="#fff" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_below="@+id/textView1" android:layout_marginTop="22dp" android:ems="10" android:layout_margin="5dp"> <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_below="@+id/editText1" android:text="Write Text into File" android:onClick="WriteBtn" android:layout_margin="5dp"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java package com.example.sample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import android.app.Activity; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText textmsg; static final int READ_BLOCK_SIZE=100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textmsg=(EditText)findViewById(R.id.editText1); } // write text to file public void WriteBtn(View v) { // add-write text into file try { FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE); OutputStreamWriter outputWriter=new OutputStreamWriter(fileout); outputWriter.write(textmsg.getText().toString()); outputWriter.close(); //display file saved message Toast.makeText(getBaseContext(), "File saved successfully!", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } } Step 4 − Add the following code to manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1153, "s": 1062, "text": "This example demonstrates how to create text file and insert data to that file on Android." }, { "code": null, "e": 1282, "s": 1153, "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": 1347, "s": 1282, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2836, "s": 1347, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentRight=\"true\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"Android Write Text to a File\"\n android:textColor=\"#fff\" />\n <EditText\n android:id=\"@+id/editText1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentRight=\"true\"\n android:layout_below=\"@+id/textView1\"\n android:layout_marginTop=\"22dp\"\n android:ems=\"10\"\n android:layout_margin=\"5dp\">\n <requestFocus />\n </EditText>\n <Button\n android:id=\"@+id/button1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentRight=\"true\"\n android:layout_below=\"@+id/editText1\"\n android:text=\"Write Text into File\"\n android:onClick=\"WriteBtn\"\n android:layout_margin=\"5dp\"/>\n</RelativeLayout>" }, { "code": null, "e": 2893, "s": 2836, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4149, "s": 2893, "text": "package com.example.sample;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.InputStreamReader;\nimport java.io.OutputStreamWriter;\nimport android.app.Activity;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n EditText textmsg;\n static final int READ_BLOCK_SIZE=100;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textmsg=(EditText)findViewById(R.id.editText1);\n }\n // write text to file\n public void WriteBtn(View v) {\n // add-write text into file\n try {\n FileOutputStream fileout=openFileOutput(\"mytextfile.txt\", MODE_PRIVATE);\n OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);\n outputWriter.write(textmsg.getText().toString());\n outputWriter.close();\n //display file saved message\n Toast.makeText(getBaseContext(), \"File saved successfully!\",\n Toast.LENGTH_SHORT).show();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 4214, "s": 4149, "text": "Step 4 − Add the following code to manifests/AndroidManifest.xml" }, { "code": null, "e": 4888, "s": 4214, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5236, "s": 4888, "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": 5276, "s": 5236, "text": "Click here to download the project code" } ]
Chef - Cookbooks
Cookbooks are fundamental working units of Chef, which consists of all the details related to working units, having the capability to modify configuration and the state of any system configured as a node on Chef infrastructure. Cookbooks can perform multiple tasks. Cookbooks contain values about the desired state of node. This is achieved in Chef by using the desired external libraries. Recipes Metadata Attributes Resources Templates Libraries Anything else that helps to create a system There are two ways to dynamically create a cookbook. Using chef command Using knife utility To create an empty cookbook using Chef command, run the following command. C:\Users\vipinkumarm>chef generate cookbook <Cookbook Name> C:\Users\vipinkumarm>chef generate cookbook VTest Installing Cookbook Gems: Compiling Cookbooks... Recipe: code_generator::cookbook * directory[C:/Users/vipinkumarm/VTest] action create - create new directory C:/Users/vipinkumarm/VTest * template[C:/Users/vipinkumarm/VTest/metadata.rb] action create_if_missing - create new file C:/Users/vipinkumarm/VTest/metadata.rb - update content in file C:/Users/vipinkumarm/VTest/metadata.rb from none to 4b9435 (diff output suppressed by config) * template[C:/Users/vipinkumarm/VTest/README.md] action create_if_missing - create new file C:/Users/vipinkumarm/VTest/README.md - update content in file C:/Users/vipinkumarm/VTest/README.md from none to 482077 (diff output suppressed by config) * cookbook_file[C:/Users/vipinkumarm/VTest/chefignore] action create - create new file C:/Users/vipinkumarm/VTest/chefignore - update content in file C:/Users/vipinkumarm/VTest/chefignore from none to 15fac5 (diff output suppressed by config) * cookbook_file[C:/Users/vipinkumarm/VTest/Berksfile] action create_if_missing - create new file C:/Users/vipinkumarm/VTest/Berksfile - update content in file C:/Users/vipinkumarm/VTest/Berksfile from none to 9f08dc (diff output suppressed by config) * template[C:/Users/vipinkumarm/VTest/.kitchen.yml] action create_if_missing - create new file C:/Users/vipinkumarm/VTest/.kitchen.yml - update content in file C:/Users/vipinkumarm/VTest/.kitchen.yml from none to 93c5bd (diff output suppressed by config) * directory[C:/Users/vipinkumarm/VTest/test/integration/default/serverspec] action create - create new directory C:/Users/vipinkumarm/VTest/test/integration/default/serverspec * directory[C:/Users/vipinkumarm/VTest/test/integration/helpers/serverspec] action create - create new directory C:/Users/vipinkumarm/VTest/test/integration/helpers/serverspec * cookbook_file [C:/Users/vipinkumarm/VTest/test/integration/helpers/serverspec/sp ec_helper.rb] action create_if_missing - create new file C:/Users/vipinkumarm/VTest/test/integration/helpers/serverspec/spec_helper.rb - update content in file C:/Users/vipinkumarm/VTest/test/integration/helpers/serverspec/spec_helper.rb from none to d85df4 (diff output suppressed by config) * template [C:/Users/vipinkumarm/VTest/test/integration/default/serverspec/default _spec.rb] action create_if_missing - create new file C:/Users/vipinkumarm/VTest/test/integration/default/serverspec/default_spec.rb - update content in file C:/Users/vipinkumarm/VTest/test/integration/default/serverspec/default_spec.rb from none to 758b94 (diff output suppressed by config) * directory[C:/Users/vipinkumarm/VTest/spec/unit/recipes] action create - create new directory C:/Users/vipinkumarm/VTest/spec/unit/recipes * cookbook_file[C:/Users/vipinkumarm/VTest/spec/spec_helper.rb] action create_if_missing - create new file C:/Users/vipinkumarm/VTest/spec/spec_helper.rb - update content in file C:/Users/vipinkumarm/VTest/spec/spec_helper.rb from none to 587075 (diff output suppressed by config) * template[C:/Users/vipinkumarm/VTest/spec/unit/recipes/default_spec.rb] action create_if_missing - create new file C:/Users/vipinkumarm/VTest/spec/unit/recipes/default_spec.rb - update content in file C:/Users/vipinkumarm/VTest/spec/unit/recipes/default_spec.rb from none to 779503 (diff output suppressed by config) - create new file C:/Users/vipinkumarm/VTest/recipes/default.rb - update content in file C:/Users/vipinkumarm/VTest/recipes/default.rb from none to 8cc381 (diff output suppressed by config) * cookbook_file[C:/Users/vipinkumarm/VTest/.gitignore] action create - create new file C:/Users/vipinkumarm/VTest/.gitignore - update content in file C:/Users/vipinkumarm/VTest/.gitignore from none to 33d469 (diff output suppressed by config) The cookbook structure with the name VTest will be created in the directory and following will be the structure for the same. Use the following command to create a cookbook using knife utility. C:\Users\vipinkumarm\VTest>knife cookbook create VTest2 WARNING: No knife configuration file found ** Creating cookbook VTest2 in C:/chef/cookbooks ** Creating README for cookbook: VTest2 ** Creating CHANGELOG for cookbook: VTest2 ** Creating metadata for cookbook: VTest2 Following will be the structure of the cookbook. Print Add Notes Bookmark this page
[ { "code": null, "e": 2770, "s": 2380, "text": "Cookbooks are fundamental working units of Chef, which consists of all the details related to working units, having the capability to modify configuration and the state of any system configured as a node on Chef infrastructure. Cookbooks can perform multiple tasks. Cookbooks contain values about the desired state of node. This is achieved in Chef by using the desired external libraries." }, { "code": null, "e": 2778, "s": 2770, "text": "Recipes" }, { "code": null, "e": 2787, "s": 2778, "text": "Metadata" }, { "code": null, "e": 2798, "s": 2787, "text": "Attributes" }, { "code": null, "e": 2808, "s": 2798, "text": "Resources" }, { "code": null, "e": 2818, "s": 2808, "text": "Templates" }, { "code": null, "e": 2829, "s": 2818, "text": "Libraries " }, { "code": null, "e": 2873, "s": 2829, "text": "Anything else that helps to create a system" }, { "code": null, "e": 2926, "s": 2873, "text": "There are two ways to dynamically create a cookbook." }, { "code": null, "e": 2945, "s": 2926, "text": "Using chef command" }, { "code": null, "e": 2965, "s": 2945, "text": "Using knife utility" }, { "code": null, "e": 3040, "s": 2965, "text": "To create an empty cookbook using Chef command, run the following command." }, { "code": null, "e": 7307, "s": 3040, "text": "C:\\Users\\vipinkumarm>chef generate cookbook <Cookbook Name> \nC:\\Users\\vipinkumarm>chef generate cookbook VTest\nInstalling Cookbook Gems:\n\nCompiling Cookbooks...\nRecipe: code_generator::cookbook\n * directory[C:/Users/vipinkumarm/VTest] action create\n - create new directory C:/Users/vipinkumarm/VTest\n \n * template[C:/Users/vipinkumarm/VTest/metadata.rb] action create_if_missing\n - create new file C:/Users/vipinkumarm/VTest/metadata.rb\n - update content in file C:/Users/vipinkumarm/VTest/metadata.rb \n from none to 4b9435 (diff output suppressed by config)\n\n * template[C:/Users/vipinkumarm/VTest/README.md] action create_if_missing\n - create new file C:/Users/vipinkumarm/VTest/README.md\n - update content in file C:/Users/vipinkumarm/VTest/README.md \n from none to 482077 (diff output suppressed by config)\n\n * cookbook_file[C:/Users/vipinkumarm/VTest/chefignore] action create\n - create new file C:/Users/vipinkumarm/VTest/chefignore\n - update content in file C:/Users/vipinkumarm/VTest/chefignore \n from none to 15fac5 (diff output suppressed by config)\n \n * cookbook_file[C:/Users/vipinkumarm/VTest/Berksfile] action create_if_missing\n - create new file C:/Users/vipinkumarm/VTest/Berksfile\n - update content in file C:/Users/vipinkumarm/VTest/Berksfile \n from none to 9f08dc (diff output suppressed by config)\n\n * template[C:/Users/vipinkumarm/VTest/.kitchen.yml] action create_if_missing\n - create new file C:/Users/vipinkumarm/VTest/.kitchen.yml\n - update content in file C:/Users/vipinkumarm/VTest/.kitchen.yml \n from none to 93c5bd (diff output suppressed by config)\n\n * directory[C:/Users/vipinkumarm/VTest/test/integration/default/serverspec]\n action create\n - create new directory\n C:/Users/vipinkumarm/VTest/test/integration/default/serverspec\n \n * directory[C:/Users/vipinkumarm/VTest/test/integration/helpers/serverspec]\n action create\n - create new directory\n C:/Users/vipinkumarm/VTest/test/integration/helpers/serverspec\n \n * cookbook_file\n [C:/Users/vipinkumarm/VTest/test/integration/helpers/serverspec/sp ec_helper.rb]\n action create_if_missing\n - create new file\n C:/Users/vipinkumarm/VTest/test/integration/helpers/serverspec/spec_helper.rb\n - update content in file\n C:/Users/vipinkumarm/VTest/test/integration/helpers/serverspec/spec_helper.rb\n from none to d85df4 (diff output suppressed by config)\n \n * template\n [C:/Users/vipinkumarm/VTest/test/integration/default/serverspec/default _spec.rb]\n action create_if_missing\n - create new file\n C:/Users/vipinkumarm/VTest/test/integration/default/serverspec/default_spec.rb\n - update content in file\n C:/Users/vipinkumarm/VTest/test/integration/default/serverspec/default_spec.rb\n from none to 758b94 (diff output suppressed by config)\n \n * directory[C:/Users/vipinkumarm/VTest/spec/unit/recipes] action create\n - create new directory C:/Users/vipinkumarm/VTest/spec/unit/recipes\n \n * cookbook_file[C:/Users/vipinkumarm/VTest/spec/spec_helper.rb]\n action create_if_missing\n - create new file C:/Users/vipinkumarm/VTest/spec/spec_helper.rb\n - update content in file C:/Users/vipinkumarm/VTest/spec/spec_helper.rb\n from none to 587075 (diff output suppressed by config)\n\n * template[C:/Users/vipinkumarm/VTest/spec/unit/recipes/default_spec.rb]\n action create_if_missing\n - create new file C:/Users/vipinkumarm/VTest/spec/unit/recipes/default_spec.rb\n - update content in file \n C:/Users/vipinkumarm/VTest/spec/unit/recipes/default_spec.rb\n from none to 779503 (diff output suppressed by config)\n - create new file C:/Users/vipinkumarm/VTest/recipes/default.rb\n - update content in file C:/Users/vipinkumarm/VTest/recipes/default.rb\n from none to 8cc381 (diff output suppressed by config)\n\n * cookbook_file[C:/Users/vipinkumarm/VTest/.gitignore] action create\n - create new file C:/Users/vipinkumarm/VTest/.gitignore\n - update content in file C:/Users/vipinkumarm/VTest/.gitignore from none to 33d469\n (diff output suppressed by config)" }, { "code": null, "e": 7433, "s": 7307, "text": "The cookbook structure with the name VTest will be created in the directory and following will be the structure for the same." }, { "code": null, "e": 7501, "s": 7433, "text": "Use the following command to create a cookbook using knife utility." }, { "code": null, "e": 7781, "s": 7501, "text": "C:\\Users\\vipinkumarm\\VTest>knife cookbook create VTest2 \nWARNING: No knife configuration file found \n** Creating cookbook VTest2 in C:/chef/cookbooks \n** Creating README for cookbook: VTest2 \n** Creating CHANGELOG for cookbook: VTest2 \n** Creating metadata for cookbook: VTest2 \n" }, { "code": null, "e": 7830, "s": 7781, "text": "Following will be the structure of the cookbook." }, { "code": null, "e": 7837, "s": 7830, "text": " Print" }, { "code": null, "e": 7848, "s": 7837, "text": " Add Notes" } ]
Auto-Keras, or How You can Create a Deep Learning Model in 4 Lines of Code | by Favio Vázquez | Towards Data Science
Before starting, a great quote by Matthew Mayo about what AutoML is not: AutoML is not automated data science. While there is undoubtedly overlap, machine learning is but one of many tools in the data science toolkit, and its use does not actually factor in to all data science tasks. For example, if prediction will be part of a given data science task, machine learning will be a useful component; however, machine learning may not play in to a descriptive analytics task at all. Ok so, what is automated machine learning then? In simple words is a way of automating the tasks of (https://www.automl.org/automl/): Preprocess and clean the data. Select and construct appropriate features. Select an appropriate model family. Optimize model hyperparameters. Postprocess machine learning models. Critically analyze the results obtained. Now that we are clear on what is AutoML now, what is Keras? Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano. It was developed with a focus on enabling fast experimentation. Being able to go from idea to result with the least possible delay is key to doing good research. This was created by François Chollet and was the first serious step for making Deep Learning easy for the masses. TensorFlow has a Python API which is not that hard, but Keras made really easy to get into Deep Learning for lots of people. It should be noted that Keras is now officially a part of Tensorflow: www.tensorflow.org Great. Now we know what is Keras and AutoML, let’s combine them. Auto-Keras is an open source software library for automated machine learning. Auto-Keras provides functions to automatically search for architecture and hyperparameters of deep learning models. Installation pip install autokeras Usage For the usage I’m going to use an example they have on their web. But first let’s compare how we can do the same with different tools. I’ll use the famous and sometimes hated MNIST dataset. MNIST is a simple computer vision dataset. It consists of images of handwritten digits like these: It also includes labels for each image, telling us which digit it is. Resources: github.com www.tensorflow.org Not so easy, but very well explained in the example. TensorFlow is not meant to be the easiest tool for deep learning, but a fast an reliable one. With eager execution the code is much more readable. Resources: github.com Resources: github.com You can see that until now the Keras is the simpler package for running this example. It’s a great package with awesome features to got from zero to a model in just minutes. But now, the cherry on the cake. Yep, that is all. Pretty simple right? You just need an ImageClassifier, then fit the data and evaluate it. You have a final_fit there too, and it’s running a final training after found the best architecture. For now you have the ImageClassifier, the BayesianSearcher, a Graph module, a PreProcessor, a LayerTransformer, a NetTransformer, a ClassifierGenerator and some utilities. This is an evolving package, please take a look at the creators disclaimer: Please note that this is a pre-release version of the Auto-Keras which is still undergoing final testing before its official release. The website, its software and all content found on it are provided on an “as is” and “as available” basis. Auto-Keras does notgive any warranties, whether express or implied, as to the suitability or usability of the website, its software or any of its content. Auto-Keras will not be liable for any loss, whether such loss is direct, indirect, special or consequential, suffered by any party as a result of their use of the libraries or content. Any usage of the libraries is done at the user’s own risk and the user will be solely responsible for any damage to any computer system or loss of data that results from such activities. Should you encounter any bugs, glitches, lack of functionality or other problems on the website, please let us know immediately so we can rectify these accordingly. Your help in this regard is greatly appreciated. Either way is an amazing package that is very useful and it will be in the future. For more on AutoML and packages see this: www.automl.org www.kdnuggets.com www.kdnuggets.com Oh! If you want an even simple way for doing AutoML and Deep Learning without coding at all check out Deep Cognition and my posts on it:
[ { "code": null, "e": 244, "s": 171, "text": "Before starting, a great quote by Matthew Mayo about what AutoML is not:" }, { "code": null, "e": 653, "s": 244, "text": "AutoML is not automated data science. While there is undoubtedly overlap, machine learning is but one of many tools in the data science toolkit, and its use does not actually factor in to all data science tasks. For example, if prediction will be part of a given data science task, machine learning will be a useful component; however, machine learning may not play in to a descriptive analytics task at all." }, { "code": null, "e": 787, "s": 653, "text": "Ok so, what is automated machine learning then? In simple words is a way of automating the tasks of (https://www.automl.org/automl/):" }, { "code": null, "e": 818, "s": 787, "text": "Preprocess and clean the data." }, { "code": null, "e": 861, "s": 818, "text": "Select and construct appropriate features." }, { "code": null, "e": 897, "s": 861, "text": "Select an appropriate model family." }, { "code": null, "e": 929, "s": 897, "text": "Optimize model hyperparameters." }, { "code": null, "e": 966, "s": 929, "text": "Postprocess machine learning models." }, { "code": null, "e": 1007, "s": 966, "text": "Critically analyze the results obtained." }, { "code": null, "e": 1067, "s": 1007, "text": "Now that we are clear on what is AutoML now, what is Keras?" }, { "code": null, "e": 1352, "s": 1067, "text": "Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano. It was developed with a focus on enabling fast experimentation. Being able to go from idea to result with the least possible delay is key to doing good research." }, { "code": null, "e": 1467, "s": 1352, "text": "This was created by François Chollet and was the first serious step for making Deep Learning easy for the masses." }, { "code": null, "e": 1662, "s": 1467, "text": "TensorFlow has a Python API which is not that hard, but Keras made really easy to get into Deep Learning for lots of people. It should be noted that Keras is now officially a part of Tensorflow:" }, { "code": null, "e": 1681, "s": 1662, "text": "www.tensorflow.org" }, { "code": null, "e": 1940, "s": 1681, "text": "Great. Now we know what is Keras and AutoML, let’s combine them. Auto-Keras is an open source software library for automated machine learning. Auto-Keras provides functions to automatically search for architecture and hyperparameters of deep learning models." }, { "code": null, "e": 1953, "s": 1940, "text": "Installation" }, { "code": null, "e": 1975, "s": 1953, "text": "pip install autokeras" }, { "code": null, "e": 1981, "s": 1975, "text": "Usage" }, { "code": null, "e": 2171, "s": 1981, "text": "For the usage I’m going to use an example they have on their web. But first let’s compare how we can do the same with different tools. I’ll use the famous and sometimes hated MNIST dataset." }, { "code": null, "e": 2270, "s": 2171, "text": "MNIST is a simple computer vision dataset. It consists of images of handwritten digits like these:" }, { "code": null, "e": 2340, "s": 2270, "text": "It also includes labels for each image, telling us which digit it is." }, { "code": null, "e": 2351, "s": 2340, "text": "Resources:" }, { "code": null, "e": 2362, "s": 2351, "text": "github.com" }, { "code": null, "e": 2381, "s": 2362, "text": "www.tensorflow.org" }, { "code": null, "e": 2581, "s": 2381, "text": "Not so easy, but very well explained in the example. TensorFlow is not meant to be the easiest tool for deep learning, but a fast an reliable one. With eager execution the code is much more readable." }, { "code": null, "e": 2592, "s": 2581, "text": "Resources:" }, { "code": null, "e": 2603, "s": 2592, "text": "github.com" }, { "code": null, "e": 2614, "s": 2603, "text": "Resources:" }, { "code": null, "e": 2625, "s": 2614, "text": "github.com" }, { "code": null, "e": 2799, "s": 2625, "text": "You can see that until now the Keras is the simpler package for running this example. It’s a great package with awesome features to got from zero to a model in just minutes." }, { "code": null, "e": 2832, "s": 2799, "text": "But now, the cherry on the cake." }, { "code": null, "e": 3041, "s": 2832, "text": "Yep, that is all. Pretty simple right? You just need an ImageClassifier, then fit the data and evaluate it. You have a final_fit there too, and it’s running a final training after found the best architecture." }, { "code": null, "e": 3289, "s": 3041, "text": "For now you have the ImageClassifier, the BayesianSearcher, a Graph module, a PreProcessor, a LayerTransformer, a NetTransformer, a ClassifierGenerator and some utilities. This is an evolving package, please take a look at the creators disclaimer:" }, { "code": null, "e": 4271, "s": 3289, "text": "Please note that this is a pre-release version of the Auto-Keras which is still undergoing final testing before its official release. The website, its software and all content found on it are provided on an “as is” and “as available” basis. Auto-Keras does notgive any warranties, whether express or implied, as to the suitability or usability of the website, its software or any of its content. Auto-Keras will not be liable for any loss, whether such loss is direct, indirect, special or consequential, suffered by any party as a result of their use of the libraries or content. Any usage of the libraries is done at the user’s own risk and the user will be solely responsible for any damage to any computer system or loss of data that results from such activities. Should you encounter any bugs, glitches, lack of functionality or other problems on the website, please let us know immediately so we can rectify these accordingly. Your help in this regard is greatly appreciated." }, { "code": null, "e": 4396, "s": 4271, "text": "Either way is an amazing package that is very useful and it will be in the future. For more on AutoML and packages see this:" }, { "code": null, "e": 4411, "s": 4396, "text": "www.automl.org" }, { "code": null, "e": 4429, "s": 4411, "text": "www.kdnuggets.com" }, { "code": null, "e": 4447, "s": 4429, "text": "www.kdnuggets.com" } ]
XPath - Wildcard
XPath defines the following wildcards on nodes to be used with the XPath expressions. * used to match any node. . used to match the current node in context. @* used to match any attribute node() used to match node of any type This example creates a table of <student> element with their details, by iterating over each student. <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> <?xml version = "1.0" encoding = "UTF-8"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "/"> <html> <body> <h2>Students</h2> <xsl:apply-templates select = "class/*" /> </body> </html> </xsl:template> <xsl:template match = "class/*"> <xsl:apply-templates select = "@rollno" /> <xsl:apply-templates select = "firstname" /> <xsl:apply-templates select = "lastname" /> <xsl:apply-templates select = "nickname" /> <xsl:apply-templates select = "marks" /> <br /> </xsl:template> <xsl:template match = "@rollno"> <span style = "font-size = 22px;"> <xsl:value-of select = "." /> </span> <br /> </xsl:template> <xsl:template match = "firstname"> First Name:<span style = "color:blue;"> <xsl:value-of select = "." /> </span> <br /> </xsl:template> <xsl:template match = "lastname"> Last Name:<span style = "color:green;"> <xsl:value-of select = "." /> </span> <br /> </xsl:template> <xsl:template match = "nickname"> Nick Name:<span style = "color:red;"> <xsl:value-of select = "." /> </span> <br /> </xsl:template> <xsl:template match = "marks"> Marks:<span style = "color:gray;"> <xsl:value-of select = "." /> </span> <br /> </xsl:template> </xsl:stylesheet> 90 Lectures 20 hours Arun Motoori 23 Lectures 8 hours Sanjay Kumar 13 Lectures 1.5 hours Sanjay Kumar 24 Lectures 1.5 hours Sanjay Kumar 47 Lectures 3 hours Krishna Sakinala Print Add Notes Bookmark this page
[ { "code": null, "e": 1815, "s": 1729, "text": "XPath defines the following wildcards on nodes to be used with the XPath expressions." }, { "code": null, "e": 1817, "s": 1815, "text": "*" }, { "code": null, "e": 1841, "s": 1817, "text": "used to match any node." }, { "code": null, "e": 1843, "s": 1841, "text": "." }, { "code": null, "e": 1886, "s": 1843, "text": "used to match the current node in context." }, { "code": null, "e": 1889, "s": 1886, "text": "@*" }, { "code": null, "e": 1917, "s": 1889, "text": "used to match any attribute" }, { "code": null, "e": 1924, "s": 1917, "text": "node()" }, { "code": null, "e": 1955, "s": 1924, "text": "used to match node of any type" }, { "code": null, "e": 2057, "s": 1955, "text": "This example creates a table of <student> element with their details, by iterating over each student." }, { "code": null, "e": 2659, "s": 2057, "text": "<?xml version = \"1.0\"?>\n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?>\n<class>\n <student rollno = \"393\">\n <firstname>Dinkar</firstname>\n <lastname>Kad</lastname>\n <nickname>Dinkar</nickname>\n <marks>85</marks>\n </student>\n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>Vinni</nickname>\n <marks>95</marks>\n </student>\n <student rollno = \"593\">\n <firstname>Jasvir</firstname>\n <lastname>Singh</lastname>\n <nickname>Jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 4150, "s": 2659, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<xsl:stylesheet version = \"1.0\"\n xmlns:xsl = \"http://www.w3.org/1999/XSL/Transform\">\n\t\n <xsl:template match = \"/\">\n <html>\n <body>\n <h2>Students</h2>\n <xsl:apply-templates select = \"class/*\" />\n </body>\n </html>\n </xsl:template>\n\n <xsl:template match = \"class/*\">\n <xsl:apply-templates select = \"@rollno\" />\n <xsl:apply-templates select = \"firstname\" />\n <xsl:apply-templates select = \"lastname\" />\n <xsl:apply-templates select = \"nickname\" />\n <xsl:apply-templates select = \"marks\" />\n <br />\n </xsl:template>\n\n <xsl:template match = \"@rollno\">\n <span style = \"font-size = 22px;\">\n <xsl:value-of select = \".\" />\n </span>\n <br />\n </xsl:template>\n\n <xsl:template match = \"firstname\">\n First Name:<span style = \"color:blue;\">\n <xsl:value-of select = \".\" />\n </span>\n <br />\n </xsl:template>\n\n <xsl:template match = \"lastname\">\n Last Name:<span style = \"color:green;\">\n <xsl:value-of select = \".\" />\n </span>\n <br />\n </xsl:template>\n\n <xsl:template match = \"nickname\">\n Nick Name:<span style = \"color:red;\">\n <xsl:value-of select = \".\" />\n </span>\n <br />\n </xsl:template>\n\n <xsl:template match = \"marks\">\n Marks:<span style = \"color:gray;\">\n <xsl:value-of select = \".\" />\n </span>\n <br />\n </xsl:template>\n\n</xsl:stylesheet>" }, { "code": null, "e": 4184, "s": 4150, "text": "\n 90 Lectures \n 20 hours \n" }, { "code": null, "e": 4198, "s": 4184, "text": " Arun Motoori" }, { "code": null, "e": 4231, "s": 4198, "text": "\n 23 Lectures \n 8 hours \n" }, { "code": null, "e": 4245, "s": 4231, "text": " Sanjay Kumar" }, { "code": null, "e": 4280, "s": 4245, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4294, "s": 4280, "text": " Sanjay Kumar" }, { "code": null, "e": 4329, "s": 4294, "text": "\n 24 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4343, "s": 4329, "text": " Sanjay Kumar" }, { "code": null, "e": 4376, "s": 4343, "text": "\n 47 Lectures \n 3 hours \n" }, { "code": null, "e": 4394, "s": 4376, "text": " Krishna Sakinala" }, { "code": null, "e": 4401, "s": 4394, "text": " Print" }, { "code": null, "e": 4412, "s": 4401, "text": " Add Notes" } ]
Apache Derby - Retrieve Data
The SELECT statement is used to retrieve data from a table. This returns the data in the form of a table known as result set. Following is the syntax of the SELECT statement − ij> SELECT column_name, column_name, ... FROM table_name; Or, Ij>SELECT * from table_name Let us suppose we have a table named Employees in the database as shown below − ij> CREATE TABLE Employees ( Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, Name VARCHAR(255), Salary INT NOT NULL, Location VARCHAR(255), PRIMARY KEY (Id) ); > > > > > > > 0 rows inserted/updated/deleted And, inserted four records in it as shown below − ij> INSERT INTO Employees (Name, Salary, Location) VALUES ('Amit', 30000, 'Hyderabad'), ('Kalyan', 40000, 'Vishakhapatnam'), ('Renuka', 50000, 'Delhi'), ('Archana', 15000, 'Mumbai'); > > > > 4 rows inserted/updated/deleted The following SQL statement retrieves the name, age and salary details of all the employees in the table: ij> SELECT Id, Name, Salary FROM Employees; The output of this query is − ID|NAME |SALARY ------------------------------------------------------------------------ 1 |Amit |30000 2 |Kalyan |40000 3 |Renuka |50000 4 |Archana|15000 4 rows selected If you want to get all the records of this table at once, use * instead of the names of the columns. ij> select * from Employees; This will produce the following result − ID |NAME |SALARY |LOCATION ------------------------------------------------------------------ 1 |Amit |30000 |Hyderabad 2 |Kalyan |40000 |Vishakhapatnam 3 |Renuka |50000 |Delhi 4 |Archana |15000 |Mumbai 4 rows selected This section teaches you how to Retrieve data from a table in Apache Derby database using JDBC application. If you want to request the Derby network server using network client, make sure that the server is up and running. The class name for the Network client driver is org.apache.derby.jdbc.ClientDriver and the URL is jdbc:derby://localhost:1527DATABASE_NAME;create=true;user=USER_NAME;passw ord=PASSWORD" Follow the steps given below to Retrieve data from a table in Apache Derby − To communicate with the database, first of all, you need to register the driver. The forName() method of the class Class accepts a String value representing a class name loads it in to the memory, which automatically registers it. Register the driver using this method. In general, the first step we do to communicate to the database is to connect with it. The Connection class represents the physical connection with a database server. You can create a connection object by invoking the getConnection() method of the DriverManager class. Create a connection using this method. You need to create a Statement or PreparedStatement or, CallableStatement objects to send SQL statements to the database. You can create these using the methods createStatement(), prepareStatement() and, prepareCall() respectively. Create either of these objects using the appropriate method. After creating a statement, you need to execute it. The Statement class provides various methods to execute a query like the execute() method to execute a statement that returns more than one result set. The executeUpdate() method executes queries like INSERT, UPDATE, DELETE. The executeQuery() method to results that returns data etc. Use either of these methods and execute the statement created previously. Following JDBC example demonstrates how to Retrieve data from a table in Apache Derby using JDBC program. Here, we are connecting to a database named sampleDB (will create if it does not exist) using the embedded driver. The executeQuery() method returns a ResultSet object which holds the result of the statement. Initially the result set pointer will be at the first record, you can print the contents of the ResultSet object using its next() and getXXX() methods. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class RetrieveData { public static void main(String args[]) throws SQLException, ClassNotFoundException { //Registering the driver Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); //Getting the Connection object String URL = "jdbc:derby:sampleDB;create=true"; Connection conn = DriverManager.getConnection(URL); //Creating the Statement object 4Statement stmt = conn.createStatement(); //Creating a table and populating it String query = "CREATE TABLE Employees(" + "Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, " + "Name VARCHAR(255), Salary INT NOT NULL, " + "Location VARCHAR(255), " + "PRIMARY KEY (Id))"; String query = "INSERT INTO Employees(" + "Name, Salary, Location) VALUES " + "('Amit', 30000, 'Hyderabad'), " + "('Kalyan', 40000, 'Vishakhapatnam'), " + "('Renuka', 50000, 'Delhi'), " + "('Archana', 15000, 'Mumbai'), " + "('Trupthi', 45000, 'Kochin'), " + "('Suchatra', 33000, 'Pune'), " + "('Rahul', 39000, 'Lucknow'), " + "('Trupti', 45000, 'Kochin')"; //Executing the query String query = "SELECT Id, Name, Salary FROM Employees"; ResultSet rs = stmt.executeQuery(query); while(rs.next()) { System.out.println("Id: "+rs.getString("Id")); System.out.println("Name: "+rs.getString("Name")); System.out.println("Salary: "+rs.getString("Salary")); System.out.println(" "); } } } On executing the above program, you will get the following output. Id: 1 Name: Amit Salary: 30000 Id: 2 Name: Kalyan Salary: 43000 Id: 3 Name: Renuka Salary: 50000 Id: 4 Name: Archana Salary: 15000 Id: 5 Name: Trupthi Salary: 45000 Id: 6 Name: Suchatra Salary: 33000 Id: 7 Name: Rahul Salary: 39000 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2306, "s": 2180, "text": "The SELECT statement is used to retrieve data from a table. This returns the data in the form of a table known as result set." }, { "code": null, "e": 2356, "s": 2306, "text": "Following is the syntax of the SELECT statement −" }, { "code": null, "e": 2447, "s": 2356, "text": "ij> SELECT column_name, column_name, ... FROM table_name;\nOr,\nIj>SELECT * from table_name\n" }, { "code": null, "e": 2527, "s": 2447, "text": "Let us suppose we have a table named Employees in the database as shown below −" }, { "code": null, "e": 2747, "s": 2527, "text": "ij> CREATE TABLE Employees (\n Id INT NOT NULL GENERATED ALWAYS AS IDENTITY,\n Name VARCHAR(255),\n Salary INT NOT NULL,\n Location VARCHAR(255),\n PRIMARY KEY (Id)\n);\n> > > > > > > 0 rows inserted/updated/deleted\n" }, { "code": null, "e": 2797, "s": 2747, "text": "And, inserted four records in it as shown below −" }, { "code": null, "e": 3033, "s": 2797, "text": "ij> INSERT INTO Employees (Name, Salary, Location) VALUES\n ('Amit', 30000, 'Hyderabad'),\n ('Kalyan', 40000, 'Vishakhapatnam'),\n ('Renuka', 50000, 'Delhi'),\n ('Archana', 15000, 'Mumbai');\n> > > > 4 rows inserted/updated/deleted\n" }, { "code": null, "e": 3139, "s": 3033, "text": "The following SQL statement retrieves the name, age and salary details of all the employees in the table:" }, { "code": null, "e": 3183, "s": 3139, "text": "ij> SELECT Id, Name, Salary FROM Employees;" }, { "code": null, "e": 3213, "s": 3183, "text": "The output of this query is −" }, { "code": null, "e": 3389, "s": 3213, "text": "ID|NAME |SALARY\n------------------------------------------------------------------------\n1 |Amit |30000\n2 |Kalyan |40000\n3 |Renuka |50000\n4 |Archana|15000\n4 rows selected\n" }, { "code": null, "e": 3490, "s": 3389, "text": "If you want to get all the records of this table at once, use * instead of the names of the columns." }, { "code": null, "e": 3519, "s": 3490, "text": "ij> select * from Employees;" }, { "code": null, "e": 3560, "s": 3519, "text": "This will produce the following result −" }, { "code": null, "e": 3796, "s": 3560, "text": "ID |NAME |SALARY |LOCATION\n------------------------------------------------------------------\n1 |Amit |30000 |Hyderabad\n2 |Kalyan |40000 |Vishakhapatnam\n3 |Renuka |50000 |Delhi\n4 |Archana |15000 |Mumbai\n4 rows selected\n" }, { "code": null, "e": 3904, "s": 3796, "text": "This section teaches you how to Retrieve data from a table in Apache Derby database using JDBC application." }, { "code": null, "e": 4205, "s": 3904, "text": "If you want to request the Derby network server using network client, make sure that the server is up and running. The class name for the Network client driver is org.apache.derby.jdbc.ClientDriver and the URL is jdbc:derby://localhost:1527DATABASE_NAME;create=true;user=USER_NAME;passw ord=PASSWORD\"" }, { "code": null, "e": 4282, "s": 4205, "text": "Follow the steps given below to Retrieve data from a table in Apache Derby −" }, { "code": null, "e": 4552, "s": 4282, "text": "To communicate with the database, first of all, you need to register the driver. The forName() method of the class Class accepts a String value representing a class name loads it in to the memory, which automatically registers it. Register the driver using this method." }, { "code": null, "e": 4860, "s": 4552, "text": "In general, the first step we do to communicate to the database is to connect with it. The Connection class represents the physical connection with a database server. You can create a connection object by invoking the getConnection() method of the DriverManager class. Create a connection using this method." }, { "code": null, "e": 5153, "s": 4860, "text": "You need to create a Statement or PreparedStatement or, CallableStatement objects to send SQL statements to the database. You can create these using the methods createStatement(), prepareStatement() and, prepareCall() respectively. Create either of these objects using the appropriate method." }, { "code": null, "e": 5564, "s": 5153, "text": "After creating a statement, you need to execute it. The Statement class provides various methods to execute a query like the execute() method to execute a statement that returns more than one result set. The executeUpdate() method executes queries like INSERT, UPDATE, DELETE. The executeQuery() method to results that returns data etc. Use either of these methods and execute the statement created previously." }, { "code": null, "e": 5785, "s": 5564, "text": "Following JDBC example demonstrates how to Retrieve data from a table in Apache Derby using JDBC program. Here, we are connecting to a database named sampleDB (will create if it does not exist) using the embedded driver." }, { "code": null, "e": 6031, "s": 5785, "text": "The executeQuery() method returns a ResultSet object which holds the result of the statement. Initially the result set pointer will be at the first record, you can print the contents of the ResultSet object using its next() and getXXX() methods." }, { "code": null, "e": 7735, "s": 6031, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class RetrieveData {\n public static void main(String args[]) throws SQLException,\n ClassNotFoundException {\n //Registering the driver\n Class.forName(\"org.apache.derby.jdbc.EmbeddedDriver\");\n //Getting the Connection object\n String URL = \"jdbc:derby:sampleDB;create=true\";\n Connection conn = DriverManager.getConnection(URL);\n\n //Creating the Statement object\n 4Statement stmt = conn.createStatement();\n\n //Creating a table and populating it\n String query = \"CREATE TABLE Employees(\"\n + \"Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, \"\n + \"Name VARCHAR(255), Salary INT NOT NULL, \"\n + \"Location VARCHAR(255), \"\n + \"PRIMARY KEY (Id))\";\n String query = \"INSERT INTO Employees(\"\n + \"Name, Salary, Location) VALUES \"\n + \"('Amit', 30000, 'Hyderabad'), \"\n + \"('Kalyan', 40000, 'Vishakhapatnam'), \"\n + \"('Renuka', 50000, 'Delhi'), \"\n + \"('Archana', 15000, 'Mumbai'), \"\n + \"('Trupthi', 45000, 'Kochin'), \"\n + \"('Suchatra', 33000, 'Pune'), \"\n + \"('Rahul', 39000, 'Lucknow'), \"\n + \"('Trupti', 45000, 'Kochin')\";\n //Executing the query\n String query = \"SELECT Id, Name, Salary FROM Employees\";\n ResultSet rs = stmt.executeQuery(query);\n while(rs.next()) {\n System.out.println(\"Id: \"+rs.getString(\"Id\"));\n System.out.println(\"Name: \"+rs.getString(\"Name\"));\n System.out.println(\"Salary: \"+rs.getString(\"Salary\"));\n System.out.println(\" \");\n }\n }\n}" }, { "code": null, "e": 7802, "s": 7735, "text": "On executing the above program, you will get the following output." }, { "code": null, "e": 8042, "s": 7802, "text": "Id: 1\nName: Amit\nSalary: 30000\n\nId: 2\nName: Kalyan\nSalary: 43000\n\nId: 3\nName: Renuka\nSalary: 50000\n\nId: 4\nName: Archana\nSalary: 15000\n\nId: 5\nName: Trupthi\nSalary: 45000\n\nId: 6\nName: Suchatra\nSalary: 33000\n\nId: 7\nName: Rahul\nSalary: 39000 \n" }, { "code": null, "e": 8077, "s": 8042, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8096, "s": 8077, "text": " Arnab Chakraborty" }, { "code": null, "e": 8131, "s": 8096, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8152, "s": 8131, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 8185, "s": 8152, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 8198, "s": 8185, "text": " Nilay Mehta" }, { "code": null, "e": 8233, "s": 8198, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8251, "s": 8233, "text": " Bigdata Engineer" }, { "code": null, "e": 8284, "s": 8251, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8302, "s": 8284, "text": " Bigdata Engineer" }, { "code": null, "e": 8335, "s": 8302, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 8353, "s": 8335, "text": " Bigdata Engineer" }, { "code": null, "e": 8360, "s": 8353, "text": " Print" }, { "code": null, "e": 8371, "s": 8360, "text": " Add Notes" } ]
Java Robot Class | Get the pixel Color of a given point - GeeksforGeeks
14 Apr, 2021 Robot is part of java.awt package . Robot class is basically used to generate native system input events for the purposes of self- running demos, test automation, and other application where control over mouse and keyboard is used. Robot class generates events that can be used to control mouse, keyboard and can be used to take screenshot of the screen. In this article we will discuss how to get the pixel color of the point on the screen mentioned by the user.Method used : getPixelColor(int x, int y) This function returns an object of the color class of the given screen coordinates. In the following program we will print a label that will contain the RGB values of the pixel entered and the text of the label will be of the pixel Color Java // Java program to get the pixel color of// given screen coordinatesimport java.awt.*;import javax.swing.*;import java.awt.event.*;public class color extends JFrame implements ActionListener { // textfield to get x, y coordinates static JTextField x, y; // button static JButton b; // create a frame static JFrame f; // label static JLabel l; public static void main() { // create a frame f = new JFrame("pixel Color"); // label to show the RGB value l = new JLabel("no value"); // create the text field x = new JTextField(16); y = new JTextField(16); // create a button b = new JButton("find"); // create an object of the class color co = new color(); // add ActionListener b.addActionListener(co); // create a panel JPanel p = new JPanel(); // add textfield and button to the panel p.add(x); p.add(y); p.add(b); p.add(l); // add the panel f.add(p); // set the size of the frame f.setSize(500, 500); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals("find")) { int xp, yp; // get user inputs of x and y position xp = Integer.parseInt(x.getText()); yp = Integer.parseInt(y.getText()); // try and catch block to handle exceptions try { // create an object of robot class Robot r = new Robot(); // get the pixel color c = r.getPixelColor(xp, yp); } catch (Exception evt) { // print error message System.err.println(evt.getMessage()); } Color c; // set the RGB value to the label // and to its foreground l.setForeground(c); l.setText("Red = " + c.getRed() + ",Green = " + c.getGreen() + ", Blue = " + c.getBlue()); } }} Output : Note : the following program might not run in an online compiler please use an offline IDE. sweetyty Java Programming Language Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Arrow operator -> in C/C++ with Examples Modulo Operator (%) in C/C++ with Examples Structures in C++ Differences between Procedural and Object Oriented Programming Top 10 Programming Languages to Learn in 2022
[ { "code": null, "e": 24536, "s": 24508, "text": "\n14 Apr, 2021" }, { "code": null, "e": 25015, "s": 24536, "text": "Robot is part of java.awt package . Robot class is basically used to generate native system input events for the purposes of self- running demos, test automation, and other application where control over mouse and keyboard is used. Robot class generates events that can be used to control mouse, keyboard and can be used to take screenshot of the screen. In this article we will discuss how to get the pixel color of the point on the screen mentioned by the user.Method used : " }, { "code": null, "e": 25131, "s": 25015, "text": "getPixelColor(int x, int y) \nThis function returns an object of the color class \nof the given screen coordinates. " }, { "code": null, "e": 25286, "s": 25131, "text": "In the following program we will print a label that will contain the RGB values of the pixel entered and the text of the label will be of the pixel Color " }, { "code": null, "e": 25291, "s": 25286, "text": "Java" }, { "code": "// Java program to get the pixel color of// given screen coordinatesimport java.awt.*;import javax.swing.*;import java.awt.event.*;public class color extends JFrame implements ActionListener { // textfield to get x, y coordinates static JTextField x, y; // button static JButton b; // create a frame static JFrame f; // label static JLabel l; public static void main() { // create a frame f = new JFrame(\"pixel Color\"); // label to show the RGB value l = new JLabel(\"no value\"); // create the text field x = new JTextField(16); y = new JTextField(16); // create a button b = new JButton(\"find\"); // create an object of the class color co = new color(); // add ActionListener b.addActionListener(co); // create a panel JPanel p = new JPanel(); // add textfield and button to the panel p.add(x); p.add(y); p.add(b); p.add(l); // add the panel f.add(p); // set the size of the frame f.setSize(500, 500); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals(\"find\")) { int xp, yp; // get user inputs of x and y position xp = Integer.parseInt(x.getText()); yp = Integer.parseInt(y.getText()); // try and catch block to handle exceptions try { // create an object of robot class Robot r = new Robot(); // get the pixel color c = r.getPixelColor(xp, yp); } catch (Exception evt) { // print error message System.err.println(evt.getMessage()); } Color c; // set the RGB value to the label // and to its foreground l.setForeground(c); l.setText(\"Red = \" + c.getRed() + \",Green = \" + c.getGreen() + \", Blue = \" + c.getBlue()); } }}", "e": 27398, "s": 25291, "text": null }, { "code": null, "e": 27409, "s": 27398, "text": "Output : " }, { "code": null, "e": 27502, "s": 27409, "text": "Note : the following program might not run in an online compiler please use an offline IDE. " }, { "code": null, "e": 27511, "s": 27502, "text": "sweetyty" }, { "code": null, "e": 27516, "s": 27511, "text": "Java" }, { "code": null, "e": 27537, "s": 27516, "text": "Programming Language" }, { "code": null, "e": 27542, "s": 27537, "text": "Java" }, { "code": null, "e": 27640, "s": 27542, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27672, "s": 27640, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27691, "s": 27672, "text": "Interfaces in Java" }, { "code": null, "e": 27709, "s": 27691, "text": "ArrayList in Java" }, { "code": null, "e": 27741, "s": 27709, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27761, "s": 27741, "text": "Stack Class in Java" }, { "code": null, "e": 27802, "s": 27761, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27845, "s": 27802, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 27863, "s": 27845, "text": "Structures in C++" }, { "code": null, "e": 27926, "s": 27863, "text": "Differences between Procedural and Object Oriented Programming" } ]
VB.Net - Data Types
Data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted. VB.Net provides a wide range of data types. The following table shows all the data types available − -1.79769313486231570E+308 through -4.94065645841246544E-324, for negative values 4.94065645841246544E-324 through 1.79769313486231570E+308, for positive values 4 bytes on 32-bit platform 8 bytes on 64-bit platform -3.4028235E+38 through -1.401298E-45 for negative values; 1.401298E-45 through 3.4028235E+38 for positive values The following example demonstrates use of some of the types − Module DataTypes Sub Main() Dim b As Byte Dim n As Integer Dim si As Single Dim d As Double Dim da As Date Dim c As Char Dim s As String Dim bl As Boolean b = 1 n = 1234567 si = 0.12345678901234566 d = 0.12345678901234566 da = Today c = "U"c s = "Me" If ScriptEngine = "VB" Then bl = True Else bl = False End If If bl Then 'the oath taking Console.Write(c & " and," & s & vbCrLf) Console.WriteLine("declaring on the day of: {0}", da) Console.WriteLine("We will learn VB.Net seriously") Console.WriteLine("Lets see what happens to the floating point variables:") Console.WriteLine("The Single: {0}, The Double: {1}", si, d) End If Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − U and, Me declaring on the day of: 12/4/2012 12:00:00 PM We will learn VB.Net seriously Lets see what happens to the floating point variables: The Single:0.1234568, The Double: 0.123456789012346 VB.Net provides the following in-line type conversion functions − CBool(expression) Converts the expression to Boolean data type. CByte(expression) Converts the expression to Byte data type. CChar(expression) Converts the expression to Char data type. CDate(expression) Converts the expression to Date data type CDbl(expression) Converts the expression to Double data type. CDec(expression) Converts the expression to Decimal data type. CInt(expression) Converts the expression to Integer data type. CLng(expression) Converts the expression to Long data type. CObj(expression) Converts the expression to Object type. CSByte(expression) Converts the expression to SByte data type. CShort(expression) Converts the expression to Short data type. CSng(expression) Converts the expression to Single data type. CStr(expression) Converts the expression to String data type. CUInt(expression) Converts the expression to UInt data type. CULng(expression) Converts the expression to ULng data type. CUShort(expression) Converts the expression to UShort data type. The following example demonstrates some of these functions − Module DataTypes Sub Main() Dim n As Integer Dim da As Date Dim bl As Boolean = True n = 1234567 da = Today Console.WriteLine(bl) Console.WriteLine(CSByte(bl)) Console.WriteLine(CStr(bl)) Console.WriteLine(CStr(da)) Console.WriteLine(CChar(CChar(CStr(n)))) Console.WriteLine(CChar(CStr(da))) Console.ReadKey() End Sub End Module When the above code is compiled and executed, it produces the following result − True -1 True 12/4/2012 1 1 63 Lectures 4 hours Frahaan Hussain 103 Lectures 12 hours Arnold Higuit 60 Lectures 9.5 hours Arnold Higuit 97 Lectures 9 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2521, "s": 2300, "text": "Data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted." }, { "code": null, "e": 2622, "s": 2521, "text": "VB.Net provides a wide range of data types. The following table shows all the data types available −" }, { "code": null, "e": 2703, "s": 2622, "text": "-1.79769313486231570E+308 through -4.94065645841246544E-324, for negative values" }, { "code": null, "e": 2782, "s": 2703, "text": "4.94065645841246544E-324 through 1.79769313486231570E+308, for positive values" }, { "code": null, "e": 2809, "s": 2782, "text": "4 bytes on 32-bit platform" }, { "code": null, "e": 2836, "s": 2809, "text": "8 bytes on 64-bit platform" }, { "code": null, "e": 2894, "s": 2836, "text": "-3.4028235E+38 through -1.401298E-45 for negative values;" }, { "code": null, "e": 2949, "s": 2894, "text": "1.401298E-45 through 3.4028235E+38 for positive values" }, { "code": null, "e": 3011, "s": 2949, "text": "The following example demonstrates use of some of the types −" }, { "code": null, "e": 3903, "s": 3011, "text": "Module DataTypes\n Sub Main()\n Dim b As Byte\n Dim n As Integer\n Dim si As Single\n Dim d As Double\n Dim da As Date\n Dim c As Char\n Dim s As String\n Dim bl As Boolean\n \n b = 1\n n = 1234567\n si = 0.12345678901234566\n d = 0.12345678901234566\n da = Today\n c = \"U\"c\n s = \"Me\"\n \n If ScriptEngine = \"VB\" Then\n bl = True\n Else\n bl = False\n End If\n \n If bl Then\n 'the oath taking\n Console.Write(c & \" and,\" & s & vbCrLf)\n Console.WriteLine(\"declaring on the day of: {0}\", da)\n Console.WriteLine(\"We will learn VB.Net seriously\")\n Console.WriteLine(\"Lets see what happens to the floating point variables:\")\n Console.WriteLine(\"The Single: {0}, The Double: {1}\", si, d)\n End If\n Console.ReadKey()\n End Sub\nEnd Module" }, { "code": null, "e": 3984, "s": 3903, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4180, "s": 3984, "text": "U and, Me\ndeclaring on the day of: 12/4/2012 12:00:00 PM\nWe will learn VB.Net seriously\nLets see what happens to the floating point variables:\nThe Single:0.1234568, The Double: 0.123456789012346\n" }, { "code": null, "e": 4246, "s": 4180, "text": "VB.Net provides the following in-line type conversion functions −" }, { "code": null, "e": 4264, "s": 4246, "text": "CBool(expression)" }, { "code": null, "e": 4310, "s": 4264, "text": "Converts the expression to Boolean data type." }, { "code": null, "e": 4328, "s": 4310, "text": "CByte(expression)" }, { "code": null, "e": 4371, "s": 4328, "text": "Converts the expression to Byte data type." }, { "code": null, "e": 4389, "s": 4371, "text": "CChar(expression)" }, { "code": null, "e": 4432, "s": 4389, "text": "Converts the expression to Char data type." }, { "code": null, "e": 4450, "s": 4432, "text": "CDate(expression)" }, { "code": null, "e": 4492, "s": 4450, "text": "Converts the expression to Date data type" }, { "code": null, "e": 4509, "s": 4492, "text": "CDbl(expression)" }, { "code": null, "e": 4554, "s": 4509, "text": "Converts the expression to Double data type." }, { "code": null, "e": 4571, "s": 4554, "text": "CDec(expression)" }, { "code": null, "e": 4617, "s": 4571, "text": "Converts the expression to Decimal data type." }, { "code": null, "e": 4634, "s": 4617, "text": "CInt(expression)" }, { "code": null, "e": 4680, "s": 4634, "text": "Converts the expression to Integer data type." }, { "code": null, "e": 4697, "s": 4680, "text": "CLng(expression)" }, { "code": null, "e": 4740, "s": 4697, "text": "Converts the expression to Long data type." }, { "code": null, "e": 4757, "s": 4740, "text": "CObj(expression)" }, { "code": null, "e": 4797, "s": 4757, "text": "Converts the expression to Object type." }, { "code": null, "e": 4816, "s": 4797, "text": "CSByte(expression)" }, { "code": null, "e": 4860, "s": 4816, "text": "Converts the expression to SByte data type." }, { "code": null, "e": 4879, "s": 4860, "text": "CShort(expression)" }, { "code": null, "e": 4923, "s": 4879, "text": "Converts the expression to Short data type." }, { "code": null, "e": 4940, "s": 4923, "text": "CSng(expression)" }, { "code": null, "e": 4985, "s": 4940, "text": "Converts the expression to Single data type." }, { "code": null, "e": 5002, "s": 4985, "text": "CStr(expression)" }, { "code": null, "e": 5047, "s": 5002, "text": "Converts the expression to String data type." }, { "code": null, "e": 5065, "s": 5047, "text": "CUInt(expression)" }, { "code": null, "e": 5108, "s": 5065, "text": "Converts the expression to UInt data type." }, { "code": null, "e": 5126, "s": 5108, "text": "CULng(expression)" }, { "code": null, "e": 5169, "s": 5126, "text": "Converts the expression to ULng data type." }, { "code": null, "e": 5189, "s": 5169, "text": "CUShort(expression)" }, { "code": null, "e": 5234, "s": 5189, "text": "Converts the expression to UShort data type." }, { "code": null, "e": 5295, "s": 5234, "text": "The following example demonstrates some of these functions −" }, { "code": null, "e": 5709, "s": 5295, "text": "Module DataTypes\n Sub Main()\n Dim n As Integer\n Dim da As Date\n Dim bl As Boolean = True\n n = 1234567\n da = Today\n \n Console.WriteLine(bl)\n Console.WriteLine(CSByte(bl))\n Console.WriteLine(CStr(bl))\n Console.WriteLine(CStr(da))\n Console.WriteLine(CChar(CChar(CStr(n))))\n Console.WriteLine(CChar(CStr(da)))\n Console.ReadKey()\n End Sub\nEnd Module" }, { "code": null, "e": 5790, "s": 5709, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5818, "s": 5790, "text": "True\n-1\nTrue\n12/4/2012\n1\n1\n" }, { "code": null, "e": 5851, "s": 5818, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 5868, "s": 5851, "text": " Frahaan Hussain" }, { "code": null, "e": 5903, "s": 5868, "text": "\n 103 Lectures \n 12 hours \n" }, { "code": null, "e": 5918, "s": 5903, "text": " Arnold Higuit" }, { "code": null, "e": 5953, "s": 5918, "text": "\n 60 Lectures \n 9.5 hours \n" }, { "code": null, "e": 5968, "s": 5953, "text": " Arnold Higuit" }, { "code": null, "e": 6001, "s": 5968, "text": "\n 97 Lectures \n 9 hours \n" }, { "code": null, "e": 6016, "s": 6001, "text": " Arnold Higuit" }, { "code": null, "e": 6023, "s": 6016, "text": " Print" }, { "code": null, "e": 6034, "s": 6023, "text": " Add Notes" } ]
How to rotate tick labels in a subplot in Matplotlib?
To rotate tick labels in a subplot, we can use set_xticklabels() or set_yticklabels() with rotation argument in the method. Create a list of numbers (x) that can be used to tick the axes. Create a list of numbers (x) that can be used to tick the axes. Get the axis using subplot() that helps to add a subplot to the current figure. Get the axis using subplot() that helps to add a subplot to the current figure. Set ticks on the X and Y axes using set_xticks and set_yticks methods, respectively, and the list x (from step 1). Set ticks on the X and Y axes using set_xticks and set_yticks methods, respectively, and the list x (from step 1). Set tick labels with label lists (["one", "two", "three", "four"]) and rotation=45 using set_xticklabels() and set_yticklabels(). Set tick labels with label lists (["one", "two", "three", "four"]) and rotation=45 using set_xticklabels() and set_yticklabels(). To add space between axes and tick labels, we can use tick_params() method with pad argument that helps to add space. The argument direction(in) helps to put the ticks inside the axes. And, apply axis(both) parameters on both the axes. To add space between axes and tick labels, we can use tick_params() method with pad argument that helps to add space. The argument direction(in) helps to put the ticks inside the axes. And, apply axis(both) parameters on both the axes. To show the figure, use plt.show() method. To show the figure, use plt.show() method. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = [1, 2, 3, 4] ax1 = plt.subplot() ax1.set_xticks(x) ax1.set_yticks(x) ax1.set_xticklabels(["one", "two", "three", "four"], rotation=45) ax1.set_yticklabels(["one", "two", "three", "four"], rotation=45) ax1.tick_params(axis="both", direction="in", pad=15) plt.show()
[ { "code": null, "e": 1186, "s": 1062, "text": "To rotate tick labels in a subplot, we can use set_xticklabels() or set_yticklabels() with rotation argument in the method." }, { "code": null, "e": 1250, "s": 1186, "text": "Create a list of numbers (x) that can be used to tick the axes." }, { "code": null, "e": 1314, "s": 1250, "text": "Create a list of numbers (x) that can be used to tick the axes." }, { "code": null, "e": 1394, "s": 1314, "text": "Get the axis using subplot() that helps to add a subplot to the current figure." }, { "code": null, "e": 1474, "s": 1394, "text": "Get the axis using subplot() that helps to add a subplot to the current figure." }, { "code": null, "e": 1589, "s": 1474, "text": "Set ticks on the X and Y axes using set_xticks and set_yticks methods, respectively, and the list x (from step 1)." }, { "code": null, "e": 1704, "s": 1589, "text": "Set ticks on the X and Y axes using set_xticks and set_yticks methods, respectively, and the list x (from step 1)." }, { "code": null, "e": 1834, "s": 1704, "text": "Set tick labels with label lists ([\"one\", \"two\", \"three\", \"four\"]) and rotation=45 using set_xticklabels() and set_yticklabels()." }, { "code": null, "e": 1964, "s": 1834, "text": "Set tick labels with label lists ([\"one\", \"two\", \"three\", \"four\"]) and rotation=45 using set_xticklabels() and set_yticklabels()." }, { "code": null, "e": 2200, "s": 1964, "text": "To add space between axes and tick labels, we can use tick_params() method with pad argument that helps to add space. The argument direction(in) helps to put the ticks inside the axes. And, apply axis(both) parameters on both the axes." }, { "code": null, "e": 2436, "s": 2200, "text": "To add space between axes and tick labels, we can use tick_params() method with pad argument that helps to add space. The argument direction(in) helps to put the ticks inside the axes. And, apply axis(both) parameters on both the axes." }, { "code": null, "e": 2479, "s": 2436, "text": "To show the figure, use plt.show() method." }, { "code": null, "e": 2522, "s": 2479, "text": "To show the figure, use plt.show() method." }, { "code": null, "e": 2910, "s": 2522, "text": "import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = [1, 2, 3, 4]\nax1 = plt.subplot()\nax1.set_xticks(x)\nax1.set_yticks(x)\nax1.set_xticklabels([\"one\", \"two\", \"three\", \"four\"], rotation=45)\nax1.set_yticklabels([\"one\", \"two\", \"three\", \"four\"], rotation=45)\nax1.tick_params(axis=\"both\", direction=\"in\", pad=15)\nplt.show()" } ]
How to add PDF in Tkinter GUI Python ? - GeeksforGeeks
13 Jan, 2021 In this article, We are going to see how to add a PDF file Tkinter GUI, For that, we don’t have a direct widget to do this. For that, We need to have python version 2.7 or more. And you need to install the ‘tkPDFViewer‘ library. This library allows you to embed the PDF file in your Tkinter GUI. Installation: To install this library you just have to type: pip install tkPDFViewer Initialize tk and geometry of our GUI. Import tkPDFViewer. Make the object of Class ShowPdf() from tkPDFViewer. Using pdf_view method from ShowPdf() to place our pdf. Pack the pdf_view in GUI. Below is the implementation: We are using this pdf for demonstration: Code: Python # Importing tkinter to make gui in pythonfrom tkinter import* # Importing tkPDFViewer to place pdf file in gui.# In tkPDFViewer library there is# an tkPDFViewer module. That I have imported as pdffrom tkPDFViewer import tkPDFViewer as pdf # Initializing tkroot = Tk() # Set the width and height of our root window.root.geometry("550x750") # creating object of ShowPdf from tkPDFViewer.v1 = pdf.ShowPdf() # Adding pdf location and width and height.v2 = v1.pdf_view(root, pdf_location = r"location", width = 50, height = 100) # Placing Pdf in my gui.v2.pack()root.mainloop() Output: Python Tkinter-exercises Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n13 Jan, 2021" }, { "code": null, "e": 24588, "s": 24292, "text": "In this article, We are going to see how to add a PDF file Tkinter GUI, For that, we don’t have a direct widget to do this. For that, We need to have python version 2.7 or more. And you need to install the ‘tkPDFViewer‘ library. This library allows you to embed the PDF file in your Tkinter GUI." }, { "code": null, "e": 24602, "s": 24588, "text": "Installation:" }, { "code": null, "e": 24649, "s": 24602, "text": "To install this library you just have to type:" }, { "code": null, "e": 24673, "s": 24649, "text": "pip install tkPDFViewer" }, { "code": null, "e": 24712, "s": 24673, "text": "Initialize tk and geometry of our GUI." }, { "code": null, "e": 24732, "s": 24712, "text": "Import tkPDFViewer." }, { "code": null, "e": 24785, "s": 24732, "text": "Make the object of Class ShowPdf() from tkPDFViewer." }, { "code": null, "e": 24840, "s": 24785, "text": "Using pdf_view method from ShowPdf() to place our pdf." }, { "code": null, "e": 24866, "s": 24840, "text": "Pack the pdf_view in GUI." }, { "code": null, "e": 24895, "s": 24866, "text": "Below is the implementation:" }, { "code": null, "e": 24936, "s": 24895, "text": "We are using this pdf for demonstration:" }, { "code": null, "e": 24942, "s": 24936, "text": "Code:" }, { "code": null, "e": 24949, "s": 24942, "text": "Python" }, { "code": "# Importing tkinter to make gui in pythonfrom tkinter import* # Importing tkPDFViewer to place pdf file in gui.# In tkPDFViewer library there is# an tkPDFViewer module. That I have imported as pdffrom tkPDFViewer import tkPDFViewer as pdf # Initializing tkroot = Tk() # Set the width and height of our root window.root.geometry(\"550x750\") # creating object of ShowPdf from tkPDFViewer.v1 = pdf.ShowPdf() # Adding pdf location and width and height.v2 = v1.pdf_view(root, pdf_location = r\"location\", width = 50, height = 100) # Placing Pdf in my gui.v2.pack()root.mainloop()", "e": 25561, "s": 24949, "text": null }, { "code": null, "e": 25569, "s": 25561, "text": "Output:" }, { "code": null, "e": 25594, "s": 25569, "text": "Python Tkinter-exercises" }, { "code": null, "e": 25609, "s": 25594, "text": "Python-tkinter" }, { "code": null, "e": 25616, "s": 25609, "text": "Python" }, { "code": null, "e": 25714, "s": 25616, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25723, "s": 25714, "text": "Comments" }, { "code": null, "e": 25736, "s": 25723, "text": "Old Comments" }, { "code": null, "e": 25768, "s": 25736, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25824, "s": 25768, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25879, "s": 25824, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25921, "s": 25879, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25963, "s": 25921, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25994, "s": 25963, "text": "Python | os.path.join() method" }, { "code": null, "e": 26033, "s": 25994, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26055, "s": 26033, "text": "Defaultdict in Python" }, { "code": null, "e": 26084, "s": 26055, "text": "Create a directory in Python" } ]
Java program to Print Odd and Even Number from an Array
In the loop check, the result of I %2 operation on each element, if 0 the element is even else the element is odd. Live Demo public class OddNumbersInAnArray { public static void main(String args[]){ int[] myArray = {23, 93, 56, 92, 39}; System.out.println("Even numbers in the given array are:: "); for (int i=0; i<myArray.length; i++){ if(myArray[i]%2 == 0){ System.out.println(myArray[i]); } } System.out.println("Odd numbers in the given array are:: "); for (int i=0; i<myArray.length; i++){ if(myArray[i]%2 != 0){ System.out.println(myArray[i]); } } } } Even numbers in the given array are:: 56 92 Odd numbers in the given array are:: 23 93 39
[ { "code": null, "e": 1177, "s": 1062, "text": "In the loop check, the result of I %2 operation on each element, if 0 the element is even else the element is odd." }, { "code": null, "e": 1187, "s": 1177, "text": "Live Demo" }, { "code": null, "e": 1731, "s": 1187, "text": "public class OddNumbersInAnArray {\n public static void main(String args[]){\n int[] myArray = {23, 93, 56, 92, 39};\n System.out.println(\"Even numbers in the given array are:: \");\n\n for (int i=0; i<myArray.length; i++){\n if(myArray[i]%2 == 0){\n System.out.println(myArray[i]);\n }\n }\n System.out.println(\"Odd numbers in the given array are:: \");\n\n for (int i=0; i<myArray.length; i++){\n if(myArray[i]%2 != 0){\n System.out.println(myArray[i]);\n }\n }\n }\n}" }, { "code": null, "e": 1821, "s": 1731, "text": "Even numbers in the given array are::\n56\n92\nOdd numbers in the given array are::\n23\n93\n39" } ]
What is the use of ‘new’ keyword in C#?
Use the new keyword to create an instance of the array − int [] a = new int[5]; The new operator is used to create an object or instantiate an object. Here in the example, an object is created for the class using the new − Live Demo using System; namespace CalculatorApplication { class NumberManipulator { public void swap(int x, int y) { int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put temp into y */ } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* local variable definition */ int a = 100; int b = 200; Console.WriteLine("Before swap, value of a : {0}", a); Console.WriteLine("Before swap, value of b : {0}", b); /* calling a function to swap the values */ n.swap(a, b); Console.WriteLine("After swap, value of a : {0}", a); Console.WriteLine("After swap, value of b : {0}", b); Console.ReadLine(); } } } Before swap, value of a : 100 Before swap, value of b : 200 After swap, value of a : 100 After swap, value of b : 200
[ { "code": null, "e": 1119, "s": 1062, "text": "Use the new keyword to create an instance of the array −" }, { "code": null, "e": 1142, "s": 1119, "text": "int [] a = new int[5];" }, { "code": null, "e": 1285, "s": 1142, "text": "The new operator is used to create an object or instantiate an object. Here in the example, an object is created for the class using the new −" }, { "code": null, "e": 1296, "s": 1285, "text": " Live Demo" }, { "code": null, "e": 2118, "s": 1296, "text": "using System;\n\nnamespace CalculatorApplication {\n class NumberManipulator {\n public void swap(int x, int y) {\n int temp;\n\n temp = x; /* save the value of x */\n x = y; /* put y into x */\n y = temp; /* put temp into y */\n }\n static void Main(string[] args) {\n NumberManipulator n = new NumberManipulator();\n\n /* local variable definition */\n int a = 100;\n int b = 200;\n Console.WriteLine(\"Before swap, value of a : {0}\", a);\n Console.WriteLine(\"Before swap, value of b : {0}\", b);\n /* calling a function to swap the values */\n n.swap(a, b);\n Console.WriteLine(\"After swap, value of a : {0}\", a);\n Console.WriteLine(\"After swap, value of b : {0}\", b);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2236, "s": 2118, "text": "Before swap, value of a : 100\nBefore swap, value of b : 200\nAfter swap, value of a : 100\nAfter swap, value of b : 200" } ]
HTML - <article> Tag
The HTML <article> tag is used in a blog post, forum post, newspaper article etc. It specifies self-contained composition in a site, document, page or application. <!DOCTYPE html> <html> <head> <title>HTML Article Tag</title> </head> <body> <article> <h2>PHP</h2> <p>PHP is PHP Hypertext Preprocessor</p> </article> </body> </html> This will produce the following result − PHP is PHP Hypertext Preprocessor This tag supports all the global attributes described in HTML Attribute Reference This tag supports all the event attributes described in HTML Events Reference 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2538, "s": 2374, "text": "The HTML <article> tag is used in a blog post, forum post, newspaper article etc. It specifies self-contained composition in a site, document, page or application." }, { "code": null, "e": 2758, "s": 2538, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Article Tag</title>\n </head>\n\n <body>\n <article>\n <h2>PHP</h2> \n <p>PHP is PHP Hypertext Preprocessor</p>\n </article>\n </body>\n\n</html>" }, { "code": null, "e": 2799, "s": 2758, "text": "This will produce the following result −" }, { "code": null, "e": 2833, "s": 2799, "text": "PHP is PHP Hypertext Preprocessor" }, { "code": null, "e": 2915, "s": 2833, "text": "This tag supports all the global attributes described in HTML Attribute Reference" }, { "code": null, "e": 2993, "s": 2915, "text": "This tag supports all the event attributes described in HTML Events Reference" }, { "code": null, "e": 3026, "s": 2993, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3040, "s": 3026, "text": " Anadi Sharma" }, { "code": null, "e": 3075, "s": 3040, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3089, "s": 3075, "text": " Anadi Sharma" }, { "code": null, "e": 3124, "s": 3089, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3141, "s": 3124, "text": " Frahaan Hussain" }, { "code": null, "e": 3176, "s": 3141, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3207, "s": 3176, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3240, "s": 3207, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3271, "s": 3240, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3306, "s": 3271, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3337, "s": 3306, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3344, "s": 3337, "text": " Print" }, { "code": null, "e": 3355, "s": 3344, "text": " Add Notes" } ]
HTML | DOM Style backgroundColor Property - GeeksforGeeks
10 Jan, 2022 The backgroundColor property in HTML DOM is used to set or return the background-color of an element.Syntax: object.style.backgroundColor It returns the background color of an element. object.style.backgroundColor = "color|transparent|initial| inherit" It is used to set the background color of an element. Parameter: There are four parameter accepted by backgroundColot property color: This property holds the background color. transparent: Bydefault the background color is transparent. initial: Set this property to it’s default inherit: Inherits the property from it’s parent element Return Values: It returns a string value, which representing the background color. Example 1: html <!DOCTYPE html><html> <head> <title> Style backgroundColor Property </title> <script> /* script to set background color */ function geeks() { document.body.style.backgroundColor = "lightgreen"; } </script></head> <body style="text-align:center"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2> Style backgroundColor Property </h2> <button type="button" onclick="geeks()"> Submit </button></body></html Output: Before: After: Example 2: html <!DOCTYPE html><html> <head> <title> Style backgroundColor Property </title> <style> #geeks { width: 250px; height: 100px; background-color: coral; } </style></head> <body> <center> <h1 style="color:green;"> GeeksForGeeks </h1> <h2> DOM Style backgroundColor Property </h2> <button onclick="geeks()">Submitt</button> <div id="geeks"> <h1>GeeksForGeeks</h1> </div> <script> function geeks() { document.getElementById("geeks").style.backgroundColor = "lightgreen"; } </script> </center></body> </html> Output: Before: After: Supported Browsers: The browser supported by DOM style backgroundColor Property are listed below: Chrome 1.0 Internet Explorer4.0 Firefox 1.0 Safari 1.0 Opera 3.5 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Akanksha_Rai ManasChhabra2 varshagumber28 HTML-DOM HTML Misc Misc Misc HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Top 10 algorithms in Interview Questions vector::push_back() and vector::pop_back() in C++ STL Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions?
[ { "code": null, "e": 24751, "s": 24723, "text": "\n10 Jan, 2022" }, { "code": null, "e": 24861, "s": 24751, "text": "The backgroundColor property in HTML DOM is used to set or return the background-color of an element.Syntax: " }, { "code": null, "e": 24890, "s": 24861, "text": "object.style.backgroundColor" }, { "code": null, "e": 24937, "s": 24890, "text": "It returns the background color of an element." }, { "code": null, "e": 25005, "s": 24937, "text": "object.style.backgroundColor = \"color|transparent|initial|\ninherit\"" }, { "code": null, "e": 25059, "s": 25005, "text": "It is used to set the background color of an element." }, { "code": null, "e": 25134, "s": 25059, "text": "Parameter: There are four parameter accepted by backgroundColot property " }, { "code": null, "e": 25183, "s": 25134, "text": "color: This property holds the background color." }, { "code": null, "e": 25243, "s": 25183, "text": "transparent: Bydefault the background color is transparent." }, { "code": null, "e": 25286, "s": 25243, "text": "initial: Set this property to it’s default" }, { "code": null, "e": 25342, "s": 25286, "text": "inherit: Inherits the property from it’s parent element" }, { "code": null, "e": 25425, "s": 25342, "text": "Return Values: It returns a string value, which representing the background color." }, { "code": null, "e": 25438, "s": 25425, "text": "Example 1: " }, { "code": null, "e": 25443, "s": 25438, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Style backgroundColor Property </title> <script> /* script to set background color */ function geeks() { document.body.style.backgroundColor = \"lightgreen\"; } </script></head> <body style=\"text-align:center\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2> Style backgroundColor Property </h2> <button type=\"button\" onclick=\"geeks()\"> Submit </button></body></html ", "e": 25989, "s": 25443, "text": null }, { "code": null, "e": 25998, "s": 25989, "text": "Output: " }, { "code": null, "e": 26007, "s": 25998, "text": "Before: " }, { "code": null, "e": 26015, "s": 26007, "text": "After: " }, { "code": null, "e": 26028, "s": 26015, "text": "Example 2: " }, { "code": null, "e": 26033, "s": 26028, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Style backgroundColor Property </title> <style> #geeks { width: 250px; height: 100px; background-color: coral; } </style></head> <body> <center> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2> DOM Style backgroundColor Property </h2> <button onclick=\"geeks()\">Submitt</button> <div id=\"geeks\"> <h1>GeeksForGeeks</h1> </div> <script> function geeks() { document.getElementById(\"geeks\").style.backgroundColor = \"lightgreen\"; } </script> </center></body> </html> ", "e": 26803, "s": 26033, "text": null }, { "code": null, "e": 26812, "s": 26803, "text": "Output: " }, { "code": null, "e": 26821, "s": 26812, "text": "Before: " }, { "code": null, "e": 26829, "s": 26821, "text": "After: " }, { "code": null, "e": 26929, "s": 26829, "text": "Supported Browsers: The browser supported by DOM style backgroundColor Property are listed below: " }, { "code": null, "e": 26940, "s": 26929, "text": "Chrome 1.0" }, { "code": null, "e": 26961, "s": 26940, "text": "Internet Explorer4.0" }, { "code": null, "e": 26973, "s": 26961, "text": "Firefox 1.0" }, { "code": null, "e": 26984, "s": 26973, "text": "Safari 1.0" }, { "code": null, "e": 26995, "s": 26984, "text": "Opera 3.5 " }, { "code": null, "e": 27132, "s": 26995, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27145, "s": 27132, "text": "Akanksha_Rai" }, { "code": null, "e": 27159, "s": 27145, "text": "ManasChhabra2" }, { "code": null, "e": 27174, "s": 27159, "text": "varshagumber28" }, { "code": null, "e": 27183, "s": 27174, "text": "HTML-DOM" }, { "code": null, "e": 27188, "s": 27183, "text": "HTML" }, { "code": null, "e": 27193, "s": 27188, "text": "Misc" }, { "code": null, "e": 27198, "s": 27193, "text": "Misc" }, { "code": null, "e": 27203, "s": 27198, "text": "Misc" }, { "code": null, "e": 27208, "s": 27203, "text": "HTML" }, { "code": null, "e": 27306, "s": 27208, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27356, "s": 27306, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27418, "s": 27356, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27466, "s": 27418, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27526, "s": 27466, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27579, "s": 27526, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 27620, "s": 27579, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 27674, "s": 27620, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 27735, "s": 27674, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" } ]
How to calculate absolute value in Python?
The abs() function of Python's standard library returns the absolute value of the given number. Absolute value of a number is the value without considering its sign. Hence absolute of 10 is 10, -10 is also 10. If the number is a complex number, abs() returns its magnitude. >>> abs(11.11) 11.11 >>> abs(-11.11) 11.11 >>> abs(2+3j) 3.605551275463989 >>> abs(3-6j) 6.708203932499369 >>> abs(3-4j) 5.0
[ { "code": null, "e": 1336, "s": 1062, "text": "The abs() function of Python's standard library returns the absolute value of the given number. Absolute value of a number is the value without considering its sign. Hence absolute of 10 is 10, -10 is also 10. If the number is a complex number, abs() returns its magnitude." }, { "code": null, "e": 1461, "s": 1336, "text": ">>> abs(11.11)\n11.11\n>>> abs(-11.11)\n11.11\n>>> abs(2+3j)\n3.605551275463989\n>>> abs(3-6j)\n6.708203932499369\n>>> abs(3-4j)\n5.0" } ]
Neural ODEs: breakdown of another deep learning breakthrough | by Alexandr Honchar | Towards Data Science
Hi everyone! If you’re reading this article, most probably you’re catching up with the recent advances that happen in the AI world. The topic we will review today comes from NIPS 2018, and it will be about the best paper award from there: Neural Ordinary Differential Equations (Neural ODEs). In this article, I will try to give a brief intro and the importance of this paper, but I will emphasize the practical use and how and for what we can apply this need breed of neural networks in applications and if can at all. As always, if you want to dive straight to the code, you can check this GitHub repository, I recommend you to launch it in Google Colab. First of all, let’s recap quickly what a beast ordinary differential equation is. It describes evolution in time of some process that depends on one variable (that’s why ordinary), and this change in time is described via a derivative: Usually, we can talk about solving this differential equation, if we have some initial condition (at which point the process starts) and we want to see how the process will evolve up to some final state. The solution function is also called the integral curve (because we can integrate the equation to get the solution x(t)). Let’s try to solve the equation from the picture above using SymPy package: from sympy import dsolve, Eq, symbols, Functiont = symbols('t')x = symbols('x', cls=Function)deqn1 = Eq(x(t).diff(t), 1 - x(t))sol1 = dsolve(deqn1, x(t)) which will return as the solution Eq(x(t), C1*exp(-t) + 1) where C1 is a constant, that can be determined while given some initial condition. ODEs can be solved analytically if given in the appropriate form, but normally they are solved numerically. One of the oldest and simplest algorithms is Euler’s method: the core idea is approximating the solution function step by step using tangents lines: Visit the link under the picture for a more detailed explanation, but at the end, we end up with a very simple formula, for equation the solution at the discretized grid of n time steps is For more details on ODEs, especially how to program them and their solutions in Python, I recommend you to check out this book, it also has a lot of examples of processes in chemistry, physics and industrial fields that have such time evolution, that can be described with the ODEs. Also, for additional intuition about differential equation compared to ML models visit this resource. Meanwhile, looking at Euler’s equation doesn’t it remind you anything from the recent deep learning architectures yet...? Exactly! The y_{n+1} = y_n + f(t_n, y_n) is nothing but a residual connection in ResNet, where the output of some layer is a sum of the output of the layer f() itself and the input y_n to this layer. This is basically the main idea of neural ODEs: a chain of residual blocks in a neural network is basically a solution of the ODE with the Euler method! In this case, the initial condition for the system is “time” 0, which indicates the very first layer of the neural network, and as x(0) will serve the normal input, which can be time series, image, whatever you want! The final condition at “time” t will be the desired output of the neural network: a scalar value, a vector representing classes or anything else. If we remember, that these residual connections are discretized time steps of the Euler method, it means, that we can regulate the depth of the neural network, just with choosing the discretizing scheme, hence, making the solution (aka neural network) more or less accurate, even making it infinite-layer like! Is Euler too primitive ODE solving method? Indeed it is, so let’s replace ResNet / EulerSolverNet with some abstract concept as ODESolveNet, where ODESolve will be a function, that provides a solution to the ODE (lowkey: our neural network itself) with much better accuracy than Euler’s method. The network architecture now might look like the following: nn = Network( Dense(...), # making some primary embedding ODESolve(...), # "infinite-layer neural network" Dense(...) # output layer) We forgot about one thing... A neural network is a differentiable function, so we can train it with gradient-based optimization routines. How should we backpropagate through the ODESolve() function, which is also actually a black box in our case? In particular, we need a gradient of loss function by the input and the dynamics parameters. The mathematical trick is called adjoint sensitivity method. I will refer you to the original paper and this tutorial for more details, but the essence is described in the picture below (L stands for the main loss function we want to optimize): Briefly, alongside with the original dynamical system that describes the process, the adjoint system describes the derivative states at each point of the process backward, via the chain rule (that’s where the roots of well-known backpropagation are). Exactly from it, we can obtain the derivative by the initial state, and, in a similar way, by the parameters of a function that is modeling dynamics (one “residual block”, or the discretization step in the “old” Euler’s method). For more details I recommend you to watch the presentation of one of the authors of the paper himself as well: First, advantages and motivation to use them instead of the “normal ResNets”: Memory efficiency: we don’t need to store all the parameters and gradients while backpropagating Adaptive computation: we can balance speed and accuracy with the discretization scheme, moreover, having it different while training and inference Parameters efficiency: the parameters of nearby “layers” are automatically tied together (see the paper) Normalizing flows new type of invertible density models Continuous time series models: continuously-defined dynamics can naturally incorporate data which arrives at arbitrary times. The applications, according to the paper, apart of the replacing ResNet with ODENet for computer vision, that I see a bit unrealistic now, are the next ones: Compressing complex ODEs into a single dynamic modeling neural network Applying it for time series with missing time steps Invertible normalizing flows (out of the scope of this blog) For the disadvantages, consult the original paper, there are some. Enough theory, let’s check some practical examples now. Just to remind, all the code for experiments is here. As we could see before, differential equations are used widely do describe complex continuous processes. Of course, in real life we observe them as discrete processes, and, most importantly, a lot of observations at the time steps t_i can simply be missing. Let’s supposed you want to model such a system with a neural network. How would you deal with this kind of situation in a classical sequence modeling paradigm? Throw it onto the recurrent neural network somehow, which isn’t even designed for it. In this part, we will check how Neural ODEs will deal with them. Our setup will be the following: Define the ODE itself we will model as a PyTorch nn.Module()Define a simple (or not really) neural network, that will model dynamics between two consequent dynamics steps from h_t to h_{t+1} or, in case of a dynamical system, x_t, and x_{t+1}.Run the optimization process that backpropagates through the ODE solver and minimizes the difference between actual and modeled dynamics. Define the ODE itself we will model as a PyTorch nn.Module() Define a simple (or not really) neural network, that will model dynamics between two consequent dynamics steps from h_t to h_{t+1} or, in case of a dynamical system, x_t, and x_{t+1}. Run the optimization process that backpropagates through the ODE solver and minimizes the difference between actual and modeled dynamics. In all the following experiments the neural network will be just a following (which is supposedly enough to model simple functions with two variables): self.net = nn.Sequential( nn.Linear(2, 50), nn.Tanh(), nn.Linear(50, 2), ) All further examples are highly inspired by this repository with amazing explanations. In the next subsections, I will show how the dynamical systems we model look themselves in the code and how system evolution over time and the phase portrait is being fit by the ODENet. In this, and all the future visualizations, the dotted lines stand for the fitting model. true_A = torch.tensor([[-0.1, 2.0], [-2.0, -0.1]])class Lambda(nn.Module): def forward(self, t, y): return torch.mm(y, true_A) true_A = torch.randn(2, 2)/2. a, b, c, d = 1.5, 1.0, 3.0, 1.0true_A = torch.tensor([[0., -b*c/d], [d*a/b, 0.]]) true_A2 = torch.tensor([[-0.1, -0.5], [0.5, -0.1]])true_B2 = torch.tensor([[0.2, 1.], [-1, 0.2]])class Lambda2(nn.Module): def __init__(self, A, B): super(Lambda2, self).__init__() self.A = nn.Linear(2, 2, bias=False) self.A.weight = nn.Parameter(A) self.B = nn.Linear(2, 2, bias=False) self.B.weight = nn.Parameter(B) def forward(self, t, y): xTx0 = torch.sum(y * true_y0, dim=1) dxdt = torch.sigmoid(xTx0) * self.A(y - true_y0) + torch.sigmoid(-xTx0) * self.B(y + true_y0) return dxdt As we can see, our single “residual block” can’t learn this process well enough, so we might make it more complex for the next functions. Let’s make a function fully parametrized by a multilayer perceptron with randomly initialized weights: true_y0 = torch.tensor([[1., 1.]])t = torch.linspace(-15., 15., data_size)class Lambda3(nn.Module): def __init__(self): super(Lambda3, self).__init__() self.fc1 = nn.Linear(2, 25, bias = False) self.fc2 = nn.Linear(25, 50, bias = False) self.fc3 = nn.Linear(50, 10, bias = False) self.fc4 = nn.Linear(10, 2, bias = False) self.relu = nn.ELU(inplace=True) def forward(self, t, y): x = self.relu(self.fc1(y * t)) x = self.relu(self.fc2(x)) x = self.relu(self.fc3(x)) x = self.relu(self.fc4(x)) return x Here 2–50–2 network fails horribly because it’s too simple, let’s increase its depth: self.net = nn.Sequential( nn.Linear(2, 150), nn.Tanh(), nn.Linear(150, 50), nn.Tanh(), nn.Linear(50, 50), nn.Tanh(), nn.Linear(50, 2), ) Now it works more or less as expected, don’t forget to check the code :) Authors also claim that they can build a generative time series model via VAE framework, using Neural ODEs as a part of it. How does it work? First, we encode the input sequence with some “standard” time series algorithms, let’s say RNN to obtain the primary embedding of the process Run the embedding through the Neural ODE to get the “continuous” embedding Recover initial sequence from the “continuous” embedding in VAE fashion As a proof of concept, I just have re-run the code from this repository and it seemed like working very well in learning spiral trajectories: Then, I decided to turn heartbeats from the electrocardiogram (ECG) to the phase portraits with x(t) as time-space and x`(t) as derivative-space (as it was presented in this work) and tried to fit with different VAE setting. This use case might be very useful for wearable devices like Mawi Band, where due to noisy or interrupted signal we have to recover it (and actually we do it with the help of deep learning, but ECG is a continuous signal, isn’t it?). Unfortunately, it doesn’t converge really well, showing all the signs of overfitting to a single form of a beat: I also have tried another experiment: to learn this autoencoder only on the parts of each beat and recover the whole waveform from it (i.e. let’s extrapolate a signal). Unfortunately, I didn’t come up with anything meaningful with extrapolating this piece of signal to the left or to the right — just collapsing to infinity, whatever I did with the hyperparameters and data preprocessing. Probably, someone of the readers may help to understand what went wrong :( It’s clear, that Neural ODEs are designed to learn relatively simple processes (that’s why we even have ordinary in the title), so we need a model that is able to model much richer families of functions. And there are two interesting approaches already: Augmented Neural ODEs: https://github.com/EmilienDupont/augmented-neural-odes Neural Jump Stochastic DEs: https://www.groundai.com/project/neural-jump-stochastic-differential-equations/1 Will take some time to explore them as well :) IMHO, Neural ODEs are not ready to be used in practice yet. The idea itself is great and by the level of innovation it reminds me of the Capsule Networks by Geoffrey Hinton, but where they are now...? As well as Neural ODEs they showed good results on the toy tasks but failed on anything close to real applications or large-scale datasets. I can see only two practical application at the moment: using the ODESolve() layers to balance speed/accuracy tradeoff in classical neural networks “squeezing” regular ODEs into the neural architectures to embed them in standard data science pipelines Personally, I am hoping for the further development of this direction (I showed some links above) to make these Neural (O)DEs represent much richer classes of functions and I will follow it closely. P.S.If you found this content useful and perspective, you can support me on Bitclout. Follow me also on the Facebook blog, where I regularly post short AI articles or news that are too short for Medium, Instagram for personal stuff and Linkedin! Contact me if you want to collaborate on interpretable AI applications or other ML projects.
[ { "code": null, "e": 829, "s": 172, "text": "Hi everyone! If you’re reading this article, most probably you’re catching up with the recent advances that happen in the AI world. The topic we will review today comes from NIPS 2018, and it will be about the best paper award from there: Neural Ordinary Differential Equations (Neural ODEs). In this article, I will try to give a brief intro and the importance of this paper, but I will emphasize the practical use and how and for what we can apply this need breed of neural networks in applications and if can at all. As always, if you want to dive straight to the code, you can check this GitHub repository, I recommend you to launch it in Google Colab." }, { "code": null, "e": 1065, "s": 829, "text": "First of all, let’s recap quickly what a beast ordinary differential equation is. It describes evolution in time of some process that depends on one variable (that’s why ordinary), and this change in time is described via a derivative:" }, { "code": null, "e": 1467, "s": 1065, "text": "Usually, we can talk about solving this differential equation, if we have some initial condition (at which point the process starts) and we want to see how the process will evolve up to some final state. The solution function is also called the integral curve (because we can integrate the equation to get the solution x(t)). Let’s try to solve the equation from the picture above using SymPy package:" }, { "code": null, "e": 1621, "s": 1467, "text": "from sympy import dsolve, Eq, symbols, Functiont = symbols('t')x = symbols('x', cls=Function)deqn1 = Eq(x(t).diff(t), 1 - x(t))sol1 = dsolve(deqn1, x(t))" }, { "code": null, "e": 1655, "s": 1621, "text": "which will return as the solution" }, { "code": null, "e": 1680, "s": 1655, "text": "Eq(x(t), C1*exp(-t) + 1)" }, { "code": null, "e": 2020, "s": 1680, "text": "where C1 is a constant, that can be determined while given some initial condition. ODEs can be solved analytically if given in the appropriate form, but normally they are solved numerically. One of the oldest and simplest algorithms is Euler’s method: the core idea is approximating the solution function step by step using tangents lines:" }, { "code": null, "e": 2153, "s": 2020, "text": "Visit the link under the picture for a more detailed explanation, but at the end, we end up with a very simple formula, for equation" }, { "code": null, "e": 2209, "s": 2153, "text": "the solution at the discretized grid of n time steps is" }, { "code": null, "e": 2716, "s": 2209, "text": "For more details on ODEs, especially how to program them and their solutions in Python, I recommend you to check out this book, it also has a lot of examples of processes in chemistry, physics and industrial fields that have such time evolution, that can be described with the ODEs. Also, for additional intuition about differential equation compared to ML models visit this resource. Meanwhile, looking at Euler’s equation doesn’t it remind you anything from the recent deep learning architectures yet...?" }, { "code": null, "e": 3432, "s": 2716, "text": "Exactly! The y_{n+1} = y_n + f(t_n, y_n) is nothing but a residual connection in ResNet, where the output of some layer is a sum of the output of the layer f() itself and the input y_n to this layer. This is basically the main idea of neural ODEs: a chain of residual blocks in a neural network is basically a solution of the ODE with the Euler method! In this case, the initial condition for the system is “time” 0, which indicates the very first layer of the neural network, and as x(0) will serve the normal input, which can be time series, image, whatever you want! The final condition at “time” t will be the desired output of the neural network: a scalar value, a vector representing classes or anything else." }, { "code": null, "e": 3743, "s": 3432, "text": "If we remember, that these residual connections are discretized time steps of the Euler method, it means, that we can regulate the depth of the neural network, just with choosing the discretizing scheme, hence, making the solution (aka neural network) more or less accurate, even making it infinite-layer like!" }, { "code": null, "e": 4098, "s": 3743, "text": "Is Euler too primitive ODE solving method? Indeed it is, so let’s replace ResNet / EulerSolverNet with some abstract concept as ODESolveNet, where ODESolve will be a function, that provides a solution to the ODE (lowkey: our neural network itself) with much better accuracy than Euler’s method. The network architecture now might look like the following:" }, { "code": null, "e": 4235, "s": 4098, "text": "nn = Network( Dense(...), # making some primary embedding ODESolve(...), # \"infinite-layer neural network\" Dense(...) # output layer)" }, { "code": null, "e": 4820, "s": 4235, "text": "We forgot about one thing... A neural network is a differentiable function, so we can train it with gradient-based optimization routines. How should we backpropagate through the ODESolve() function, which is also actually a black box in our case? In particular, we need a gradient of loss function by the input and the dynamics parameters. The mathematical trick is called adjoint sensitivity method. I will refer you to the original paper and this tutorial for more details, but the essence is described in the picture below (L stands for the main loss function we want to optimize):" }, { "code": null, "e": 5300, "s": 4820, "text": "Briefly, alongside with the original dynamical system that describes the process, the adjoint system describes the derivative states at each point of the process backward, via the chain rule (that’s where the roots of well-known backpropagation are). Exactly from it, we can obtain the derivative by the initial state, and, in a similar way, by the parameters of a function that is modeling dynamics (one “residual block”, or the discretization step in the “old” Euler’s method)." }, { "code": null, "e": 5411, "s": 5300, "text": "For more details I recommend you to watch the presentation of one of the authors of the paper himself as well:" }, { "code": null, "e": 5489, "s": 5411, "text": "First, advantages and motivation to use them instead of the “normal ResNets”:" }, { "code": null, "e": 5586, "s": 5489, "text": "Memory efficiency: we don’t need to store all the parameters and gradients while backpropagating" }, { "code": null, "e": 5733, "s": 5586, "text": "Adaptive computation: we can balance speed and accuracy with the discretization scheme, moreover, having it different while training and inference" }, { "code": null, "e": 5838, "s": 5733, "text": "Parameters efficiency: the parameters of nearby “layers” are automatically tied together (see the paper)" }, { "code": null, "e": 5894, "s": 5838, "text": "Normalizing flows new type of invertible density models" }, { "code": null, "e": 6020, "s": 5894, "text": "Continuous time series models: continuously-defined dynamics can naturally incorporate data which arrives at arbitrary times." }, { "code": null, "e": 6178, "s": 6020, "text": "The applications, according to the paper, apart of the replacing ResNet with ODENet for computer vision, that I see a bit unrealistic now, are the next ones:" }, { "code": null, "e": 6249, "s": 6178, "text": "Compressing complex ODEs into a single dynamic modeling neural network" }, { "code": null, "e": 6301, "s": 6249, "text": "Applying it for time series with missing time steps" }, { "code": null, "e": 6362, "s": 6301, "text": "Invertible normalizing flows (out of the scope of this blog)" }, { "code": null, "e": 6539, "s": 6362, "text": "For the disadvantages, consult the original paper, there are some. Enough theory, let’s check some practical examples now. Just to remind, all the code for experiments is here." }, { "code": null, "e": 7108, "s": 6539, "text": "As we could see before, differential equations are used widely do describe complex continuous processes. Of course, in real life we observe them as discrete processes, and, most importantly, a lot of observations at the time steps t_i can simply be missing. Let’s supposed you want to model such a system with a neural network. How would you deal with this kind of situation in a classical sequence modeling paradigm? Throw it onto the recurrent neural network somehow, which isn’t even designed for it. In this part, we will check how Neural ODEs will deal with them." }, { "code": null, "e": 7141, "s": 7108, "text": "Our setup will be the following:" }, { "code": null, "e": 7522, "s": 7141, "text": "Define the ODE itself we will model as a PyTorch nn.Module()Define a simple (or not really) neural network, that will model dynamics between two consequent dynamics steps from h_t to h_{t+1} or, in case of a dynamical system, x_t, and x_{t+1}.Run the optimization process that backpropagates through the ODE solver and minimizes the difference between actual and modeled dynamics." }, { "code": null, "e": 7583, "s": 7522, "text": "Define the ODE itself we will model as a PyTorch nn.Module()" }, { "code": null, "e": 7767, "s": 7583, "text": "Define a simple (or not really) neural network, that will model dynamics between two consequent dynamics steps from h_t to h_{t+1} or, in case of a dynamical system, x_t, and x_{t+1}." }, { "code": null, "e": 7905, "s": 7767, "text": "Run the optimization process that backpropagates through the ODE solver and minimizes the difference between actual and modeled dynamics." }, { "code": null, "e": 8057, "s": 7905, "text": "In all the following experiments the neural network will be just a following (which is supposedly enough to model simple functions with two variables):" }, { "code": null, "e": 8172, "s": 8057, "text": "self.net = nn.Sequential( nn.Linear(2, 50), nn.Tanh(), nn.Linear(50, 2), )" }, { "code": null, "e": 8445, "s": 8172, "text": "All further examples are highly inspired by this repository with amazing explanations. In the next subsections, I will show how the dynamical systems we model look themselves in the code and how system evolution over time and the phase portrait is being fit by the ODENet." }, { "code": null, "e": 8535, "s": 8445, "text": "In this, and all the future visualizations, the dotted lines stand for the fitting model." }, { "code": null, "e": 8672, "s": 8535, "text": "true_A = torch.tensor([[-0.1, 2.0], [-2.0, -0.1]])class Lambda(nn.Module): def forward(self, t, y): return torch.mm(y, true_A)" }, { "code": null, "e": 8702, "s": 8672, "text": "true_A = torch.randn(2, 2)/2." }, { "code": null, "e": 8784, "s": 8702, "text": "a, b, c, d = 1.5, 1.0, 3.0, 1.0true_A = torch.tensor([[0., -b*c/d], [d*a/b, 0.]])" }, { "code": null, "e": 9341, "s": 8784, "text": "true_A2 = torch.tensor([[-0.1, -0.5], [0.5, -0.1]])true_B2 = torch.tensor([[0.2, 1.], [-1, 0.2]])class Lambda2(nn.Module): def __init__(self, A, B): super(Lambda2, self).__init__() self.A = nn.Linear(2, 2, bias=False) self.A.weight = nn.Parameter(A) self.B = nn.Linear(2, 2, bias=False) self.B.weight = nn.Parameter(B) def forward(self, t, y): xTx0 = torch.sum(y * true_y0, dim=1) dxdt = torch.sigmoid(xTx0) * self.A(y - true_y0) + torch.sigmoid(-xTx0) * self.B(y + true_y0) return dxdt" }, { "code": null, "e": 9479, "s": 9341, "text": "As we can see, our single “residual block” can’t learn this process well enough, so we might make it more complex for the next functions." }, { "code": null, "e": 9582, "s": 9479, "text": "Let’s make a function fully parametrized by a multilayer perceptron with randomly initialized weights:" }, { "code": null, "e": 10176, "s": 9582, "text": "true_y0 = torch.tensor([[1., 1.]])t = torch.linspace(-15., 15., data_size)class Lambda3(nn.Module): def __init__(self): super(Lambda3, self).__init__() self.fc1 = nn.Linear(2, 25, bias = False) self.fc2 = nn.Linear(25, 50, bias = False) self.fc3 = nn.Linear(50, 10, bias = False) self.fc4 = nn.Linear(10, 2, bias = False) self.relu = nn.ELU(inplace=True) def forward(self, t, y): x = self.relu(self.fc1(y * t)) x = self.relu(self.fc2(x)) x = self.relu(self.fc3(x)) x = self.relu(self.fc4(x)) return x" }, { "code": null, "e": 10262, "s": 10176, "text": "Here 2–50–2 network fails horribly because it’s too simple, let’s increase its depth:" }, { "code": null, "e": 10483, "s": 10262, "text": "self.net = nn.Sequential( nn.Linear(2, 150), nn.Tanh(), nn.Linear(150, 50), nn.Tanh(), nn.Linear(50, 50), nn.Tanh(), nn.Linear(50, 2), )" }, { "code": null, "e": 10556, "s": 10483, "text": "Now it works more or less as expected, don’t forget to check the code :)" }, { "code": null, "e": 10698, "s": 10556, "text": "Authors also claim that they can build a generative time series model via VAE framework, using Neural ODEs as a part of it. How does it work?" }, { "code": null, "e": 10840, "s": 10698, "text": "First, we encode the input sequence with some “standard” time series algorithms, let’s say RNN to obtain the primary embedding of the process" }, { "code": null, "e": 10915, "s": 10840, "text": "Run the embedding through the Neural ODE to get the “continuous” embedding" }, { "code": null, "e": 10987, "s": 10915, "text": "Recover initial sequence from the “continuous” embedding in VAE fashion" }, { "code": null, "e": 11129, "s": 10987, "text": "As a proof of concept, I just have re-run the code from this repository and it seemed like working very well in learning spiral trajectories:" }, { "code": null, "e": 11701, "s": 11129, "text": "Then, I decided to turn heartbeats from the electrocardiogram (ECG) to the phase portraits with x(t) as time-space and x`(t) as derivative-space (as it was presented in this work) and tried to fit with different VAE setting. This use case might be very useful for wearable devices like Mawi Band, where due to noisy or interrupted signal we have to recover it (and actually we do it with the help of deep learning, but ECG is a continuous signal, isn’t it?). Unfortunately, it doesn’t converge really well, showing all the signs of overfitting to a single form of a beat:" }, { "code": null, "e": 12165, "s": 11701, "text": "I also have tried another experiment: to learn this autoencoder only on the parts of each beat and recover the whole waveform from it (i.e. let’s extrapolate a signal). Unfortunately, I didn’t come up with anything meaningful with extrapolating this piece of signal to the left or to the right — just collapsing to infinity, whatever I did with the hyperparameters and data preprocessing. Probably, someone of the readers may help to understand what went wrong :(" }, { "code": null, "e": 12419, "s": 12165, "text": "It’s clear, that Neural ODEs are designed to learn relatively simple processes (that’s why we even have ordinary in the title), so we need a model that is able to model much richer families of functions. And there are two interesting approaches already:" }, { "code": null, "e": 12497, "s": 12419, "text": "Augmented Neural ODEs: https://github.com/EmilienDupont/augmented-neural-odes" }, { "code": null, "e": 12606, "s": 12497, "text": "Neural Jump Stochastic DEs: https://www.groundai.com/project/neural-jump-stochastic-differential-equations/1" }, { "code": null, "e": 12653, "s": 12606, "text": "Will take some time to explore them as well :)" }, { "code": null, "e": 12994, "s": 12653, "text": "IMHO, Neural ODEs are not ready to be used in practice yet. The idea itself is great and by the level of innovation it reminds me of the Capsule Networks by Geoffrey Hinton, but where they are now...? As well as Neural ODEs they showed good results on the toy tasks but failed on anything close to real applications or large-scale datasets." }, { "code": null, "e": 13050, "s": 12994, "text": "I can see only two practical application at the moment:" }, { "code": null, "e": 13142, "s": 13050, "text": "using the ODESolve() layers to balance speed/accuracy tradeoff in classical neural networks" }, { "code": null, "e": 13246, "s": 13142, "text": "“squeezing” regular ODEs into the neural architectures to embed them in standard data science pipelines" }, { "code": null, "e": 13445, "s": 13246, "text": "Personally, I am hoping for the further development of this direction (I showed some links above) to make these Neural (O)DEs represent much richer classes of functions and I will follow it closely." } ]
Git Pull from GitHub
When working as a team on a project, it is important that everyone stays up to date. Any time you start working on a project, you should get the most recent changes to your local copy. With Git, you can do that with pull. pull is a combination of 2 different commands: fetch merge Let's take a closer look into how fetch, merge, and pull works. fetch gets all the change history of a tracked branch/repo. So, on your local Git, fetch updates to see what has changed on GitHub: git fetch origin remote: Enumerating objects: 5, done. remote: Counting objects: 100% (5/5), done. remote: Compressing objects: 100% (3/3), done. remote: Total 3 (delta 2), reused 0 (delta 0), pack-reused 0 Unpacking objects: 100% (3/3), 733 bytes | 3.00 KiB/s, done. From https://github.com/w3schools-test/hello-world e0b6038..d29d69f master -> origin/master Now that we have the recent changes, we can check our status: git status On branch master Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded. (use "git pull" to update your local branch) nothing to commit, working tree clean We are behind the origin/master by 1 commit. That should be the updated README.md, but lets double check by viewing the log: git log origin/master commit d29d69ffe2ee9e6df6fa0d313bb0592b50f3b853 (origin/master) Author: w3schools-test <77673807+w3schools-test@users.noreply.github.com> Date: Fri Mar 26 14:59:14 2021 +0100 Updated README.md with a line about GitHub commit e0b6038b1345e50aca8885d8fd322fc0e5765c3b (HEAD -> master) Merge: dfa79db 1f1584e Author: w3schools-test Date: Fri Mar 26 12:42:56 2021 +0100 merged with hello-world-images after fixing conflicts ... ... That looks as expected, but we can also verify by showing the differences between our local master and origin/master: git diff origin/master diff --git a/README.md b/README.md index 23a0122..a980c39 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,4 @@ Hello World repository for Git tutorial This is an example repository for the Git tutoial on https://www.w3schools.com -This repository is built step by step in the tutorial. - -It now includes steps for GitHub +This repository is built step by step in the tutorial. \ No newline at end of file That looks precisely as expected! Now we can safely merge. merge combines the current branch, with a specified branch. We have confirmed that the updates are as expected, and we can merge our current branch (master) with origin/master: git merge origin/master Updating e0b6038..d29d69f Fast-forward README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) Check our status again to confirm we are up to date: git status On branch master Your branch is up to date with 'origin/master'. nothing to commit, working tree clean There! Your local git is up to date! But what if you just want to update your local repository, without going through all those steps? pull is a combination of fetch and merge. It is used to pull all changes from a remote repository into the branch you are working on. Make another change to the Readme.md file on GitHub. Use pull to update our local Git: git pull origin remote: Enumerating objects: 5, done. remote: Counting objects: 100% (5/5), done. remote: Compressing objects: 100% (3/3), done. remote: Total 3 (delta 1), reused 0 (delta 0), pack-reused 0 Unpacking objects: 100% (3/3), 794 bytes | 1024 bytes/s, done. From https://github.com/w3schools-test/hello-world a7cdd4b..ab6b4ed master -> origin/master Updating a7cdd4b..ab6b4ed Fast-forward README.md | 2 ++ 1 file changed, 2 insertions(+) That is how you keep your local Git up to date from a remote repository. In the next chapter, we will look closer at how push works on GitHub. pull is a combination of: and then Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 85, "s": 0, "text": "When working as a team on a project, it is important that everyone stays up to date." }, { "code": null, "e": 186, "s": 85, "text": "Any time you start working on a project, you should get the most recent \nchanges to your local copy." }, { "code": null, "e": 223, "s": 186, "text": "With Git, you can do that with pull." }, { "code": null, "e": 270, "s": 223, "text": "pull is a combination of 2 different commands:" }, { "code": null, "e": 276, "s": 270, "text": "fetch" }, { "code": null, "e": 282, "s": 276, "text": "merge" }, { "code": null, "e": 346, "s": 282, "text": "Let's take a closer look into how fetch, merge, and pull works." }, { "code": null, "e": 407, "s": 346, "text": " fetch gets all the change history of a tracked branch/repo." }, { "code": null, "e": 479, "s": 407, "text": "So, on your local Git, fetch updates to see what has changed on GitHub:" }, { "code": null, "e": 847, "s": 479, "text": "git fetch origin\nremote: Enumerating objects: 5, done.\nremote: Counting objects: 100% (5/5), done.\nremote: Compressing objects: 100% (3/3), done.\nremote: Total 3 (delta 2), reused 0 (delta 0), pack-reused 0\nUnpacking objects: 100% (3/3), 733 bytes | 3.00 KiB/s, done.\nFrom https://github.com/w3schools-test/hello-world\n e0b6038..d29d69f master -> origin/master" }, { "code": null, "e": 910, "s": 847, "text": "Now that we have the recent changes, we can check our \nstatus:" }, { "code": null, "e": 1102, "s": 910, "text": "git status\nOn branch master\nYour branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.\n (use \"git pull\" to update your local branch)\n\nnothing to commit, working tree clean" }, { "code": null, "e": 1230, "s": 1102, "text": "We are behind the origin/master by 1 \ncommit. That should be the updated \nREADME.md, but lets double check by viewing the \nlog:" }, { "code": null, "e": 1697, "s": 1230, "text": "git log origin/master\ncommit d29d69ffe2ee9e6df6fa0d313bb0592b50f3b853 (origin/master)\nAuthor: w3schools-test <77673807+w3schools-test@users.noreply.github.com>\nDate: Fri Mar 26 14:59:14 2021 +0100\n\n Updated README.md with a line about GitHub\n\ncommit e0b6038b1345e50aca8885d8fd322fc0e5765c3b (HEAD -> master)\nMerge: dfa79db 1f1584e\nAuthor: w3schools-test \nDate: Fri Mar 26 12:42:56 2021 +0100\n\n merged with hello-world-images after fixing conflicts\n\n...\n..." }, { "code": null, "e": 1817, "s": 1697, "text": "That looks as expected, but we can also verify by showing the differences \nbetween our local master and \norigin/master:" }, { "code": null, "e": 2251, "s": 1817, "text": "git diff origin/master\ndiff --git a/README.md b/README.md\nindex 23a0122..a980c39 100644\n--- a/README.md\n+++ b/README.md\n@@ -2,6 +2,4 @@\n Hello World repository for Git tutorial\n This is an example repository for the Git tutoial on https://www.w3schools.com\n\n-This repository is built step by step in the tutorial.\n-\n-It now includes steps for GitHub\n+This repository is built step by step in the tutorial.\n\\ No newline at end of file" }, { "code": null, "e": 2310, "s": 2251, "text": "That looks precisely as expected! Now we can safely merge." }, { "code": null, "e": 2371, "s": 2310, "text": " merge combines the current branch, with a specified branch." }, { "code": null, "e": 2489, "s": 2371, "text": "We have confirmed that the updates are as expected, and we can merge our current branch (master) with \norigin/master:" }, { "code": null, "e": 2620, "s": 2489, "text": "git merge origin/master\nUpdating e0b6038..d29d69f\nFast-forward\n README.md | 4 +++-\n 1 file changed, 3 insertions(+), 1 deletion(-)" }, { "code": null, "e": 2673, "s": 2620, "text": "Check our status again to confirm we are up to date:" }, { "code": null, "e": 2788, "s": 2673, "text": "git status\nOn branch master\nYour branch is up to date with 'origin/master'.\n\nnothing to commit, working tree clean" }, { "code": null, "e": 2825, "s": 2788, "text": "There! Your local git is up to date!" }, { "code": null, "e": 2924, "s": 2825, "text": "But what if you just want to update your local repository, without going through \nall those steps?" }, { "code": null, "e": 3059, "s": 2924, "text": "pull is a combination of fetch and merge. It is used to pull all changes from \na remote repository into the branch you are working on." }, { "code": null, "e": 3112, "s": 3059, "text": "Make another change to the Readme.md file on GitHub." }, { "code": null, "e": 3146, "s": 3112, "text": "Use pull to update our local Git:" }, { "code": null, "e": 3607, "s": 3146, "text": "git pull origin\nremote: Enumerating objects: 5, done.\nremote: Counting objects: 100% (5/5), done.\nremote: Compressing objects: 100% (3/3), done.\nremote: Total 3 (delta 1), reused 0 (delta 0), pack-reused 0\nUnpacking objects: 100% (3/3), 794 bytes | 1024 bytes/s, done.\nFrom https://github.com/w3schools-test/hello-world\n a7cdd4b..ab6b4ed master -> origin/master\nUpdating a7cdd4b..ab6b4ed\nFast-forward\n README.md | 2 ++\n 1 file changed, 2 insertions(+)" }, { "code": null, "e": 3750, "s": 3607, "text": "That is how you keep your local Git up to date from a remote repository. In the next chapter, we will look closer at how\npush works on GitHub." }, { "code": null, "e": 3776, "s": 3750, "text": "pull is a combination of:" }, { "code": null, "e": 3788, "s": 3776, "text": " and then \n" }, { "code": null, "e": 3808, "s": 3788, "text": "\nStart the Exercise" }, { "code": null, "e": 3841, "s": 3808, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3883, "s": 3841, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3990, "s": 3883, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 4009, "s": 3990, "text": "help@w3schools.com" } ]
Convert boolean result into number/integer in JavaScript - GeeksforGeeks
02 Jul, 2019 A JavaScript boolean represents one of two values: true or false.However, if one wants to convert a variable that stores boolean value, into integer “0” or “1”, they can do so using multiple approaches. We will look into some of them in this article.The most popular methods are:Using ternary or conditional operatorUsing unary + operator.Using bitwise And (&) or bitwise Or ( | ) operator.Using Number() function. It converts data type to number. A JavaScript boolean represents one of two values: true or false.However, if one wants to convert a variable that stores boolean value, into integer “0” or “1”, they can do so using multiple approaches. We will look into some of them in this article. The most popular methods are: Using ternary or conditional operator Using unary + operator. Using bitwise And (&) or bitwise Or ( | ) operator. Using Number() function. It converts data type to number. Syntax:var i = value ? 1 : 0; var i = value ? 1 : 0; Program:<!DOCTYPE html><html> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h4>Click the button to change the boolean value into number.</h4> <script> // Initializing boolvalue as true var boolvalue = true </script> <button onclick="myFunction()">Change</button> <p>The number value of the variable is :</p> <p id="result"></p> <script> // JavaScript program to illustrate boolean // conversion using ternary operator function myFunction() { var i = boolvalue ? 1 : 0; document.getElementById("result").innerHTML = i; } </script> </center></body> </html> <!DOCTYPE html><html> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <h4>Click the button to change the boolean value into number.</h4> <script> // Initializing boolvalue as true var boolvalue = true </script> <button onclick="myFunction()">Change</button> <p>The number value of the variable is :</p> <p id="result"></p> <script> // JavaScript program to illustrate boolean // conversion using ternary operator function myFunction() { var i = boolvalue ? 1 : 0; document.getElementById("result").innerHTML = i; } </script> </center></body> </html> Output after clicking the button: Syntax:var i = + boolvalue; var i = + boolvalue; Program:<!DOCTYPE html><html><body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p>Click the button to change the boolean value.</p> <script> // Initializing boolvalue as true var boolvalue = true; </script> <button onclick="myFunction()">Change</button> <p>The value of the variable is now:</p> <p id="result"></p> <script> // JavaScript program to illustrate boolean // conversion using unary operator function myFunction(){ var i = + boolvalue; document.getElementById("result").innerHTML = i; } </script></body></html> <!DOCTYPE html><html><body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p>Click the button to change the boolean value.</p> <script> // Initializing boolvalue as true var boolvalue = true; </script> <button onclick="myFunction()">Change</button> <p>The value of the variable is now:</p> <p id="result"></p> <script> // JavaScript program to illustrate boolean // conversion using unary operator function myFunction(){ var i = + boolvalue; document.getElementById("result").innerHTML = i; } </script></body></html> Output after clicking the button: Syntax:var i = boolvalue & 1; // bitwise and var j = boolvalue | 0; // bitwise or var i = boolvalue & 1; // bitwise and var j = boolvalue | 0; // bitwise or Program:<!DOCTYPE html><html><body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p>Click the button to change the boolean value.</p> <script> // Initializing boolvalue as true var boolvalue = true; // Initializing boolvalue2 as false var boolvalue2 = false; </script> <button onclick="myFunction()">Change</button> <p>The value of the variable 1 is now:</p> <p id="result"></p> <p>The value of the variable 2 is now:</p> <p id="result2"></p> <script> // JavaScript program to illustrate boolean // conversion using bitwise operator function myFunction(){ var i = boolvalue & 1; var j = boolvalue2 | 0; document.getElementById("result").innerHTML = i; document.getElementById("result2").innerHTML = j; } </script></body></html> <!DOCTYPE html><html><body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p>Click the button to change the boolean value.</p> <script> // Initializing boolvalue as true var boolvalue = true; // Initializing boolvalue2 as false var boolvalue2 = false; </script> <button onclick="myFunction()">Change</button> <p>The value of the variable 1 is now:</p> <p id="result"></p> <p>The value of the variable 2 is now:</p> <p id="result2"></p> <script> // JavaScript program to illustrate boolean // conversion using bitwise operator function myFunction(){ var i = boolvalue & 1; var j = boolvalue2 | 0; document.getElementById("result").innerHTML = i; document.getElementById("result2").innerHTML = j; } </script></body></html> Output after clicking the button: Syntax:var i = Number(boolvalue); var i = Number(boolvalue); Program:<!DOCTYPE html><html><body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p>Click the button to change the boolean value.</p> <script> // Initializing boolvalue as true var boolvalue = true; </script> <button onclick="myFunction()">Change</button> <p>The value of the variable is now:</p> <p id="result"></p> <script> // JavaScript program to illustrate boolean // conversion using Number() function function myFunction(){ var i = Number(boolvalue); document.getElementById("result").innerHTML = i; } </script></body></html> Output after clicking the button: <!DOCTYPE html><html><body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p>Click the button to change the boolean value.</p> <script> // Initializing boolvalue as true var boolvalue = true; </script> <button onclick="myFunction()">Change</button> <p>The value of the variable is now:</p> <p id="result"></p> <script> // JavaScript program to illustrate boolean // conversion using Number() function function myFunction(){ var i = Number(boolvalue); document.getElementById("result").innerHTML = i; } </script></body></html> Output after clicking the button: JavaScript-Misc Picked JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to filter object array based on attributes? How to get character array from string in JavaScript? Lodash _.debounce() Method Angular File Upload How to remove duplicate elements from JavaScript Array ? How to get selected value in dropdown list using JavaScript ?
[ { "code": null, "e": 26653, "s": 26625, "text": "\n02 Jul, 2019" }, { "code": null, "e": 27101, "s": 26653, "text": "A JavaScript boolean represents one of two values: true or false.However, if one wants to convert a variable that stores boolean value, into integer “0” or “1”, they can do so using multiple approaches. We will look into some of them in this article.The most popular methods are:Using ternary or conditional operatorUsing unary + operator.Using bitwise And (&) or bitwise Or ( | ) operator.Using Number() function. It converts data type to number." }, { "code": null, "e": 27352, "s": 27101, "text": "A JavaScript boolean represents one of two values: true or false.However, if one wants to convert a variable that stores boolean value, into integer “0” or “1”, they can do so using multiple approaches. We will look into some of them in this article." }, { "code": null, "e": 27382, "s": 27352, "text": "The most popular methods are:" }, { "code": null, "e": 27420, "s": 27382, "text": "Using ternary or conditional operator" }, { "code": null, "e": 27444, "s": 27420, "text": "Using unary + operator." }, { "code": null, "e": 27496, "s": 27444, "text": "Using bitwise And (&) or bitwise Or ( | ) operator." }, { "code": null, "e": 27554, "s": 27496, "text": "Using Number() function. It converts data type to number." }, { "code": null, "e": 27585, "s": 27554, "text": "Syntax:var i = value ? 1 : 0;\n" }, { "code": null, "e": 27609, "s": 27585, "text": "var i = value ? 1 : 0;\n" }, { "code": null, "e": 28390, "s": 27609, "text": "Program:<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h4>Click the button to change the boolean value into number.</h4> <script> // Initializing boolvalue as true var boolvalue = true </script> <button onclick=\"myFunction()\">Change</button> <p>The number value of the variable is :</p> <p id=\"result\"></p> <script> // JavaScript program to illustrate boolean // conversion using ternary operator function myFunction() { var i = boolvalue ? 1 : 0; document.getElementById(\"result\").innerHTML = i; } </script> </center></body> </html> " }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <h4>Click the button to change the boolean value into number.</h4> <script> // Initializing boolvalue as true var boolvalue = true </script> <button onclick=\"myFunction()\">Change</button> <p>The number value of the variable is :</p> <p id=\"result\"></p> <script> // JavaScript program to illustrate boolean // conversion using ternary operator function myFunction() { var i = boolvalue ? 1 : 0; document.getElementById(\"result\").innerHTML = i; } </script> </center></body> </html> ", "e": 29163, "s": 28390, "text": null }, { "code": null, "e": 29197, "s": 29163, "text": "Output after clicking the button:" }, { "code": null, "e": 29226, "s": 29197, "text": "Syntax:var i = + boolvalue;\n" }, { "code": null, "e": 29248, "s": 29226, "text": "var i = + boolvalue;\n" }, { "code": null, "e": 29952, "s": 29248, "text": "Program:<!DOCTYPE html><html><body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p>Click the button to change the boolean value.</p> <script> // Initializing boolvalue as true var boolvalue = true; </script> <button onclick=\"myFunction()\">Change</button> <p>The value of the variable is now:</p> <p id=\"result\"></p> <script> // JavaScript program to illustrate boolean // conversion using unary operator function myFunction(){ var i = + boolvalue; document.getElementById(\"result\").innerHTML = i; } </script></body></html> " }, { "code": "<!DOCTYPE html><html><body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p>Click the button to change the boolean value.</p> <script> // Initializing boolvalue as true var boolvalue = true; </script> <button onclick=\"myFunction()\">Change</button> <p>The value of the variable is now:</p> <p id=\"result\"></p> <script> // JavaScript program to illustrate boolean // conversion using unary operator function myFunction(){ var i = + boolvalue; document.getElementById(\"result\").innerHTML = i; } </script></body></html> ", "e": 30648, "s": 29952, "text": null }, { "code": null, "e": 30682, "s": 30648, "text": "Output after clicking the button:" }, { "code": null, "e": 30765, "s": 30682, "text": "Syntax:var i = boolvalue & 1; // bitwise and\nvar j = boolvalue | 0; // bitwise or\n" }, { "code": null, "e": 30841, "s": 30765, "text": "var i = boolvalue & 1; // bitwise and\nvar j = boolvalue | 0; // bitwise or\n" }, { "code": null, "e": 31815, "s": 30841, "text": "Program:<!DOCTYPE html><html><body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p>Click the button to change the boolean value.</p> <script> // Initializing boolvalue as true var boolvalue = true; // Initializing boolvalue2 as false var boolvalue2 = false; </script> <button onclick=\"myFunction()\">Change</button> <p>The value of the variable 1 is now:</p> <p id=\"result\"></p> <p>The value of the variable 2 is now:</p> <p id=\"result2\"></p> <script> // JavaScript program to illustrate boolean // conversion using bitwise operator function myFunction(){ var i = boolvalue & 1; var j = boolvalue2 | 0; document.getElementById(\"result\").innerHTML = i; document.getElementById(\"result2\").innerHTML = j; } </script></body></html> " }, { "code": "<!DOCTYPE html><html><body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p>Click the button to change the boolean value.</p> <script> // Initializing boolvalue as true var boolvalue = true; // Initializing boolvalue2 as false var boolvalue2 = false; </script> <button onclick=\"myFunction()\">Change</button> <p>The value of the variable 1 is now:</p> <p id=\"result\"></p> <p>The value of the variable 2 is now:</p> <p id=\"result2\"></p> <script> // JavaScript program to illustrate boolean // conversion using bitwise operator function myFunction(){ var i = boolvalue & 1; var j = boolvalue2 | 0; document.getElementById(\"result\").innerHTML = i; document.getElementById(\"result2\").innerHTML = j; } </script></body></html> ", "e": 32781, "s": 31815, "text": null }, { "code": null, "e": 32815, "s": 32781, "text": "Output after clicking the button:" }, { "code": null, "e": 32850, "s": 32815, "text": "Syntax:var i = Number(boolvalue);\n" }, { "code": null, "e": 32878, "s": 32850, "text": "var i = Number(boolvalue);\n" }, { "code": null, "e": 33624, "s": 32878, "text": "Program:<!DOCTYPE html><html><body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p>Click the button to change the boolean value.</p> <script> // Initializing boolvalue as true var boolvalue = true; </script> <button onclick=\"myFunction()\">Change</button> <p>The value of the variable is now:</p> <p id=\"result\"></p> <script> // JavaScript program to illustrate boolean // conversion using Number() function function myFunction(){ var i = Number(boolvalue); document.getElementById(\"result\").innerHTML = i; } </script></body></html> Output after clicking the button:" }, { "code": "<!DOCTYPE html><html><body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p>Click the button to change the boolean value.</p> <script> // Initializing boolvalue as true var boolvalue = true; </script> <button onclick=\"myFunction()\">Change</button> <p>The value of the variable is now:</p> <p id=\"result\"></p> <script> // JavaScript program to illustrate boolean // conversion using Number() function function myFunction(){ var i = Number(boolvalue); document.getElementById(\"result\").innerHTML = i; } </script></body></html> ", "e": 34329, "s": 33624, "text": null }, { "code": null, "e": 34363, "s": 34329, "text": "Output after clicking the button:" }, { "code": null, "e": 34379, "s": 34363, "text": "JavaScript-Misc" }, { "code": null, "e": 34386, "s": 34379, "text": "Picked" }, { "code": null, "e": 34397, "s": 34386, "text": "JavaScript" }, { "code": null, "e": 34495, "s": 34397, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34535, "s": 34495, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34596, "s": 34535, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 34637, "s": 34596, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 34659, "s": 34637, "text": "JavaScript | Promises" }, { "code": null, "e": 34707, "s": 34659, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 34761, "s": 34707, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 34788, "s": 34761, "text": "Lodash _.debounce() Method" }, { "code": null, "e": 34808, "s": 34788, "text": "Angular File Upload" }, { "code": null, "e": 34865, "s": 34808, "text": "How to remove duplicate elements from JavaScript Array ?" } ]
COVID-19 Peak Prediction using Logistic Function - GeeksforGeeks
05 Aug, 2021 Making fast and accurate decisions are vital these days and especially now when the world is facing such a phenomenon as COVID-19, therefore, counting on current as well as projected information is decisive for this process. In this matter, we have applied a model in which is possible to observe the peak in specific country cases, using current statistical information, hoping it can be used as foundation support to take action in this scenario. To accomplish this objective, Non-linear regression has been applied to the model, using a logistic function. This process consists of: Data Cleaning Choosing the most suitable equation which can be graphically adapted to the data, in this case, Logistic Function (Sigmoid) Database Normalization Fitting of the model to our dataset using “curve_fit” process, obtaining new reference beta. Model evaluation Dataset is public, and it is available at Data.europa.eu following this link: DATASETData Cleaning: The data available has been originally labelled. We were able to identify two countries which did not mention geographical location, this information was added however it wouldn ́t contribute to the model significantly. A new column is added to the dataset named “n-day” to show the consecutive number of days. Code: Importing Libraries Python3 # import librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt % matplotlib inline # sklearn specific function to obtain R2 calculationsfrom sklearn.metrics import r2_score Code: Using data Python3 # Data Readingdf = pd.read_excel("C:/BaseDato / COVID-19-310302020chi.xlsx")df.head() Output: Code: Python3 # Initial Data Graphicsplt.figure(figsize =(8, 5)) x_data, y_data = (df["Nday"].values, df["cases"].values) plt.plot(x_data, y_data, 'ro')plt.title('Data: Cases Vs Day of infection')plt.ylabel('Cases')plt.xlabel('Day Number') Output: Code: Choosing the modelWe apply logistic function, a specific case of sigmoid functions, considering that the original curve starts with slow growth remaining nearly flat for a time before increasing, eventually it could descend or maintain its growth in the way of an exponential curve. The formula for the logistic function is: Y = 1/(1+e^B1(X-B2)) Code: Construction of the model Python3 # Definition of the logistic functiondef sigmoid(x, Beta_1, Beta_2): y = 1 / (1 + np.exp(-Beta_1*(x-Beta_2))) return y # Choosing initial arbitrary beta parametersbeta_1 = 0.09beta_2 = 305 # application of the logistic function using betaY_pred = sigmoid(x_data, beta_1, beta_2) # point predictionplt.plot(x_data, Y_pred * 15000000000000., label = "Model")plt.plot(x_data, y_data, 'ro', label = "Data")plt.title('Data Vs Model')plt.legend(loc ='best')plt.ylabel('Cases')plt.xlabel('Day Number') Output: Data Normalization: Here, variables x and y are normalized assigning them a 0 to 1 range (depending on each case). So both can be interpreted in equal relevance. Reference – information Code: Python3 xdata = x_data / max(x_data)ydata = y_data / max(y_data) Model Fitting: The objective is to obtain new B optimal parameters, to adjust the model to our data. We use “curve_fit” which uses non-linear least squares to fit the sigmoid function. Being “popt” our optimized parameters. Code: Input Python3 from scipy.optimize import curve_fitpopt, pcov = curve_fit(sigmoid, xdata, data) # imprimir los parámetros finalesprint(" beta_1 = % f, beta_2 = % f" % (popt[0], popt[1])) Output: beta_1 = 9.833364, beta_2 = 0.777140 Code: New Beta values are applied to the model Python3 x = np.linspace(0, 40, 4)x = x / max(x) plt.figure(figsize = (8, 5)) y = sigmoid(x, *popt) plt.plot(xdata, ydata, 'ro', label ='data')plt.plot(x, y, linewidth = 3.0, label ='fit')plt.title("Data Vs Fit model")plt.legend(loc ='best')plt.ylabel('Cases')plt.xlabel('Day Number')plt.show() Model Evaluation: The model is ready to be evaluated. The data is split in at 80:20, for training and testing respectively. The data is applied to the model obtaining the corresponding statistical means to evaluate the distance of the resulting data from the regression line. Code: Input Python3 # Model accuracy calculation# Splitting training and testing data L = np.random.rand(len(df)) < 0.8 # 80 % training datatrain_x = xdata[L]test_x = xdata[~L]train_y = ydata[L]test_y = ydata[~L] # Construction of the modelpopt, pcov = curve_fit(sigmoid, train_x, train_y) # Predicting using testing modely_predic = sigmoid(test_x, *popt) # Evaluationprint("Mean Absolute Error: %.2f" % np.mean(np.absolute(y_predic - test_y)))print("Mean Square Error (MSE): %.2f" % np.mean(( test_y - y_predic)**2))print("R2-score: %.2f" % r2_score(y_predic, test_y)) Output: Mean Absolute Error: 0.06 Mean Square Error (MSE): 0.01 R2-score: 0.93 anikakapoor ML-Regression Regression Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Reinforcement learning Activation functions in Neural Networks Decision Tree Introduction with example Introduction to Recurrent Neural Network Support Vector Machine Algorithm Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25973, "s": 25945, "text": "\n05 Aug, 2021" }, { "code": null, "e": 26559, "s": 25973, "text": "Making fast and accurate decisions are vital these days and especially now when the world is facing such a phenomenon as COVID-19, therefore, counting on current as well as projected information is decisive for this process. In this matter, we have applied a model in which is possible to observe the peak in specific country cases, using current statistical information, hoping it can be used as foundation support to take action in this scenario. To accomplish this objective, Non-linear regression has been applied to the model, using a logistic function. This process consists of: " }, { "code": null, "e": 26573, "s": 26559, "text": "Data Cleaning" }, { "code": null, "e": 26697, "s": 26573, "text": "Choosing the most suitable equation which can be graphically adapted to the data, in this case, Logistic Function (Sigmoid)" }, { "code": null, "e": 26720, "s": 26697, "text": "Database Normalization" }, { "code": null, "e": 26813, "s": 26720, "text": "Fitting of the model to our dataset using “curve_fit” process, obtaining new reference beta." }, { "code": null, "e": 26830, "s": 26813, "text": "Model evaluation" }, { "code": null, "e": 27241, "s": 26830, "text": "Dataset is public, and it is available at Data.europa.eu following this link: DATASETData Cleaning: The data available has been originally labelled. We were able to identify two countries which did not mention geographical location, this information was added however it wouldn ́t contribute to the model significantly. A new column is added to the dataset named “n-day” to show the consecutive number of days." }, { "code": null, "e": 27268, "s": 27241, "text": "Code: Importing Libraries " }, { "code": null, "e": 27276, "s": 27268, "text": "Python3" }, { "code": "# import librariesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt % matplotlib inline # sklearn specific function to obtain R2 calculationsfrom sklearn.metrics import r2_score", "e": 27473, "s": 27276, "text": null }, { "code": null, "e": 27490, "s": 27473, "text": "Code: Using data" }, { "code": null, "e": 27498, "s": 27490, "text": "Python3" }, { "code": "# Data Readingdf = pd.read_excel(\"C:/BaseDato / COVID-19-310302020chi.xlsx\")df.head()", "e": 27584, "s": 27498, "text": null }, { "code": null, "e": 27593, "s": 27584, "text": "Output: " }, { "code": null, "e": 27600, "s": 27593, "text": "Code: " }, { "code": null, "e": 27608, "s": 27600, "text": "Python3" }, { "code": "# Initial Data Graphicsplt.figure(figsize =(8, 5)) x_data, y_data = (df[\"Nday\"].values, df[\"cases\"].values) plt.plot(x_data, y_data, 'ro')plt.title('Data: Cases Vs Day of infection')plt.ylabel('Cases')plt.xlabel('Day Number')", "e": 27834, "s": 27608, "text": null }, { "code": null, "e": 27843, "s": 27834, "text": "Output: " }, { "code": null, "e": 28133, "s": 27843, "text": "Code: Choosing the modelWe apply logistic function, a specific case of sigmoid functions, considering that the original curve starts with slow growth remaining nearly flat for a time before increasing, eventually it could descend or maintain its growth in the way of an exponential curve. " }, { "code": null, "e": 28176, "s": 28133, "text": "The formula for the logistic function is: " }, { "code": null, "e": 28197, "s": 28176, "text": "Y = 1/(1+e^B1(X-B2))" }, { "code": null, "e": 28230, "s": 28197, "text": "Code: Construction of the model " }, { "code": null, "e": 28238, "s": 28230, "text": "Python3" }, { "code": "# Definition of the logistic functiondef sigmoid(x, Beta_1, Beta_2): y = 1 / (1 + np.exp(-Beta_1*(x-Beta_2))) return y # Choosing initial arbitrary beta parametersbeta_1 = 0.09beta_2 = 305 # application of the logistic function using betaY_pred = sigmoid(x_data, beta_1, beta_2) # point predictionplt.plot(x_data, Y_pred * 15000000000000., label = \"Model\")plt.plot(x_data, y_data, 'ro', label = \"Data\")plt.title('Data Vs Model')plt.legend(loc ='best')plt.ylabel('Cases')plt.xlabel('Day Number')", "e": 28741, "s": 28238, "text": null }, { "code": null, "e": 28750, "s": 28741, "text": "Output: " }, { "code": null, "e": 28936, "s": 28750, "text": "Data Normalization: Here, variables x and y are normalized assigning them a 0 to 1 range (depending on each case). So both can be interpreted in equal relevance. Reference – information" }, { "code": null, "e": 28944, "s": 28936, "text": "Code: " }, { "code": null, "e": 28952, "s": 28944, "text": "Python3" }, { "code": "xdata = x_data / max(x_data)ydata = y_data / max(y_data)", "e": 29009, "s": 28952, "text": null }, { "code": null, "e": 29233, "s": 29009, "text": "Model Fitting: The objective is to obtain new B optimal parameters, to adjust the model to our data. We use “curve_fit” which uses non-linear least squares to fit the sigmoid function. Being “popt” our optimized parameters." }, { "code": null, "e": 29247, "s": 29233, "text": "Code: Input " }, { "code": null, "e": 29255, "s": 29247, "text": "Python3" }, { "code": "from scipy.optimize import curve_fitpopt, pcov = curve_fit(sigmoid, xdata, data) # imprimir los parámetros finalesprint(\" beta_1 = % f, beta_2 = % f\" % (popt[0], popt[1]))", "e": 29428, "s": 29255, "text": null }, { "code": null, "e": 29437, "s": 29428, "text": "Output: " }, { "code": null, "e": 29474, "s": 29437, "text": "beta_1 = 9.833364, beta_2 = 0.777140" }, { "code": null, "e": 29523, "s": 29474, "text": "Code: New Beta values are applied to the model " }, { "code": null, "e": 29531, "s": 29523, "text": "Python3" }, { "code": "x = np.linspace(0, 40, 4)x = x / max(x) plt.figure(figsize = (8, 5)) y = sigmoid(x, *popt) plt.plot(xdata, ydata, 'ro', label ='data')plt.plot(x, y, linewidth = 3.0, label ='fit')plt.title(\"Data Vs Fit model\")plt.legend(loc ='best')plt.ylabel('Cases')plt.xlabel('Day Number')plt.show()", "e": 29817, "s": 29531, "text": null }, { "code": null, "e": 30093, "s": 29817, "text": "Model Evaluation: The model is ready to be evaluated. The data is split in at 80:20, for training and testing respectively. The data is applied to the model obtaining the corresponding statistical means to evaluate the distance of the resulting data from the regression line." }, { "code": null, "e": 30107, "s": 30093, "text": "Code: Input " }, { "code": null, "e": 30115, "s": 30107, "text": "Python3" }, { "code": "# Model accuracy calculation# Splitting training and testing data L = np.random.rand(len(df)) < 0.8 # 80 % training datatrain_x = xdata[L]test_x = xdata[~L]train_y = ydata[L]test_y = ydata[~L] # Construction of the modelpopt, pcov = curve_fit(sigmoid, train_x, train_y) # Predicting using testing modely_predic = sigmoid(test_x, *popt) # Evaluationprint(\"Mean Absolute Error: %.2f\" % np.mean(np.absolute(y_predic - test_y)))print(\"Mean Square Error (MSE): %.2f\" % np.mean(( test_y - y_predic)**2))print(\"R2-score: %.2f\" % r2_score(y_predic, test_y))", "e": 30665, "s": 30115, "text": null }, { "code": null, "e": 30674, "s": 30665, "text": "Output: " }, { "code": null, "e": 30745, "s": 30674, "text": "Mean Absolute Error: 0.06\nMean Square Error (MSE): 0.01\nR2-score: 0.93" }, { "code": null, "e": 30759, "s": 30747, "text": "anikakapoor" }, { "code": null, "e": 30773, "s": 30759, "text": "ML-Regression" }, { "code": null, "e": 30784, "s": 30773, "text": "Regression" }, { "code": null, "e": 30801, "s": 30784, "text": "Machine Learning" }, { "code": null, "e": 30808, "s": 30801, "text": "Python" }, { "code": null, "e": 30825, "s": 30808, "text": "Machine Learning" }, { "code": null, "e": 30923, "s": 30825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30946, "s": 30923, "text": "Reinforcement learning" }, { "code": null, "e": 30986, "s": 30946, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 31026, "s": 30986, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 31067, "s": 31026, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 31100, "s": 31067, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 31128, "s": 31100, "text": "Read JSON file using Python" }, { "code": null, "e": 31178, "s": 31128, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 31200, "s": 31178, "text": "Python map() function" } ]
How to send row data when clicking button using javascript?
15 Sep, 2020 In this article we will learn how to send and access row data when clicking a button using JavaScript. The below example contains a simple Bootstrap table. Each table row (<tr>) has an id and a submit button. When the button corresponding to a row is clicked, the row’s data is displayed using alert. Approach: We get the row id of the row whose button was clicked using “event.target.parentNode.parentNode.id”. Here, “event.targent” returns the element that triggered the event (clicking the button), which in this case is <input>. “event.target.parentNode” refers to parent of <input>, that is <td>. “event.target.parentNode.parentNode()” refers to the parent of <td>, that is <tr>. Therefore, var rowId stores id of the row whose button was clicked. Now we want to access the data inside this particular row. All data elements have class=”row-data”. “document.getElementById(rowId).querySelectorAll(“.row-data”) ” returns an array of all elements with “row-data” class inside the element (row) whose id is given by rowId. The array is stored in var “data” variable. We can access the data using data[0].innerHTML (name) and so on. Solution: <!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous" /> </head> <body> <!-- Bootstrap table --> <table class="table"> <tbody> <tr> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">Age</th> <th scope="col">Submit</th> </tr> <tr id="1"> <th scope="row">1</th> <td class="row-data">Sara</td> <td class="row-data">23</td> <td><input type="button" value="submit" onclick="show()" /></td> </tr> <tr id="2"> <th scope="row">2</th> <td class="row-data">John</td> <td class="row-data">30</td> <td><input type="button" value="submit" onclick="show()" /></td> </tr> <tr id="3"> <th scope="row">3</th> <td class="row-data">Naman</td> <td class="row-data">20</td> <td><input type="button" value="submit" onclick="show()" /></td> </tr> </tbody> </table> <script> function show() { var rowId = event.target.parentNode.parentNode.id; //this gives id of tr whose button was clicked var data = document.getElementById(rowId).querySelectorAll(".row-data"); /*returns array of all elements with "row-data" class within the row with given id*/ var name = data[0].innerHTML; var age = data[1].innerHTML; alert("Name: " + name + "\nAge: " + age); } </script> </body></html> Output before button click: Output after clicking 3rd button: JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Sep, 2020" }, { "code": null, "e": 131, "s": 28, "text": "In this article we will learn how to send and access row data when clicking a button using JavaScript." }, { "code": null, "e": 331, "s": 131, "text": "The below example contains a simple Bootstrap table. Each table row (<tr>) has an id and a submit button. When the button corresponding to a row is clicked, the row’s data is displayed using alert. " }, { "code": null, "e": 341, "s": 331, "text": "Approach:" }, { "code": null, "e": 785, "s": 341, "text": "We get the row id of the row whose button was clicked using “event.target.parentNode.parentNode.id”. Here, “event.targent” returns the element that triggered the event (clicking the button), which in this case is <input>. “event.target.parentNode” refers to parent of <input>, that is <td>. “event.target.parentNode.parentNode()” refers to the parent of <td>, that is <tr>. Therefore, var rowId stores id of the row whose button was clicked." }, { "code": null, "e": 1166, "s": 785, "text": "Now we want to access the data inside this particular row. All data elements have class=”row-data”. “document.getElementById(rowId).querySelectorAll(“.row-data”) ” returns an array of all elements with “row-data” class inside the element (row) whose id is given by rowId. The array is stored in var “data” variable. We can access the data using data[0].innerHTML (name) and so on." }, { "code": null, "e": 1176, "s": 1166, "text": "Solution:" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\" integrity=\"sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z\" crossorigin=\"anonymous\" /> </head> <body> <!-- Bootstrap table --> <table class=\"table\"> <tbody> <tr> <th scope=\"col\">#</th> <th scope=\"col\">Name</th> <th scope=\"col\">Age</th> <th scope=\"col\">Submit</th> </tr> <tr id=\"1\"> <th scope=\"row\">1</th> <td class=\"row-data\">Sara</td> <td class=\"row-data\">23</td> <td><input type=\"button\" value=\"submit\" onclick=\"show()\" /></td> </tr> <tr id=\"2\"> <th scope=\"row\">2</th> <td class=\"row-data\">John</td> <td class=\"row-data\">30</td> <td><input type=\"button\" value=\"submit\" onclick=\"show()\" /></td> </tr> <tr id=\"3\"> <th scope=\"row\">3</th> <td class=\"row-data\">Naman</td> <td class=\"row-data\">20</td> <td><input type=\"button\" value=\"submit\" onclick=\"show()\" /></td> </tr> </tbody> </table> <script> function show() { var rowId = event.target.parentNode.parentNode.id; //this gives id of tr whose button was clicked var data = document.getElementById(rowId).querySelectorAll(\".row-data\"); /*returns array of all elements with \"row-data\" class within the row with given id*/ var name = data[0].innerHTML; var age = data[1].innerHTML; alert(\"Name: \" + name + \"\\nAge: \" + age); } </script> </body></html>", "e": 3429, "s": 1176, "text": null }, { "code": null, "e": 3457, "s": 3429, "text": "Output before button click:" }, { "code": null, "e": 3491, "s": 3457, "text": "Output after clicking 3rd button:" }, { "code": null, "e": 3507, "s": 3491, "text": "JavaScript-Misc" }, { "code": null, "e": 3518, "s": 3507, "text": "JavaScript" }, { "code": null, "e": 3535, "s": 3518, "text": "Web Technologies" } ]
C# | Type.GetFields() Method
05 Dec, 2019 Type.GetFields() Method is used to get the fields of the current Type. There are 2 methods in the overload list of this method as follows: GetFields() Method GetFields(BindingFlags) Method This method is used to return all the public fields of the current Type. Syntax: public System.Reflection.FieldInfo[] GetFields (); Return Value: This method returns an array of FieldInfo objects representing all the public fields defined for the current Type. Or, an empty array of type FieldInfo, if no public fields are defined for the current Type. Below programs illustrate the use of Type.GetFields() Method: Example 1: // C# program to demonstrate the// Type.GetFields() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { // Getting array of Fields by // using GetField() Method FieldInfo[] info = objType.GetFields(BindingFlags.Public | BindingFlags.Static); // Display the Result Console.Write("Fields of current type is as Follow: "); for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student{ public string Name = "Rahul"; public string Dept = "Electrical"; public int Roll = 10; public static int id = 02;} Fields of current type is as Follow: System.Int32 id Example 2: For if no public field is defined // C# program to demonstrate the// Type.GetFields(String) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { // Getting array of Fields by // using GetField() Method FieldInfo[] info = objType.GetFields(); // Display the Result Console.Write("Public Fields of current type is as follow: "); if (info.Length != 0) { for (int i = 0; i < info.Length; i++) Console.WriteLine(" {0}", info[i]); } else Console.WriteLine("No public fields are defined for the current Type."); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student{ } Public Fields of current type is as follow: No public fields are defined for the current Type. This method is used to search for the fields defined for the current Type, using the specified binding when overridden in a derived class, constraints. Syntax: public abstract System.Reflection.FieldInfo[] GetFields (System.Reflection.BindingFlags bindingAttr);Here, bindingAttr is a bitmask comprised of one or more BindingFlags that specify how the search is conducted or Zero, to return null. Return Value: This method returns an array of FieldInfo objects representing all fields defined for the current Type that match the specified binding constraints. Or, an empty array of type FieldInfo, if no fields are defined for the current Type, or if none of the defined fields match the binding constraints. Below programs illustrate the use of the above-discussed method: Example 1: // C# program to demonstrate the // Type.GetField(String) // Method using System; using System.Globalization; using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // Creating try-catch block for handling Exception try { // You must specify either BindingFlags.Instance or BindingFlags.Static // and Specify BindingFlags.Public // to include public fields in the search. BindingFlags battr = BindingFlags.Public | BindingFlags.Instance; // Getting FieldInfo by // using GetField() Method FieldInfo info = objType.GetField("Name", battr); // Display the Result Console.WriteLine("FieldInfo is - {0}",info); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } } // Defining class Studentpublic class Student{ public string Name = "Rahul"; public string Dept = "Electrical"; public int Roll = 10;} FieldInfo is - System.String Name Example 2: For ArgumentNullException // C# program to demonstrate the // Type.GetFields(String) // Method using System; using System.Globalization; using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Book); // Creating try-catch block for handling Exception try { // Getting array of Fields by // using GetField() Method FieldInfo[] info = objType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); // Display the Result Console.WriteLine("Fields of current type is as follow :-"); for(int i=0; i<info.Length; i++) Console.WriteLine(" {0}",info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write("name is null."); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } } // Defining class Studentpublic class Book{ public string Name = "Element of Physics"; public string Author = "R.S. Agrwal"; public static int Price = 500; private string metadata = "djdieeiie"; } FieldInfo is - System.String Name Reference: https://docs.microsoft.com/en-us/dotnet/api/system.type.getfields?view=netframework-4.8 CSharp-method CSharp-Type-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Dec, 2019" }, { "code": null, "e": 167, "s": 28, "text": "Type.GetFields() Method is used to get the fields of the current Type. There are 2 methods in the overload list of this method as follows:" }, { "code": null, "e": 186, "s": 167, "text": "GetFields() Method" }, { "code": null, "e": 217, "s": 186, "text": "GetFields(BindingFlags) Method" }, { "code": null, "e": 290, "s": 217, "text": "This method is used to return all the public fields of the current Type." }, { "code": null, "e": 349, "s": 290, "text": "Syntax: public System.Reflection.FieldInfo[] GetFields ();" }, { "code": null, "e": 570, "s": 349, "text": "Return Value: This method returns an array of FieldInfo objects representing all the public fields defined for the current Type. Or, an empty array of type FieldInfo, if no public fields are defined for the current Type." }, { "code": null, "e": 632, "s": 570, "text": "Below programs illustrate the use of Type.GetFields() Method:" }, { "code": null, "e": 643, "s": 632, "text": "Example 1:" }, { "code": "// C# program to demonstrate the// Type.GetFields() Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { // Getting array of Fields by // using GetField() Method FieldInfo[] info = objType.GetFields(BindingFlags.Public | BindingFlags.Static); // Display the Result Console.Write(\"Fields of current type is as Follow: \"); for (int i = 0; i < info.Length; i++) Console.WriteLine(\" {0}\", info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student{ public string Name = \"Rahul\"; public string Dept = \"Electrical\"; public int Roll = 10; public static int id = 02;}", "e": 1804, "s": 643, "text": null }, { "code": null, "e": 1859, "s": 1804, "text": "Fields of current type is as Follow: System.Int32 id\n" }, { "code": null, "e": 1904, "s": 1859, "text": "Example 2: For if no public field is defined" }, { "code": "// C# program to demonstrate the// Type.GetFields(String) Methodusing System;using System.Globalization;using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // try-catch block for handling Exception try { // Getting array of Fields by // using GetField() Method FieldInfo[] info = objType.GetFields(); // Display the Result Console.Write(\"Public Fields of current type is as follow: \"); if (info.Length != 0) { for (int i = 0; i < info.Length; i++) Console.WriteLine(\" {0}\", info[i]); } else Console.WriteLine(\"No public fields are defined for the current Type.\"); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }} // Defining class Studentpublic class Student{ }", "e": 3084, "s": 1904, "text": null }, { "code": null, "e": 3180, "s": 3084, "text": "Public Fields of current type is as follow: No public fields are defined for the current Type.\n" }, { "code": null, "e": 3332, "s": 3180, "text": "This method is used to search for the fields defined for the current Type, using the specified binding when overridden in a derived class, constraints." }, { "code": null, "e": 3576, "s": 3332, "text": "Syntax: public abstract System.Reflection.FieldInfo[] GetFields (System.Reflection.BindingFlags bindingAttr);Here, bindingAttr is a bitmask comprised of one or more BindingFlags that specify how the search is conducted or Zero, to return null." }, { "code": null, "e": 3888, "s": 3576, "text": "Return Value: This method returns an array of FieldInfo objects representing all fields defined for the current Type that match the specified binding constraints. Or, an empty array of type FieldInfo, if no fields are defined for the current Type, or if none of the defined fields match the binding constraints." }, { "code": null, "e": 3953, "s": 3888, "text": "Below programs illustrate the use of the above-discussed method:" }, { "code": null, "e": 3964, "s": 3953, "text": "Example 1:" }, { "code": "// C# program to demonstrate the // Type.GetField(String) // Method using System; using System.Globalization; using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Student); // Creating try-catch block for handling Exception try { // You must specify either BindingFlags.Instance or BindingFlags.Static // and Specify BindingFlags.Public // to include public fields in the search. BindingFlags battr = BindingFlags.Public | BindingFlags.Instance; // Getting FieldInfo by // using GetField() Method FieldInfo info = objType.GetField(\"Name\", battr); // Display the Result Console.WriteLine(\"FieldInfo is - {0}\",info); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } } // Defining class Studentpublic class Student{ public string Name = \"Rahul\"; public string Dept = \"Electrical\"; public int Roll = 10;}", "e": 5288, "s": 3964, "text": null }, { "code": null, "e": 5323, "s": 5288, "text": "FieldInfo is - System.String Name\n" }, { "code": null, "e": 5360, "s": 5323, "text": "Example 2: For ArgumentNullException" }, { "code": "// C# program to demonstrate the // Type.GetFields(String) // Method using System; using System.Globalization; using System.Reflection; class GFG { // Main Method public static void Main() { // Declaring and initializing object of Type Type objType = typeof(Book); // Creating try-catch block for handling Exception try { // Getting array of Fields by // using GetField() Method FieldInfo[] info = objType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); // Display the Result Console.WriteLine(\"Fields of current type is as follow :-\"); for(int i=0; i<info.Length; i++) Console.WriteLine(\" {0}\",info[i]); } // catch ArgumentNullException here catch (ArgumentNullException e) { Console.Write(\"name is null.\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } } // Defining class Studentpublic class Book{ public string Name = \"Element of Physics\"; public string Author = \"R.S. Agrwal\"; public static int Price = 500; private string metadata = \"djdieeiie\"; }", "e": 6618, "s": 5360, "text": null }, { "code": null, "e": 6653, "s": 6618, "text": "FieldInfo is - System.String Name\n" }, { "code": null, "e": 6664, "s": 6653, "text": "Reference:" }, { "code": null, "e": 6752, "s": 6664, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.type.getfields?view=netframework-4.8" }, { "code": null, "e": 6766, "s": 6752, "text": "CSharp-method" }, { "code": null, "e": 6784, "s": 6766, "text": "CSharp-Type-Class" }, { "code": null, "e": 6787, "s": 6784, "text": "C#" } ]
Stack clear() method in Java with Example
24 Dec, 2018 The Java.util.Stack.clear() method is used to remove all the elements from a Stack. Using the clear() method only clears all the element from the Stack and does not delete the Stack. In other words, we can say that the clear() method is used to only empty an existing Stack. Syntax: Stack.clear() Parameters: The method does not take any parameter Return Value: The function does not returns any value. Below programs illustrate the Java.util.Stack.clear() method. Example 1: // Java code to illustrate clear()import java.util.*; public class GFG { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add("Welcome"); stack.add("To"); stack.add("Geeks"); stack.add("4"); stack.add("Geeks"); // Displaying the Stack System.out.println("Stack: " + stack); // Clearing the Stack using clear() method stack.clear(); // Displaying the final Stack after clearing; System.out.println("The final Stack: " + stack); }} Stack: [Welcome, To, Geeks, 4, Geeks] The final Stack: [] Example 2: // Java code to illustrate clear()import java.util.*; public class GFG { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements into the Queue stack.add(10); stack.add(15); stack.add(30); stack.add(20); stack.add(5); // Displaying the Stack System.out.println("Stack: " + stack); // Clearing the Stack using clear() method stack.clear(); // Displaying the final Stack after clearing; System.out.println("The final Stack: " + stack); }} Stack: [10, 15, 30, 20, 5] The final Stack: [] Java - util package Java-Collections Java-Functions Java-Stack Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2018" }, { "code": null, "e": 303, "s": 28, "text": "The Java.util.Stack.clear() method is used to remove all the elements from a Stack. Using the clear() method only clears all the element from the Stack and does not delete the Stack. In other words, we can say that the clear() method is used to only empty an existing Stack." }, { "code": null, "e": 311, "s": 303, "text": "Syntax:" }, { "code": null, "e": 325, "s": 311, "text": "Stack.clear()" }, { "code": null, "e": 376, "s": 325, "text": "Parameters: The method does not take any parameter" }, { "code": null, "e": 431, "s": 376, "text": "Return Value: The function does not returns any value." }, { "code": null, "e": 493, "s": 431, "text": "Below programs illustrate the Java.util.Stack.clear() method." }, { "code": null, "e": 504, "s": 493, "text": "Example 1:" }, { "code": "// Java code to illustrate clear()import java.util.*; public class GFG { public static void main(String args[]) { // Creating an empty Stack Stack<String> stack = new Stack<String>(); // Use add() method to add elements into the Stack stack.add(\"Welcome\"); stack.add(\"To\"); stack.add(\"Geeks\"); stack.add(\"4\"); stack.add(\"Geeks\"); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Clearing the Stack using clear() method stack.clear(); // Displaying the final Stack after clearing; System.out.println(\"The final Stack: \" + stack); }}", "e": 1169, "s": 504, "text": null }, { "code": null, "e": 1228, "s": 1169, "text": "Stack: [Welcome, To, Geeks, 4, Geeks]\nThe final Stack: []\n" }, { "code": null, "e": 1239, "s": 1228, "text": "Example 2:" }, { "code": "// Java code to illustrate clear()import java.util.*; public class GFG { public static void main(String args[]) { // Creating an empty Stack Stack<Integer> stack = new Stack<Integer>(); // Use add() method to add elements into the Queue stack.add(10); stack.add(15); stack.add(30); stack.add(20); stack.add(5); // Displaying the Stack System.out.println(\"Stack: \" + stack); // Clearing the Stack using clear() method stack.clear(); // Displaying the final Stack after clearing; System.out.println(\"The final Stack: \" + stack); }}", "e": 1885, "s": 1239, "text": null }, { "code": null, "e": 1933, "s": 1885, "text": "Stack: [10, 15, 30, 20, 5]\nThe final Stack: []\n" }, { "code": null, "e": 1953, "s": 1933, "text": "Java - util package" }, { "code": null, "e": 1970, "s": 1953, "text": "Java-Collections" }, { "code": null, "e": 1985, "s": 1970, "text": "Java-Functions" }, { "code": null, "e": 1996, "s": 1985, "text": "Java-Stack" }, { "code": null, "e": 2001, "s": 1996, "text": "Java" }, { "code": null, "e": 2006, "s": 2001, "text": "Java" }, { "code": null, "e": 2023, "s": 2006, "text": "Java-Collections" } ]
C++ Program to Check if a Matrix is Invertible
The determinant of a matrix can be used to find if it is invertible or not. The matrix is invertible if the determinant is non-zero. So if the determinant comes out to be zero, the matrix is not invertible. For example − The given matrix is: 4 2 1 2 1 1 9 3 2 The determinant of the above matrix is: 3 So the matrix is invertible. A program that checks if a matrix is invertible or not is as follows. Live Demo #include<iostream> #include<math.h> using namespace std; int determinant( int matrix[10][10], int n) { int det = 0; int submatrix[10][10]; if (n == 2) return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1])); else { for (int x = 0; x < n; x++) { int subi = 0; for (int i = 1; i < n; i++) { int subj = 0; for (int j = 0; j < n; j++) { if (j == x) continue; submatrix[subi][subj] = matrix[i][j]; subj++; } subi++; } det = det + (pow(-1, x) * matrix[0][x] * determinant( submatrix, n - 1 )); } } return det; } int main() { int n, d, i, j; int matrix[10][10]; cout << "Enter the size of the matrix:\n"; cin >> n; cout << "Enter the elements of the matrix:\n"; for (i = 0; i < n; i++) for (j = 0; j < n; j++) cin >> matrix[i][j]; cout<<"The entered matrix is:"<<endl; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) cout << matrix[i][j] <<" "; cout<<endl; } d = determinant(matrix, n); cout<<"Determinant of the matrix is "<< d <<endl; if( d == 0 ) cout<<"This matrix is not invertible as the determinant is zero"; else cout<<"This matrix is invertible as the determinant is not zero"; return 0; } Enter the size of the matrix: 3 Enter the elements of the matrix: 1 2 3 2 1 2 1 1 4 The entered matrix is: 1 2 3 2 1 2 1 1 4 Determinant of the matrix is -7 This matrix is invertible as the determinant is not zero In the above program, the size and elements of the matrix are provided in the main() function. Then the function determinant() is called. It returns the determinant of the matrix which is stored in d. If the determinant is 0, then the matrix is not invertible and if the determinant is not 0, then the matrix is invertible. This is demonstrated with the following code snippet. cout << "Enter the size of the matrix:\n"; cin >> n; cout << "Enter the elements of the matrix:\n"; for (i = 0; i < n; i++) for (j = 0; j < n; j++) cin >> matrix[i][j]; cout<<"The entered matrix is:"<<endl; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) cout << matrix[i][j] <<" "; cout<<endl; } d = determinant(matrix, n); cout<<"Determinant of the matrix is "<< d <<endl; if( d == 0 ) cout<<"This matrix is not invertible as the determinant is zero"; else cout<<"This matrix is invertible as the determinant is not zero"; In the function determinant(), if the size of the matrix is 2, then the determinant is directly calculated and the value is returned. This is shown as follows. if (n == 2) return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1])); If the size of the matrix is not 2, then the determinant is calculated recursively. There are 3 nested for loops used with the loop variables x, i and j. These loops are used to calculate the determinant and the function determinant() is called recursively to calculate the inner determinant and then multiply it with the outer value. This is demonstrated by the following code snippet. for (int x = 0; x < n; x++) { int subi = 0; for (int i = 1; i < n; i++) { int subj = 0; for (int j = 0; j < n; j++) { if (j == x) continue; submatrix[subi][subj] = matrix[i][j]; subj++; } subi++; } det = det + (pow(-1, x) * matrix[0][x] * determinant( submatrix, n - 1 )) }
[ { "code": null, "e": 1408, "s": 1187, "text": "The determinant of a matrix can be used to find if it is invertible or not. The matrix is invertible if the determinant is non-zero. So if the determinant comes out to be zero, the matrix is not invertible. For example −" }, { "code": null, "e": 1519, "s": 1408, "text": "The given matrix is:\n\n4 2 1\n2 1 1\n9 3 2\nThe determinant of the above matrix is: 3\nSo the matrix is invertible." }, { "code": null, "e": 1589, "s": 1519, "text": "A program that checks if a matrix is invertible or not is as follows." }, { "code": null, "e": 1600, "s": 1589, "text": " Live Demo" }, { "code": null, "e": 2958, "s": 1600, "text": "#include<iostream>\n#include<math.h>\nusing namespace std;\nint determinant( int matrix[10][10], int n) {\n int det = 0;\n int submatrix[10][10];\n if (n == 2)\n return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));\n else {\n for (int x = 0; x < n; x++) {\n int subi = 0;\n for (int i = 1; i < n; i++) {\n int subj = 0;\n for (int j = 0; j < n; j++) {\n if (j == x)\n continue;\n submatrix[subi][subj] = matrix[i][j];\n subj++;\n }\n subi++;\n }\n det = det + (pow(-1, x) * matrix[0][x] * determinant( submatrix, n - 1 ));\n }\n }\n return det;\n}\nint main() {\n int n, d, i, j;\n int matrix[10][10];\n cout << \"Enter the size of the matrix:\\n\";\n cin >> n;\n cout << \"Enter the elements of the matrix:\\n\";\n for (i = 0; i < n; i++)\n for (j = 0; j < n; j++)\n cin >> matrix[i][j];\n cout<<\"The entered matrix is:\"<<endl;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++)\n cout << matrix[i][j] <<\" \";\n cout<<endl;\n }\n d = determinant(matrix, n);\n cout<<\"Determinant of the matrix is \"<< d <<endl;\n if( d == 0 )\n cout<<\"This matrix is not invertible as the determinant is zero\";\n else\n cout<<\"This matrix is invertible as the determinant is not zero\";\n return 0;\n}" }, { "code": null, "e": 3172, "s": 2958, "text": "Enter the size of the matrix: 3\nEnter the elements of the matrix:\n1 2 3\n2 1 2\n1 1 4\nThe entered matrix is:\n1 2 3\n2 1 2\n1 1 4\nDeterminant of the matrix is -7\nThis matrix is invertible as the determinant is not zero" }, { "code": null, "e": 3550, "s": 3172, "text": "In the above program, the size and elements of the matrix are provided in the main() function. Then the function determinant() is called. It returns the determinant of the matrix which is stored in d. If the determinant is 0, then the matrix is not invertible and if the determinant is not 0, then the matrix is invertible. This is demonstrated with the following code snippet." }, { "code": null, "e": 4086, "s": 3550, "text": "cout << \"Enter the size of the matrix:\\n\";\ncin >> n;\ncout << \"Enter the elements of the matrix:\\n\";\nfor (i = 0; i < n; i++)\nfor (j = 0; j < n; j++)\ncin >> matrix[i][j];\ncout<<\"The entered matrix is:\"<<endl;\nfor (i = 0; i < n; i++) {\n for (j = 0; j < n; j++)\n cout << matrix[i][j] <<\" \";\n cout<<endl;\n}\nd = determinant(matrix, n);\ncout<<\"Determinant of the matrix is \"<< d <<endl;\nif( d == 0 )\ncout<<\"This matrix is not invertible as the determinant is zero\";\nelse\ncout<<\"This matrix is invertible as the determinant is not zero\";" }, { "code": null, "e": 4246, "s": 4086, "text": "In the function determinant(), if the size of the matrix is 2, then the determinant is directly calculated and the value is returned. This is shown as follows." }, { "code": null, "e": 4330, "s": 4246, "text": "if (n == 2)\nreturn ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));" }, { "code": null, "e": 4717, "s": 4330, "text": "If the size of the matrix is not 2, then the determinant is calculated recursively. There are 3 nested for loops used with the loop variables x, i and j. These loops are used to calculate the determinant and the function determinant() is called recursively to calculate the inner determinant and then multiply it with the outer value. This is demonstrated by the following code snippet." }, { "code": null, "e": 5063, "s": 4717, "text": "for (int x = 0; x < n; x++) {\n int subi = 0;\n for (int i = 1; i < n; i++) {\n int subj = 0;\n for (int j = 0; j < n; j++) {\n if (j == x)\n continue;\n submatrix[subi][subj] = matrix[i][j];\n subj++;\n }\n subi++;\n }\n det = det + (pow(-1, x) * matrix[0][x] * determinant( submatrix, n - 1 ))\n}" } ]
Find numbers with n-divisors in a given range
23 Jun, 2022 Given three integers a, b, n .Your task is to print number of numbers between a and b including them also which have n-divisors. A number is called n-divisor if it has total n divisors including 1 and itself. Examples: Input : a = 1, b = 7, n = 2 Output : 4 There are four numbers with 2 divisors in range [1, 7]. The numbers are 2, 3, 5, and 7. Naive Approach: The naive approach is to check all the numbers between a and b how many of them are n-divisor number for doing this find out the number of each divisors for each number . If it is equal to n then it is a n-divisor numberEfficient Approach: Any number can be written in the form of its prime factorization let the number be x and p1, p2..pm are the prime numbers which divide x so x = p1e1 * p2e2....pmem where e1, e2...em are the exponents of prime numbers p1, p2....pm. So the number of divisors of x will be (e1+1)*(e2+1)...*(em+1). Now the second observation is for prime numbers greater than sqrt(x) their exponent cannot exceed 1. Let’s prove this by contradiction suppose there is a prime number P greater than sqrt(x) and its exponent E in prime factorization of x is greater than one (E >= 2) so P^E sqrt(x) so P^E > (sqrt(x))E and E >= 2 so PE will always be greater than x Third observation is that number of prime numbers greater than sqrt(x) in the prime factorization of x will always be less than equal to 1. This can also be proved similarly by contradiction as above.Now to solve this problem Step 1: Apply sieve of eratosthenes and calculate prime numbers upto sqrt(b).Step 2: Traverse through each number from a to b and calculate exponents of each prime number in that number by repeatedly dividing that number by prime number and use the formula numberofdivisors(x) = (e1+1)*(e2+1)....(em+1).Step 3: If after dividing by all the prime numbers less than equal to square root of that number if number > 1 this means there is a prime number greater than its square root which divides and its exponent will always be one as proved above. C++ Java Python3 C# PHP Javascript // C++ program to count numbers with n divisors#include<bits/stdc++.h>using namespace std; // applying sieve of eratosthenesvoid sieve(bool primes[], int x){ primes[1] = false; // if a number is prime mark all its multiples // as non prime for (int i=2; i*i <= x; i++) { if (primes[i] == true) { for (int j=2; j*j <= x; j++) primes[i*j] = false; } }} // function that returns numbers of number that have// n divisors in range from a to b. x is sqrt(b) + 1.int nDivisors(bool primes[], int x, int a, int b, int n){ // result holds number of numbers having n divisors int result = 0; // vector to hold all the prime numbers between 1 // ans sqrt(b) vector <int> v; for (int i = 2; i <= x; i++) if (primes[i] == true) v.push_back (i); // Traversing all numbers in given range for (int i=a; i<=b; i++) { // initialising temp as i int temp = i; // total holds the number of divisors of i int total = 1; int j = 0; // we need to use that prime numbers that // are less than equal to sqrt(temp) for (int k = v[j]; k*k <= temp; k = v[++j]) { // holds the exponent of k in prime // factorization of i int count = 0; // repeatedly divide temp by k till it is // divisible and accordingly increase count while (temp%k == 0) { count++; temp = temp/k; } // using the formula no.of divisors = // (e1+1)*(e2+1).... total = total*(count+1); } // if temp is not equal to 1 then there is // prime number in prime factorization of i // greater than sqrt(i) if (temp != 1) total = total*2; // if i is a ndvisor number increase result if (total == n) result++; } return result;} // Returns count of numbers in [a..b] having// n divisors.int countNDivisors(int a, int b, int n){ int x = sqrt(b) + 1; // primes[i] = true if i is a prime number bool primes[x]; // initialising each number as prime memset(primes, true, sizeof(primes)); sieve(primes, x); return nDivisors(primes, x, a, b, n);} // driver codeint main(){ int a = 1, b = 7, n = 2; cout << countNDivisors(a, b, n); return 0;} // Java program to count numbers with n divisorsimport java.util.*; class GFG{// applying sieve of eratosthenesstatic void sieve(boolean[] primes, int x){ primes[1] = true; // if a number is prime mark all its multiples // as non prime for (int i=2; i*i <= x; i++) { if (primes[i] == false) { for (int j=2; j*i <= x; j++) primes[i*j] = true; } }} // function that returns numbers of number that have// n divisors in range from a to b. x is sqrt(b) + 1.static int nDivisors(boolean[] primes, int x, int a, int b, int n){ // result holds number of numbers having n divisors int result = 0; // vector to hold all the prime numbers between 1 // ans sqrt(b) ArrayList<Integer> v=new ArrayList<Integer>(); for (int i = 2; i <= x; i++) if (primes[i] == false) v.add(i); // Traversing all numbers in given range for (int i=a; i<=b; i++) { // initialising temp as i int temp = i; // total holds the number of divisors of i int total = 1; int j = 0; // we need to use that prime numbers that // are less than equal to sqrt(temp) for (int k = v.get(j); k*k <= temp; k = v.get(++j)) { // holds the exponent of k in prime // factorization of i int count = 0; // repeatedly divide temp by k till it is // divisible and accordingly increase count while (temp%k == 0) { count++; temp = temp/k; } // using the formula no.of divisors = // (e1+1)*(e2+1).... total = total*(count+1); } // if temp is not equal to 1 then there is // prime number in prime factorization of i // greater than sqrt(i) if (temp != 1) total = total*2; // if i is a ndvisor number increase result if (total == n) result++; } return result;} // Returns count of numbers in [a..b] having// n divisors.static int countNDivisors(int a, int b, int n){ int x = (int)Math.sqrt(b) + 1; // primes[i] = true if i is a prime number boolean[] primes=new boolean[x+1]; // initialising each number as prime sieve(primes, x); return nDivisors(primes, x, a, b, n);} // driver codepublic static void main(String[] args){ int a = 1, b = 7, n = 2; System.out.println(countNDivisors(a, b, n)); }}// This code is contributed by mits # Python3 program to count numbers# with n divisorsimport math; # applying sieve of eratosthenesdef sieve(primes, x): primes[1] = False; # if a number is prime mark all # its multiples as non prime i = 2; while (i * i <= x): if (primes[i] == True): j = 2; while (j * i <= x): primes[i * j] = False; j += 1; i += 1; # function that returns numbers of number# that have n divisors in range from a to b.# x is sqrt(b) + 1.def nDivisors(primes, x, a, b, n): # result holds number of numbers # having n divisors result = 0; # vector to hold all the prime # numbers between 1 and sqrt(b) v = []; for i in range(2, x + 1): if (primes[i]): v.append(i); # Traversing all numbers in given range for i in range(a, b + 1): # initialising temp as i temp = i; # total holds the number of # divisors of i total = 1; j = 0; # we need to use that prime numbers that # are less than equal to sqrt(temp) k = v[j]; while (k * k <= temp): # holds the exponent of k in prime # factorization of i count = 0; # repeatedly divide temp by k till it is # divisible and accordingly increase count while (temp % k == 0): count += 1; temp = int(temp / k); # using the formula no.of divisors = # (e1+1)*(e2+1).... total = total * (count + 1); j += 1; k = v[j]; # if temp is not equal to 1 then there is # prime number in prime factorization of i # greater than sqrt(i) if (temp != 1): total = total * 2; # if i is a ndivisor number # increase result if (total == n): result += 1; return result; # Returns count of numbers in [a..b]# having n divisors.def countNDivisors(a, b, n): x = int(math.sqrt(b) + 1); # primes[i] = true if i is a prime number # initialising each number as prime primes = [True] * (x + 1); sieve(primes, x); return nDivisors(primes, x, a, b, n); # Driver codea = 1;b = 7;n = 2;print(countNDivisors(a, b, n)); # This code is contributed by mits // C# program to count numbers with n divisorsusing System.Collections;using System;class GFG{// applying sieve of eratosthenesstatic void sieve(bool[] primes, int x){ primes[1] = true; // if a number is prime mark all its multiples // as non prime for (int i=2; i*i <= x; i++) { if (primes[i] == false) { for (int j=2; j*i <= x; j++) primes[i*j] = true; } }} // function that returns numbers of number that have// n divisors in range from a to b. x is sqrt(b) + 1.static int nDivisors(bool[] primes, int x, int a, int b, int n){ // result holds number of numbers having n divisors int result = 0; // vector to hold all the prime numbers between 1 // ans sqrt(b) ArrayList v=new ArrayList(); for (int i = 2; i <= x; i++) if (primes[i] == false) v.Add(i); // Traversing all numbers in given range for (int i=a; i<=b; i++) { // initialising temp as i int temp = i; // total holds the number of divisors of i int total = 1; int j = 0; // we need to use that prime numbers that // are less than equal to sqrt(temp) for (int k = (int)v[j]; k*k <= temp; k = (int)v[++j]) { // holds the exponent of k in prime // factorization of i int count = 0; // repeatedly divide temp by k till it is // divisible and accordingly increase count while (temp%k == 0) { count++; temp = temp/k; } // using the formula no.of divisors = // (e1+1)*(e2+1).... total = total*(count+1); } // if temp is not equal to 1 then there is // prime number in prime factorization of i // greater than sqrt(i) if (temp != 1) total = total*2; // if i is a ndivisor number increase result if (total == n) result++; } return result;} // Returns count of numbers in [a..b] having// n divisors.static int countNDivisors(int a, int b, int n){ int x = (int)Math.Sqrt(b) + 1; // primes[i] = true if i is a prime number bool[] primes=new bool[x+1]; // initialising each number as prime sieve(primes, x); return nDivisors(primes, x, a, b, n);} // driver codepublic static void Main(){ int a = 1, b = 7, n = 2; Console.WriteLine(countNDivisors(a, b, n)); }}// This code is contributed by mits <?php// PHP program to count numbers with n divisors // applying sieve of eratosthenesfunction sieve(&$primes, $x){ $primes[1] = false; // if a number is prime mark all // its multiples as non prime for ($i = 2; $i * $i <= $x; $i++) { if ($primes[$i] == true) { for ($j = 2; $j * $i <= $x; $j++) $primes[$i * $j] = false; } }} // function that returns numbers of number// that have n divisors in range from a to// b. x is sqrt(b) + 1.function nDivisors($primes, $x, $a, $b, $n){ // result holds number of numbers // having n divisors $result = 0; // vector to hold all the prime numbers // between 1 ans sqrt(b) $v = array(); for ($i = 2; $i <= $x; $i++) if ($primes[$i] == true) array_push($v, $i); // Traversing all numbers in given range for ($i = $a; $i <= $b; $i++) { // initialising temp as i $temp = $i; // total holds the number of // divisors of i $total = 1; $j = 0; // we need to use that prime numbers that // are less than equal to sqrt(temp) for ($k = $v[$j]; $k * $k <= $temp; $k = $v[++$j]) { // holds the exponent of k in // prime factorization of i $count = 0; // repeatedly divide temp by k till // it is divisible and accordingly // increase count while ($temp % $k == 0) { $count++; $temp = (int)($temp / $k); } // using the formula no.of divisors = // (e1+1)*(e2+1).... $total = $total * ($count + 1); } // if temp is not equal to 1 then there is // prime number in prime factorization of i // greater than sqrt(i) if ($temp != 1) $total = $total * 2; // if i is a n divisor number increase result if ($total == $n) $result++; } return $result;} // Returns count of numbers in [a..b]// having n divisors.function countNDivisors($a, $b, $n){ $x = (int)(sqrt($b) + 1); // primes[i] = true if i is a prime number // initialising each number as prime $primes = array_fill(0, $x + 1, true); sieve($primes, $x); return nDivisors($primes, $x, $a, $b, $n);} // Driver code$a = 1;$b = 7;$n = 2;print(countNDivisors($a, $b, $n)); // This code is contributed by mits?> <script> // Javascript program to count numbers with n divisors // applying sieve of eratosthenesfunction sieve(primes, x){ primes[1] = true; // if a number is prime mark all its multiples // as non prime for (var i=2; i*i <= x; i++) { if (primes[i] == false) { for (var j=2; j*i <= x; j++) primes[i*j] = true; } }} // function that returns numbers of number that have// n divisors in range from a to b. x is sqrt(b) + 1.function nDivisors(primes, x, a, b, n){ // result holds number of numbers having n divisors var result = 0; // vector to hold all the prime numbers between 1 // ans sqrt(b) var v = []; for (var i = 2; i <= x; i++) if (primes[i] == false) v.push(i); // Traversing all numbers in given range for (var i=a; i<=b; i++) { // initialising temp as i var temp = i; // total holds the number of divisors of i var total = 1; var j = 0; // we need to use that prime numbers that // are less than equal to sqrt(temp) for (var k = v[j]; k*k <= temp; k = v[++j]) { // holds the exponent of k in prime // factorization of i var count = 0; // repeatedly divide temp by k till it is // divisible and accordingly increase count while (temp%k == 0) { count++; temp = parseInt(temp/k); } // using the formula no.of divisors = // (e1+1)*(e2+1).... total = total*(count+1); } // if temp is not equal to 1 then there is // prime number in prime factorization of i // greater than sqrt(i) if (temp != 1) total = total*2; // if i is a ndivisor number increase result if (total == n) result++; } return result;} // Returns count of numbers in [a..b] having// n divisors.function countNDivisors(a, b, n){ var x = parseInt(Math.sqrt(b)) + 1; // primes[i] = true if i is a prime number var primes = Array(x+1).fill(false); // initialising each number as prime sieve(primes, x); return nDivisors(primes, x, a, b, n);} // driver codevar a = 1, b = 7, n = 2;document.write(countNDivisors(a, b, n)); // This code is contributed by rutvik_56.</script> Output: 4 Time Complexity: O(n) Auxiliary Space: O(n) This article is contributed by Aarti_Rathi and Ayush Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar ManasChhabra2 rutvik_56 pravesh25pandey codewithshinchan divisibility divisors sieve Mathematical Mathematical sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 275, "s": 54, "text": "Given three integers a, b, n .Your task is to print number of numbers between a and b including them also which have n-divisors. A number is called n-divisor if it has total n divisors including 1 and itself. Examples: " }, { "code": null, "e": 404, "s": 275, "text": "Input : a = 1, b = 7, n = 2\nOutput : 4\nThere are four numbers with 2 divisors in \nrange [1, 7]. The numbers are 2, 3, 5, and 7." }, { "code": null, "e": 2078, "s": 406, "text": "Naive Approach: The naive approach is to check all the numbers between a and b how many of them are n-divisor number for doing this find out the number of each divisors for each number . If it is equal to n then it is a n-divisor numberEfficient Approach: Any number can be written in the form of its prime factorization let the number be x and p1, p2..pm are the prime numbers which divide x so x = p1e1 * p2e2....pmem where e1, e2...em are the exponents of prime numbers p1, p2....pm. So the number of divisors of x will be (e1+1)*(e2+1)...*(em+1). Now the second observation is for prime numbers greater than sqrt(x) their exponent cannot exceed 1. Let’s prove this by contradiction suppose there is a prime number P greater than sqrt(x) and its exponent E in prime factorization of x is greater than one (E >= 2) so P^E sqrt(x) so P^E > (sqrt(x))E and E >= 2 so PE will always be greater than x Third observation is that number of prime numbers greater than sqrt(x) in the prime factorization of x will always be less than equal to 1. This can also be proved similarly by contradiction as above.Now to solve this problem Step 1: Apply sieve of eratosthenes and calculate prime numbers upto sqrt(b).Step 2: Traverse through each number from a to b and calculate exponents of each prime number in that number by repeatedly dividing that number by prime number and use the formula numberofdivisors(x) = (e1+1)*(e2+1)....(em+1).Step 3: If after dividing by all the prime numbers less than equal to square root of that number if number > 1 this means there is a prime number greater than its square root which divides and its exponent will always be one as proved above. " }, { "code": null, "e": 2082, "s": 2078, "text": "C++" }, { "code": null, "e": 2087, "s": 2082, "text": "Java" }, { "code": null, "e": 2095, "s": 2087, "text": "Python3" }, { "code": null, "e": 2098, "s": 2095, "text": "C#" }, { "code": null, "e": 2102, "s": 2098, "text": "PHP" }, { "code": null, "e": 2113, "s": 2102, "text": "Javascript" }, { "code": "// C++ program to count numbers with n divisors#include<bits/stdc++.h>using namespace std; // applying sieve of eratosthenesvoid sieve(bool primes[], int x){ primes[1] = false; // if a number is prime mark all its multiples // as non prime for (int i=2; i*i <= x; i++) { if (primes[i] == true) { for (int j=2; j*j <= x; j++) primes[i*j] = false; } }} // function that returns numbers of number that have// n divisors in range from a to b. x is sqrt(b) + 1.int nDivisors(bool primes[], int x, int a, int b, int n){ // result holds number of numbers having n divisors int result = 0; // vector to hold all the prime numbers between 1 // ans sqrt(b) vector <int> v; for (int i = 2; i <= x; i++) if (primes[i] == true) v.push_back (i); // Traversing all numbers in given range for (int i=a; i<=b; i++) { // initialising temp as i int temp = i; // total holds the number of divisors of i int total = 1; int j = 0; // we need to use that prime numbers that // are less than equal to sqrt(temp) for (int k = v[j]; k*k <= temp; k = v[++j]) { // holds the exponent of k in prime // factorization of i int count = 0; // repeatedly divide temp by k till it is // divisible and accordingly increase count while (temp%k == 0) { count++; temp = temp/k; } // using the formula no.of divisors = // (e1+1)*(e2+1).... total = total*(count+1); } // if temp is not equal to 1 then there is // prime number in prime factorization of i // greater than sqrt(i) if (temp != 1) total = total*2; // if i is a ndvisor number increase result if (total == n) result++; } return result;} // Returns count of numbers in [a..b] having// n divisors.int countNDivisors(int a, int b, int n){ int x = sqrt(b) + 1; // primes[i] = true if i is a prime number bool primes[x]; // initialising each number as prime memset(primes, true, sizeof(primes)); sieve(primes, x); return nDivisors(primes, x, a, b, n);} // driver codeint main(){ int a = 1, b = 7, n = 2; cout << countNDivisors(a, b, n); return 0;}", "e": 4521, "s": 2113, "text": null }, { "code": "// Java program to count numbers with n divisorsimport java.util.*; class GFG{// applying sieve of eratosthenesstatic void sieve(boolean[] primes, int x){ primes[1] = true; // if a number is prime mark all its multiples // as non prime for (int i=2; i*i <= x; i++) { if (primes[i] == false) { for (int j=2; j*i <= x; j++) primes[i*j] = true; } }} // function that returns numbers of number that have// n divisors in range from a to b. x is sqrt(b) + 1.static int nDivisors(boolean[] primes, int x, int a, int b, int n){ // result holds number of numbers having n divisors int result = 0; // vector to hold all the prime numbers between 1 // ans sqrt(b) ArrayList<Integer> v=new ArrayList<Integer>(); for (int i = 2; i <= x; i++) if (primes[i] == false) v.add(i); // Traversing all numbers in given range for (int i=a; i<=b; i++) { // initialising temp as i int temp = i; // total holds the number of divisors of i int total = 1; int j = 0; // we need to use that prime numbers that // are less than equal to sqrt(temp) for (int k = v.get(j); k*k <= temp; k = v.get(++j)) { // holds the exponent of k in prime // factorization of i int count = 0; // repeatedly divide temp by k till it is // divisible and accordingly increase count while (temp%k == 0) { count++; temp = temp/k; } // using the formula no.of divisors = // (e1+1)*(e2+1).... total = total*(count+1); } // if temp is not equal to 1 then there is // prime number in prime factorization of i // greater than sqrt(i) if (temp != 1) total = total*2; // if i is a ndvisor number increase result if (total == n) result++; } return result;} // Returns count of numbers in [a..b] having// n divisors.static int countNDivisors(int a, int b, int n){ int x = (int)Math.sqrt(b) + 1; // primes[i] = true if i is a prime number boolean[] primes=new boolean[x+1]; // initialising each number as prime sieve(primes, x); return nDivisors(primes, x, a, b, n);} // driver codepublic static void main(String[] args){ int a = 1, b = 7, n = 2; System.out.println(countNDivisors(a, b, n)); }}// This code is contributed by mits", "e": 7044, "s": 4521, "text": null }, { "code": "# Python3 program to count numbers# with n divisorsimport math; # applying sieve of eratosthenesdef sieve(primes, x): primes[1] = False; # if a number is prime mark all # its multiples as non prime i = 2; while (i * i <= x): if (primes[i] == True): j = 2; while (j * i <= x): primes[i * j] = False; j += 1; i += 1; # function that returns numbers of number# that have n divisors in range from a to b.# x is sqrt(b) + 1.def nDivisors(primes, x, a, b, n): # result holds number of numbers # having n divisors result = 0; # vector to hold all the prime # numbers between 1 and sqrt(b) v = []; for i in range(2, x + 1): if (primes[i]): v.append(i); # Traversing all numbers in given range for i in range(a, b + 1): # initialising temp as i temp = i; # total holds the number of # divisors of i total = 1; j = 0; # we need to use that prime numbers that # are less than equal to sqrt(temp) k = v[j]; while (k * k <= temp): # holds the exponent of k in prime # factorization of i count = 0; # repeatedly divide temp by k till it is # divisible and accordingly increase count while (temp % k == 0): count += 1; temp = int(temp / k); # using the formula no.of divisors = # (e1+1)*(e2+1).... total = total * (count + 1); j += 1; k = v[j]; # if temp is not equal to 1 then there is # prime number in prime factorization of i # greater than sqrt(i) if (temp != 1): total = total * 2; # if i is a ndivisor number # increase result if (total == n): result += 1; return result; # Returns count of numbers in [a..b]# having n divisors.def countNDivisors(a, b, n): x = int(math.sqrt(b) + 1); # primes[i] = true if i is a prime number # initialising each number as prime primes = [True] * (x + 1); sieve(primes, x); return nDivisors(primes, x, a, b, n); # Driver codea = 1;b = 7;n = 2;print(countNDivisors(a, b, n)); # This code is contributed by mits", "e": 9360, "s": 7044, "text": null }, { "code": "// C# program to count numbers with n divisorsusing System.Collections;using System;class GFG{// applying sieve of eratosthenesstatic void sieve(bool[] primes, int x){ primes[1] = true; // if a number is prime mark all its multiples // as non prime for (int i=2; i*i <= x; i++) { if (primes[i] == false) { for (int j=2; j*i <= x; j++) primes[i*j] = true; } }} // function that returns numbers of number that have// n divisors in range from a to b. x is sqrt(b) + 1.static int nDivisors(bool[] primes, int x, int a, int b, int n){ // result holds number of numbers having n divisors int result = 0; // vector to hold all the prime numbers between 1 // ans sqrt(b) ArrayList v=new ArrayList(); for (int i = 2; i <= x; i++) if (primes[i] == false) v.Add(i); // Traversing all numbers in given range for (int i=a; i<=b; i++) { // initialising temp as i int temp = i; // total holds the number of divisors of i int total = 1; int j = 0; // we need to use that prime numbers that // are less than equal to sqrt(temp) for (int k = (int)v[j]; k*k <= temp; k = (int)v[++j]) { // holds the exponent of k in prime // factorization of i int count = 0; // repeatedly divide temp by k till it is // divisible and accordingly increase count while (temp%k == 0) { count++; temp = temp/k; } // using the formula no.of divisors = // (e1+1)*(e2+1).... total = total*(count+1); } // if temp is not equal to 1 then there is // prime number in prime factorization of i // greater than sqrt(i) if (temp != 1) total = total*2; // if i is a ndivisor number increase result if (total == n) result++; } return result;} // Returns count of numbers in [a..b] having// n divisors.static int countNDivisors(int a, int b, int n){ int x = (int)Math.Sqrt(b) + 1; // primes[i] = true if i is a prime number bool[] primes=new bool[x+1]; // initialising each number as prime sieve(primes, x); return nDivisors(primes, x, a, b, n);} // driver codepublic static void Main(){ int a = 1, b = 7, n = 2; Console.WriteLine(countNDivisors(a, b, n)); }}// This code is contributed by mits", "e": 11858, "s": 9360, "text": null }, { "code": "<?php// PHP program to count numbers with n divisors // applying sieve of eratosthenesfunction sieve(&$primes, $x){ $primes[1] = false; // if a number is prime mark all // its multiples as non prime for ($i = 2; $i * $i <= $x; $i++) { if ($primes[$i] == true) { for ($j = 2; $j * $i <= $x; $j++) $primes[$i * $j] = false; } }} // function that returns numbers of number// that have n divisors in range from a to// b. x is sqrt(b) + 1.function nDivisors($primes, $x, $a, $b, $n){ // result holds number of numbers // having n divisors $result = 0; // vector to hold all the prime numbers // between 1 ans sqrt(b) $v = array(); for ($i = 2; $i <= $x; $i++) if ($primes[$i] == true) array_push($v, $i); // Traversing all numbers in given range for ($i = $a; $i <= $b; $i++) { // initialising temp as i $temp = $i; // total holds the number of // divisors of i $total = 1; $j = 0; // we need to use that prime numbers that // are less than equal to sqrt(temp) for ($k = $v[$j]; $k * $k <= $temp; $k = $v[++$j]) { // holds the exponent of k in // prime factorization of i $count = 0; // repeatedly divide temp by k till // it is divisible and accordingly // increase count while ($temp % $k == 0) { $count++; $temp = (int)($temp / $k); } // using the formula no.of divisors = // (e1+1)*(e2+1).... $total = $total * ($count + 1); } // if temp is not equal to 1 then there is // prime number in prime factorization of i // greater than sqrt(i) if ($temp != 1) $total = $total * 2; // if i is a n divisor number increase result if ($total == $n) $result++; } return $result;} // Returns count of numbers in [a..b]// having n divisors.function countNDivisors($a, $b, $n){ $x = (int)(sqrt($b) + 1); // primes[i] = true if i is a prime number // initialising each number as prime $primes = array_fill(0, $x + 1, true); sieve($primes, $x); return nDivisors($primes, $x, $a, $b, $n);} // Driver code$a = 1;$b = 7;$n = 2;print(countNDivisors($a, $b, $n)); // This code is contributed by mits?>", "e": 14301, "s": 11858, "text": null }, { "code": "<script> // Javascript program to count numbers with n divisors // applying sieve of eratosthenesfunction sieve(primes, x){ primes[1] = true; // if a number is prime mark all its multiples // as non prime for (var i=2; i*i <= x; i++) { if (primes[i] == false) { for (var j=2; j*i <= x; j++) primes[i*j] = true; } }} // function that returns numbers of number that have// n divisors in range from a to b. x is sqrt(b) + 1.function nDivisors(primes, x, a, b, n){ // result holds number of numbers having n divisors var result = 0; // vector to hold all the prime numbers between 1 // ans sqrt(b) var v = []; for (var i = 2; i <= x; i++) if (primes[i] == false) v.push(i); // Traversing all numbers in given range for (var i=a; i<=b; i++) { // initialising temp as i var temp = i; // total holds the number of divisors of i var total = 1; var j = 0; // we need to use that prime numbers that // are less than equal to sqrt(temp) for (var k = v[j]; k*k <= temp; k = v[++j]) { // holds the exponent of k in prime // factorization of i var count = 0; // repeatedly divide temp by k till it is // divisible and accordingly increase count while (temp%k == 0) { count++; temp = parseInt(temp/k); } // using the formula no.of divisors = // (e1+1)*(e2+1).... total = total*(count+1); } // if temp is not equal to 1 then there is // prime number in prime factorization of i // greater than sqrt(i) if (temp != 1) total = total*2; // if i is a ndivisor number increase result if (total == n) result++; } return result;} // Returns count of numbers in [a..b] having// n divisors.function countNDivisors(a, b, n){ var x = parseInt(Math.sqrt(b)) + 1; // primes[i] = true if i is a prime number var primes = Array(x+1).fill(false); // initialising each number as prime sieve(primes, x); return nDivisors(primes, x, a, b, n);} // driver codevar a = 1, b = 7, n = 2;document.write(countNDivisors(a, b, n)); // This code is contributed by rutvik_56.</script>", "e": 16689, "s": 14301, "text": null }, { "code": null, "e": 16699, "s": 16689, "text": "Output: " }, { "code": null, "e": 16701, "s": 16699, "text": "4" }, { "code": null, "e": 16746, "s": 16701, "text": "Time Complexity: O(n) Auxiliary Space: O(n) " }, { "code": null, "e": 17180, "s": 16746, "text": "This article is contributed by Aarti_Rathi and Ayush Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 17193, "s": 17180, "text": "Mithun Kumar" }, { "code": null, "e": 17207, "s": 17193, "text": "ManasChhabra2" }, { "code": null, "e": 17217, "s": 17207, "text": "rutvik_56" }, { "code": null, "e": 17233, "s": 17217, "text": "pravesh25pandey" }, { "code": null, "e": 17250, "s": 17233, "text": "codewithshinchan" }, { "code": null, "e": 17263, "s": 17250, "text": "divisibility" }, { "code": null, "e": 17272, "s": 17263, "text": "divisors" }, { "code": null, "e": 17278, "s": 17272, "text": "sieve" }, { "code": null, "e": 17291, "s": 17278, "text": "Mathematical" }, { "code": null, "e": 17304, "s": 17291, "text": "Mathematical" }, { "code": null, "e": 17310, "s": 17304, "text": "sieve" } ]
Compress a matrix into a single number using given operations
27 Oct, 2021 Given a matrix mat[][] of dimension M * N, the task is to first compress it to obtain an array and, then compress it again to obtain a single integer using following operations: When a matrix is compressed, its value’s binary representation gets compressed. Therefore, each bit is considered, and if a position of a bit has S set bits and NS non-set bits, then the bit is set for the position if S > NS and unset otherwise. Each column is compressed to turn the matrix into an array, then that array is compressed further into a single number. For example, if 5, 2, 3, and 1 gets compressed then their binary representations (101)2, (010)2, (011)2, and (001)2 gets compressed then for the 0th and 1st positions, S ≤ NS and for the 2nd position S > NS, then the number modifies to (001)2 = 1. Examples: Input: arr[][] ={{ 3, 2, 4}, {5, 6, 1}, {8, 1, 3}}Output: 1Explanation: The array obtained after compressing the given matrix from top is {1, 2, 1 }.Then, the obtained array is compressed to 1. Input: arr[][] = {{ 5, 3}, {6, 7}}Output: 0 Approach: The idea is to count the number of set bits for each position. Follow the steps below to solve the problem: Traverse through each element of each column of a matrix and compress each column to a single number. Count the number of set bits for each position. Set the bit for the positions with number of set bits exceeding the number of unset bits. Calculate the value after deciding whether to set or not to set the bit for each position. After obtaining an array, apply the same steps to obtain the required integer. 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 compress an // array to a single number vector<int> append(vector<int> arr, int x) { // create a new ArrayList arr.push_back(x); return arr; } int compress(vector<int> arr) { // Stores the required integer int ans = 0; int getBit = 1; // Checking for each position for (int i = 0; i < 32; i++) { int S = 0; int NS = 0; for (int j = 0; j < arr.size(); j++) { // Count set and unset bit int temp = getBit & arr[j]; if (temp == 1) { S += 1; } else { NS += 1; } // If count of set bits exceeds // count of unset bits if (S > NS) { // Add value of set bits to ans ans += pow(2, i); } getBit <<= 1; } } return ans; } // Function to compress // matrix to a single number int getResult(vector<vector<int>> mat) { // Stores compressed array vector<int> compressedArr; int len = mat.size(); int len2 = mat[0].size(); for (int i = 0; i < len; i++) { vector<int> col; for (int j = 0; j < len2; j++) { col = append(col, mat[j][i]); } // Compress all columns // to a single number compressedArr = append(compressedArr, compress(col)); } return compress(compressedArr); } // Driver Code int main() { vector<vector<int>> mat{{3, 2, 4 },{5, 6, 1},{8, 1, 3}}; cout<<(getResult(mat)); } // THIS CODE IS CONTRIBUTED BY SURENDRA_GANGWAR. // Java Program for the above approachimport java.io.*;import java.lang.*;import java.lang.Math;import java.util.*;class GFG { // Function to compress an // array to a single number static Integer[] append(Integer arr[], int x) { // create a new ArrayList List<Integer> arrlist = new ArrayList<Integer>(Arrays.asList(arr)); // Add the new element arrlist.add(x); // Convert the Arraylist to array arr = arrlist.toArray(arr); // return the array return arr; } static int compress(Integer[] arr) { // Stores the required integer int ans = 0; int getBit = 1; // Checking for each position for (int i = 0; i < 32; i++) { int S = 0; int NS = 0; for (int j = 0; j < arr.length; j++) { // Count set and unset bit int and = getBit & arr[j]; if (and == 1) { S += 1; } else { NS += 1; } // If count of set bits exceeds // count of unset bits if (S > NS) { // Add value of set bits to ans ans += Math.pow(2, i); } getBit <<= 1; } } return ans; } // Function to compress // matrix to a single number static int getResult(Integer[][] mat) { // Stores compressed array Integer[] compressedArr = {}; int len = mat.length; int len2 = mat[0].length; for (int i = 0; i < len; i++) { Integer[] col = {}; for (int j = 0; j < len2; j++) { col = append(col, mat[j][i]); } // Compress all columns // to a single number compressedArr = append(compressedArr, compress(col)); } return compress(compressedArr); } // Driver Code public static void main(String[] args) { Integer[][] mat = { { 3, 2, 4 }, { 5, 6, 1 }, { 8, 1, 3 } }; System.out.println(getResult(mat)); }} // This code is contributed by rohitsingh07052. # Python Program for the above approach # Function to compress an# array to a single numberdef compress(arr): # Stores the required integer ans = 0 getBit = 1 # Checking for each position for i in range(32): S = 0 NS = 0 for j in arr: # Count set and unset bits if getBit&j: S += 1 else: NS += 1 # If count of set bits exceeds # count of unset bits if S > NS: # Add value of set bits to ans ans += 2**i getBit <<= 1 return ans # Function to compress# matrix to a single numberdef getResult(mat): # Stores compressed array compressedArr = [] for i in range(len(mat)): col = [] for j in range(len(mat[0])): col.append(mat[j][i]) # Compress all columns # to a single number compressedArr.append(compress(col)) return compress(compressedArr) # Driver Codemat = [ [ 3, 2, 4], [5, 6, 1], [8, 1, 3] ] print( getResult(mat) ) // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to compress an// array to a single numberstatic int[] append(int []arr, int x){ // create a new List List<int> arrlist = new List<int>(arr); // Add the new element arrlist.Add(x); // Convert the Arraylist to array arr = arrlist.ToArray(); // return the array return arr;} static int compress(int[] arr){ // Stores the required integer int ans = 0; int getBit = 1; // Checking for each position for(int i = 0; i < 32; i++) { int S = 0; int NS = 0; for(int j = 0; j < arr.Length; j++) { // Count set and unset bit int and = getBit & arr[j]; if (and == 1) { S += 1; } else { NS += 1; } // If count of set bits exceeds // count of unset bits if (S > NS) { // Add value of set bits to ans ans += (int)Math.Pow(2, i); } getBit <<= 1; } } return ans;} // Function to compress// matrix to a single numberstatic int getResult(int[,] mat){ // Stores compressed array int[] compressedArr = {}; int len = mat.GetLength(0); int len2 = mat.GetLength(1); for(int i = 0; i < len; i++) { int[] col = {}; for (int j = 0; j < len2; j++) { col = append(col, mat[j,i]); } // Compress all columns // to a single number compressedArr = append(compressedArr, compress(col)); } return compress(compressedArr);} // Driver Codepublic static void Main(String[] args){ int[,] mat = { { 3, 2, 4 }, { 5, 6, 1 }, { 8, 1, 3 } }; Console.WriteLine(getResult(mat));}} // This code is contributed by shikhasingrajput <script> // Javascript Program for the above approach // Function to compress an // array to a single number function append(arr, x) { // create a new ArrayList arr.push(x); return arr; } function compress(arr) { // Stores the required integer let ans = 0; let getBit = 1; // Checking for each position for (let i = 0; i < 32; i++) { let S = 0; let NS = 0; for (let j = 0; j < arr.length; j++) { // Count set and unset bit let temp = getBit & arr[j]; if (temp == 1) { S += 1; } else { NS += 1; } // If count of set bits exceeds // count of unset bits if (S > NS) { // Add value of set bits to ans ans += Math.pow(2, i); } getBit <<= 1; } } return ans; } // Function to compress // matrix to a single number function getResult(mat) { // Stores compressed array let compressedArr = []; let len = mat.length; let len2 = mat[0].length; for (let i = 0; i < len; i++) { let col = []; for (let j = 0; j < len2; j++) { col = append(col, mat[j][i]); } // Compress all columns // to a single number compressedArr = append(compressedArr, compress(col)); } return compress(compressedArr); } let mat = [[3, 2, 4 ],[5, 6, 1],[8, 1, 3]]; document.write(getResult(mat)); // This code is contributed by mukesh07.</script> 1 Time Complexity: O(N*M) Auxiliary Space: O(N) rohitsingh07052 SURENDRA_GANGWAR shikhasingrajput mukesh07 ruhelaa48 array-rearrange setBitCount Arrays Mathematical Matrix Arrays Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Oct, 2021" }, { "code": null, "e": 206, "s": 28, "text": "Given a matrix mat[][] of dimension M * N, the task is to first compress it to obtain an array and, then compress it again to obtain a single integer using following operations:" }, { "code": null, "e": 286, "s": 206, "text": "When a matrix is compressed, its value’s binary representation gets compressed." }, { "code": null, "e": 452, "s": 286, "text": "Therefore, each bit is considered, and if a position of a bit has S set bits and NS non-set bits, then the bit is set for the position if S > NS and unset otherwise." }, { "code": null, "e": 572, "s": 452, "text": "Each column is compressed to turn the matrix into an array, then that array is compressed further into a single number." }, { "code": null, "e": 820, "s": 572, "text": "For example, if 5, 2, 3, and 1 gets compressed then their binary representations (101)2, (010)2, (011)2, and (001)2 gets compressed then for the 0th and 1st positions, S ≤ NS and for the 2nd position S > NS, then the number modifies to (001)2 = 1." }, { "code": null, "e": 830, "s": 820, "text": "Examples:" }, { "code": null, "e": 1024, "s": 830, "text": "Input: arr[][] ={{ 3, 2, 4}, {5, 6, 1}, {8, 1, 3}}Output: 1Explanation: The array obtained after compressing the given matrix from top is {1, 2, 1 }.Then, the obtained array is compressed to 1." }, { "code": null, "e": 1068, "s": 1024, "text": "Input: arr[][] = {{ 5, 3}, {6, 7}}Output: 0" }, { "code": null, "e": 1186, "s": 1068, "text": "Approach: The idea is to count the number of set bits for each position. Follow the steps below to solve the problem:" }, { "code": null, "e": 1288, "s": 1186, "text": "Traverse through each element of each column of a matrix and compress each column to a single number." }, { "code": null, "e": 1336, "s": 1288, "text": "Count the number of set bits for each position." }, { "code": null, "e": 1426, "s": 1336, "text": "Set the bit for the positions with number of set bits exceeding the number of unset bits." }, { "code": null, "e": 1517, "s": 1426, "text": "Calculate the value after deciding whether to set or not to set the bit for each position." }, { "code": null, "e": 1596, "s": 1517, "text": "After obtaining an array, apply the same steps to obtain the required integer." }, { "code": null, "e": 1647, "s": 1596, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1651, "s": 1647, "text": "C++" }, { "code": null, "e": 1656, "s": 1651, "text": "Java" }, { "code": null, "e": 1664, "s": 1656, "text": "Python3" }, { "code": null, "e": 1667, "s": 1664, "text": "C#" }, { "code": null, "e": 1678, "s": 1667, "text": "Javascript" }, { "code": "// c++ Program for the above approach#include<bits/stdc++.h>using namespace std; // Function to compress an // array to a single number vector<int> append(vector<int> arr, int x) { // create a new ArrayList arr.push_back(x); return arr; } int compress(vector<int> arr) { // Stores the required integer int ans = 0; int getBit = 1; // Checking for each position for (int i = 0; i < 32; i++) { int S = 0; int NS = 0; for (int j = 0; j < arr.size(); j++) { // Count set and unset bit int temp = getBit & arr[j]; if (temp == 1) { S += 1; } else { NS += 1; } // If count of set bits exceeds // count of unset bits if (S > NS) { // Add value of set bits to ans ans += pow(2, i); } getBit <<= 1; } } return ans; } // Function to compress // matrix to a single number int getResult(vector<vector<int>> mat) { // Stores compressed array vector<int> compressedArr; int len = mat.size(); int len2 = mat[0].size(); for (int i = 0; i < len; i++) { vector<int> col; for (int j = 0; j < len2; j++) { col = append(col, mat[j][i]); } // Compress all columns // to a single number compressedArr = append(compressedArr, compress(col)); } return compress(compressedArr); } // Driver Code int main() { vector<vector<int>> mat{{3, 2, 4 },{5, 6, 1},{8, 1, 3}}; cout<<(getResult(mat)); } // THIS CODE IS CONTRIBUTED BY SURENDRA_GANGWAR.", "e": 3276, "s": 1678, "text": null }, { "code": "// Java Program for the above approachimport java.io.*;import java.lang.*;import java.lang.Math;import java.util.*;class GFG { // Function to compress an // array to a single number static Integer[] append(Integer arr[], int x) { // create a new ArrayList List<Integer> arrlist = new ArrayList<Integer>(Arrays.asList(arr)); // Add the new element arrlist.add(x); // Convert the Arraylist to array arr = arrlist.toArray(arr); // return the array return arr; } static int compress(Integer[] arr) { // Stores the required integer int ans = 0; int getBit = 1; // Checking for each position for (int i = 0; i < 32; i++) { int S = 0; int NS = 0; for (int j = 0; j < arr.length; j++) { // Count set and unset bit int and = getBit & arr[j]; if (and == 1) { S += 1; } else { NS += 1; } // If count of set bits exceeds // count of unset bits if (S > NS) { // Add value of set bits to ans ans += Math.pow(2, i); } getBit <<= 1; } } return ans; } // Function to compress // matrix to a single number static int getResult(Integer[][] mat) { // Stores compressed array Integer[] compressedArr = {}; int len = mat.length; int len2 = mat[0].length; for (int i = 0; i < len; i++) { Integer[] col = {}; for (int j = 0; j < len2; j++) { col = append(col, mat[j][i]); } // Compress all columns // to a single number compressedArr = append(compressedArr, compress(col)); } return compress(compressedArr); } // Driver Code public static void main(String[] args) { Integer[][] mat = { { 3, 2, 4 }, { 5, 6, 1 }, { 8, 1, 3 } }; System.out.println(getResult(mat)); }} // This code is contributed by rohitsingh07052.", "e": 5212, "s": 3276, "text": null }, { "code": "# Python Program for the above approach # Function to compress an# array to a single numberdef compress(arr): # Stores the required integer ans = 0 getBit = 1 # Checking for each position for i in range(32): S = 0 NS = 0 for j in arr: # Count set and unset bits if getBit&j: S += 1 else: NS += 1 # If count of set bits exceeds # count of unset bits if S > NS: # Add value of set bits to ans ans += 2**i getBit <<= 1 return ans # Function to compress# matrix to a single numberdef getResult(mat): # Stores compressed array compressedArr = [] for i in range(len(mat)): col = [] for j in range(len(mat[0])): col.append(mat[j][i]) # Compress all columns # to a single number compressedArr.append(compress(col)) return compress(compressedArr) # Driver Codemat = [ [ 3, 2, 4], [5, 6, 1], [8, 1, 3] ] print( getResult(mat) )", "e": 6134, "s": 5212, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to compress an// array to a single numberstatic int[] append(int []arr, int x){ // create a new List List<int> arrlist = new List<int>(arr); // Add the new element arrlist.Add(x); // Convert the Arraylist to array arr = arrlist.ToArray(); // return the array return arr;} static int compress(int[] arr){ // Stores the required integer int ans = 0; int getBit = 1; // Checking for each position for(int i = 0; i < 32; i++) { int S = 0; int NS = 0; for(int j = 0; j < arr.Length; j++) { // Count set and unset bit int and = getBit & arr[j]; if (and == 1) { S += 1; } else { NS += 1; } // If count of set bits exceeds // count of unset bits if (S > NS) { // Add value of set bits to ans ans += (int)Math.Pow(2, i); } getBit <<= 1; } } return ans;} // Function to compress// matrix to a single numberstatic int getResult(int[,] mat){ // Stores compressed array int[] compressedArr = {}; int len = mat.GetLength(0); int len2 = mat.GetLength(1); for(int i = 0; i < len; i++) { int[] col = {}; for (int j = 0; j < len2; j++) { col = append(col, mat[j,i]); } // Compress all columns // to a single number compressedArr = append(compressedArr, compress(col)); } return compress(compressedArr);} // Driver Codepublic static void Main(String[] args){ int[,] mat = { { 3, 2, 4 }, { 5, 6, 1 }, { 8, 1, 3 } }; Console.WriteLine(getResult(mat));}} // This code is contributed by shikhasingrajput", "e": 8198, "s": 6134, "text": null }, { "code": "<script> // Javascript Program for the above approach // Function to compress an // array to a single number function append(arr, x) { // create a new ArrayList arr.push(x); return arr; } function compress(arr) { // Stores the required integer let ans = 0; let getBit = 1; // Checking for each position for (let i = 0; i < 32; i++) { let S = 0; let NS = 0; for (let j = 0; j < arr.length; j++) { // Count set and unset bit let temp = getBit & arr[j]; if (temp == 1) { S += 1; } else { NS += 1; } // If count of set bits exceeds // count of unset bits if (S > NS) { // Add value of set bits to ans ans += Math.pow(2, i); } getBit <<= 1; } } return ans; } // Function to compress // matrix to a single number function getResult(mat) { // Stores compressed array let compressedArr = []; let len = mat.length; let len2 = mat[0].length; for (let i = 0; i < len; i++) { let col = []; for (let j = 0; j < len2; j++) { col = append(col, mat[j][i]); } // Compress all columns // to a single number compressedArr = append(compressedArr, compress(col)); } return compress(compressedArr); } let mat = [[3, 2, 4 ],[5, 6, 1],[8, 1, 3]]; document.write(getResult(mat)); // This code is contributed by mukesh07.</script>", "e": 9808, "s": 8198, "text": null }, { "code": null, "e": 9810, "s": 9808, "text": "1" }, { "code": null, "e": 9858, "s": 9812, "text": "Time Complexity: O(N*M) Auxiliary Space: O(N)" }, { "code": null, "e": 9874, "s": 9858, "text": "rohitsingh07052" }, { "code": null, "e": 9891, "s": 9874, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 9908, "s": 9891, "text": "shikhasingrajput" }, { "code": null, "e": 9917, "s": 9908, "text": "mukesh07" }, { "code": null, "e": 9927, "s": 9917, "text": "ruhelaa48" }, { "code": null, "e": 9943, "s": 9927, "text": "array-rearrange" }, { "code": null, "e": 9955, "s": 9943, "text": "setBitCount" }, { "code": null, "e": 9962, "s": 9955, "text": "Arrays" }, { "code": null, "e": 9975, "s": 9962, "text": "Mathematical" }, { "code": null, "e": 9982, "s": 9975, "text": "Matrix" }, { "code": null, "e": 9989, "s": 9982, "text": "Arrays" }, { "code": null, "e": 10002, "s": 9989, "text": "Mathematical" }, { "code": null, "e": 10009, "s": 10002, "text": "Matrix" } ]
SQL | MINUS Operator - GeeksforGeeks
09 Nov, 2020 The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query. In simple words, we can say that MINUS operator will return only those rows which are unique in only first SELECT query and not those rows which are common to both first and second SELECT queries. Pictorial Representation:As you can see is in the above diagram, the MINUS operator will return only those rows which are present in the result set from Table1 and not present in the result set of Table2. Basic Syntax: SELECT column1 , column2 , ... columnN FROM table_name WHERE condition MINUS SELECT column1 , column2 , ... columnN FROM table_name WHERE condition; columnN: column1, column2.. are the name of columns of the table. Important Points: The WHERE clause is optional in the above query. The number of columns in both SELECT statements must be same. The data type of corresponding columns of both SELECT statement must be same. Sample Tables: Table1 Queries: SELECT NAME, AGE , GRADE FROM Table1 MINUS SELECT NAME, AGE, GRADE FROM Table2 Output:The above query will return only those rows which are unique in ‘Table1’. We can clearly see that values in the fields NAME, AGE and GRADE for the last row in both tables are same. Therefore, the output will be the first three rows from Table1. The obtained output is shown below: Note: The MINUS operator is not supported with all databases. It is supported by Oracle database but not SQL server or PostgreSQL.YouTubeGeeksforGeeks500K subscribers18. Minus in SQL (Top 50 SQL Interview Questions) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=gr0sOah50JU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SQL-Clauses-Operators SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL Trigger | Student Database SQL | Views CTE in SQL Difference between DELETE, DROP and TRUNCATE How to Update Multiple Columns in Single Update Statement in SQL? SQL | GROUP BY Difference between DDL and DML in DBMS SQL Interview Questions What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
[ { "code": null, "e": 23421, "s": 23393, "text": "\n09 Nov, 2020" }, { "code": null, "e": 23818, "s": 23421, "text": "The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query. In simple words, we can say that MINUS operator will return only those rows which are unique in only first SELECT query and not those rows which are common to both first and second SELECT queries." }, { "code": null, "e": 24023, "s": 23818, "text": "Pictorial Representation:As you can see is in the above diagram, the MINUS operator will return only those rows which are present in the result set from Table1 and not present in the result set of Table2." }, { "code": null, "e": 24037, "s": 24023, "text": "Basic Syntax:" }, { "code": null, "e": 24272, "s": 24037, "text": "SELECT column1 , column2 , ... columnN\nFROM table_name\nWHERE condition\nMINUS\nSELECT column1 , column2 , ... columnN\nFROM table_name\nWHERE condition;\n\ncolumnN: column1, column2.. are the name of columns of the table.\n Important Points:" }, { "code": null, "e": 24321, "s": 24272, "text": "The WHERE clause is optional in the above query." }, { "code": null, "e": 24383, "s": 24321, "text": "The number of columns in both SELECT statements must be same." }, { "code": null, "e": 24461, "s": 24383, "text": "The data type of corresponding columns of both SELECT statement must be same." }, { "code": null, "e": 24476, "s": 24461, "text": "Sample Tables:" }, { "code": null, "e": 24483, "s": 24476, "text": "Table1" }, { "code": null, "e": 24492, "s": 24483, "text": "Queries:" }, { "code": null, "e": 24574, "s": 24492, "text": "SELECT NAME, AGE , GRADE\nFROM Table1\nMINUS \nSELECT NAME, AGE, GRADE \nFROM Table2\n" }, { "code": null, "e": 24862, "s": 24574, "text": "Output:The above query will return only those rows which are unique in ‘Table1’. We can clearly see that values in the fields NAME, AGE and GRADE for the last row in both tables are same. Therefore, the output will be the first three rows from Table1. The obtained output is shown below:" }, { "code": null, "e": 26140, "s": 24862, "text": "Note: The MINUS operator is not supported with all databases. It is supported by Oracle database but not SQL server or PostgreSQL.YouTubeGeeksforGeeks500K subscribers18. Minus in SQL (Top 50 SQL Interview Questions) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:56•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=gr0sOah50JU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 26265, "s": 26140, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26287, "s": 26265, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 26291, "s": 26287, "text": "SQL" }, { "code": null, "e": 26295, "s": 26291, "text": "SQL" }, { "code": null, "e": 26393, "s": 26295, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26402, "s": 26393, "text": "Comments" }, { "code": null, "e": 26415, "s": 26402, "text": "Old Comments" }, { "code": null, "e": 26446, "s": 26415, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 26458, "s": 26446, "text": "SQL | Views" }, { "code": null, "e": 26469, "s": 26458, "text": "CTE in SQL" }, { "code": null, "e": 26514, "s": 26469, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 26580, "s": 26514, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26595, "s": 26580, "text": "SQL | GROUP BY" }, { "code": null, "e": 26634, "s": 26595, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 26658, "s": 26634, "text": "SQL Interview Questions" }, { "code": null, "e": 26690, "s": 26658, "text": "What is Temporary Table in SQL?" } ]
WordPress - Quick Guide
WordPress is an open source Content Management System (CMS), which allows the users to build dynamic websites and blogs. WordPress is the most popular blogging system on the web and allows updating, customizing and managing the website from its back-end CMS and components. The Content Management System (CMS) is a software which stores all the data such as text, photos, music, documents, etc. and is made available on your website. It helps in editing, publishing and modifying the content of the website. WordPress was initially released on 27th May, 2003 by Matt Mullenweg and Mike Little. WordPress was announced as open source in October 2009. User Management − It allows managing the user information such as changing the role of the users to (subscriber, contributor, author, editor or administrator), create or delete the user, change the password and user information. The main role of the user manager is Authentication. User Management − It allows managing the user information such as changing the role of the users to (subscriber, contributor, author, editor or administrator), create or delete the user, change the password and user information. The main role of the user manager is Authentication. Media Management − It is the tool for managing the media files and folder, in which you can easily upload, organize and manage the media files on your website. Media Management − It is the tool for managing the media files and folder, in which you can easily upload, organize and manage the media files on your website. Theme System − It allows modifying the site view and functionality. It includes images, stylesheet, template files and custom pages. Theme System − It allows modifying the site view and functionality. It includes images, stylesheet, template files and custom pages. Extend with Plugins − Several plugins are available which provides custom functions and features according to the users need. Extend with Plugins − Several plugins are available which provides custom functions and features according to the users need. Search Engine Optimization − It provides several search engine optimization (SEO) tools which makes on-site SEO simple. Search Engine Optimization − It provides several search engine optimization (SEO) tools which makes on-site SEO simple. Multilingual − It allows translating the entire content into the language preferred by the user. Multilingual − It allows translating the entire content into the language preferred by the user. Importers − It allows importing data in the form of posts. It imports custom files, comments, post pages and tags. Importers − It allows importing data in the form of posts. It imports custom files, comments, post pages and tags. It is an open source platform and available for free. It is an open source platform and available for free. CSS files can be modified according to the design as per users need. CSS files can be modified according to the design as per users need. There are many plugins and templates available for free. Users can customize the various plugins as per their need. There are many plugins and templates available for free. Users can customize the various plugins as per their need. It is very easy to edit the content as it uses WYSIWYG editor (What You See Is What You Get is a user interface that allows the user to directly manipulate the layout of document without having a layout command). It is very easy to edit the content as it uses WYSIWYG editor (What You See Is What You Get is a user interface that allows the user to directly manipulate the layout of document without having a layout command). Media files can be uploaded easily and quickly. Media files can be uploaded easily and quickly. It offers several SEO tools which makes on-site SEO simple. It offers several SEO tools which makes on-site SEO simple. Customization is easy according to the user's needs. Customization is easy according to the user's needs. It allows creating different roles for users for website such as admin, author, editor and contributor. It allows creating different roles for users for website such as admin, author, editor and contributor. Using several plugins can make the website heavy to load and run. Using several plugins can make the website heavy to load and run. PHP knowledge is required to make modifications or changes in the WordPress website. PHP knowledge is required to make modifications or changes in the WordPress website. Sometimes software needs to be updated to keep the WordPress up-to-date with the current browsers and mobile devices. Updating WordPress version leads to loss of data, so a backup copy of the website is required. Sometimes software needs to be updated to keep the WordPress up-to-date with the current browsers and mobile devices. Updating WordPress version leads to loss of data, so a backup copy of the website is required. Modifying and formatting the graphic images and tables is difficult. Modifying and formatting the graphic images and tables is difficult. Database − MySQL 5.0 + Database − MySQL 5.0 + Web Server − Web Server − WAMP (Windows) WAMP (Windows) LAMP (Linux) LAMP (Linux) XAMP (Multi-platform) XAMP (Multi-platform) MAMP (Macintosh) MAMP (Macintosh) 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 PHP Compatibility − PHP 5.2+ PHP Compatibility − PHP 5.2+ When you open the link https://wordpress.org/download/, you will get to see a screen as the following snapshot − WordPress requires MySQL database. So create a new empty database with user/password (for example, user as "root" and password as "root" or else you can set as per your convenience). WordPress requires MySQL database. So create a new empty database with user/password (for example, user as "root" and password as "root" or else you can set as per your convenience). Then, you can continue with the installation process as discussed further. Then, you can continue with the installation process as discussed further. It's very easy to set up WordPress into your system. The following steps describe how to set up WordPress locally on your system. Step (1) − Extract the downloaded WordPress folder and upload it into your web server or localhost. Step (2) − Open your browser and navigate to your WordPress file path, then you will get the first screen of the WordPress installer as shown in the following screen. In our case, the path is localhost/< Your_wordpress_folder >. Select your language for the WordPress and click on Continue. Step (3) − In this step, you can view the information needed for the database before proceeding with WordPress installation. Click on Let's go! Step (4) − Here, you have to enter the information about the MySQL database as described in the following screen. Database Name − Enter the database name which you have created in MySQL database for WordPress. Database Name − Enter the database name which you have created in MySQL database for WordPress. Username − Enter the user name of your MySQL database. Username − Enter the user name of your MySQL database. Password − Enter the password which you had set for MySQL database. Password − Enter the password which you had set for MySQL database. Database Host − Write the host name, by default it will be localhost. Database Host − Write the host name, by default it will be localhost. Table Prefix − It is used to add prefix in the database tables which helps to run multiple sites on the same database. It takes the default value. Table Prefix − It is used to add prefix in the database tables which helps to run multiple sites on the same database. It takes the default value. After filling all information, click on Submit button. Step (5) − WordPress checks the database setting and gives you the confirmation screen as shown in the following snapshot. Click on Run the install Step (6) − Enter administrative information. It contains the following fields − Site Title − Enter the name of the site which you are going to create in WordPress. Site Title − Enter the name of the site which you are going to create in WordPress. Username − Enter the username as per your choice while logging in the WordPress. Username − Enter the username as per your choice while logging in the WordPress. Password twice − Enter password two times to protect your site. Password twice − Enter password two times to protect your site. Your E-mail − Enter your e-mail address which helps to recover the password or any update. Your E-mail − Enter your e-mail address which helps to recover the password or any update. Privacy − It allows the search engine to index this site after checking the checkbox. Privacy − It allows the search engine to index this site after checking the checkbox. After filling all the information, click on the Install WordPress button. Step (7) − After installation being successful, you will get a screen of the stating success as seen in the following screen. You can view your username and password detail added in WordPress. Click on Log In button. Step (8) − After clicking on login, you will get a WordPress Admin Panel as depicted in the following screen. Enter the username and password which you had mentioned during installation as shown in step 6 and click on the Log In button. The WordPress Dashboard is a first screen which will be seen when you log into the administration area of your blog which will display the overview of the website. It is a collection of gadgets that provide information and provide an overview of what's happening with your blog. You can customize your needs by using some quick links such as writing quick draft, replying to latest comment, etc. Dashboard can be categorized as shown in the following snapshot. Each of these categories are discussed in the following sections − The WordPress Dashboard provides navigation menu that contains some menu options such as posts, media library, pages, comments, appearance options, plugins, users, tools and settings on the left side. The dashboard contains different types of widgets which can be shown or hidden on some screens. It contains check boxes to show or hide screen options and also allows us to customize sections on the admin screen. It includes the Customize Your Site button which allows customizing your WordPress theme. The center column provides some of the useful links such as creating a blog post, creating a page and view the front end of your website. Last column contains links to widgets, menus, settings related to comments and also a link to the First Steps With WordPress page in the WordPress codex. The Quick Draft is a mini post editor which allows writing, saving and publishing a post from admin dashboard. It includes the title for the draft, some notes about the draft and save it as a Draft. The WordPress News widget displays the latest news such as latest software version, updates, alerts, news regarding the software etc. from the official WordPress blog. The Activity widget includes latest comments on your blog, recent posts and recently published posts. It allows you to approve, disapprove, reply, edit, or delete a comment. It also allows you to move a comment to spam. This section gives an overview of your blog's posts, number of published posts and pages, and number of comments. When you click on these links, you will be taken to the respective screen. It displays the current version of running WordPress along with the currently running theme on the site. In this chapter, we will study about General Settings in WordPress. WordPress general setting is used to set the basic configuration settings for your site. In the setting administration screen, it is a default setting screen. Following are the steps to access the general settings − Step 1 − Click on Settings → General option in WordPress. Step 2 − The General Setting page is displayed as shown in the following snapshot. Following are the details of the fields on general settings page. Site Title − It displays the name of the site in the template header. Site Title − It displays the name of the site in the template header. Tagline − Displays a short sentence about your site. Tagline − Displays a short sentence about your site. WordPress Address (URL) − It is the URL of WordPress directory where your all core application files are present. WordPress Address (URL) − It is the URL of WordPress directory where your all core application files are present. Site Address(URL) − Enter the site URL which you want your site to display on the browser. Site Address(URL) − Enter the site URL which you want your site to display on the browser. E-mail Address − Enter your e-mail address which helps to recover your password or any update. E-mail Address − Enter your e-mail address which helps to recover your password or any update. Membership − Anyone can register an account on your site after you check this checkbox. Membership − Anyone can register an account on your site after you check this checkbox. New User Default Role − The default role is set for the newly registered user or members. New User Default Role − The default role is set for the newly registered user or members. Timezone − Sets the time zone based on the particular city. Timezone − Sets the time zone based on the particular city. Date Format − Sets the date format as you need to display on the site. Date Format − Sets the date format as you need to display on the site. Time Format − Sets the time format as you need to display on the site. Time Format − Sets the time format as you need to display on the site. Week Starts On − Select the week day which you prefer to start for WordPress calendar. By default it is set as Monday. Week Starts On − Select the week day which you prefer to start for WordPress calendar. By default it is set as Monday. Site Language − Sets the language for the WordPress dashboard. Site Language − Sets the language for the WordPress dashboard. Step3 − After filling all the information about general settings, click on Save Changes button. It saves all your general setting information. The writing settings controls the writing experience and provides options for customizing WordPress site. These settings control the features in the adding and editing posts, Pages, and Post Types, as well as the optional functions like Remote Publishing, Post via e-mail, and Update Services. Following are the steps to access the writing settings − Step (1) − To change writing settings, go to Settings → Writing option. Step (2) − The Writing Setting page is displayed as shown in the following screen. Following are the details of the fields on the page. Formatting − This field defines two sub options for better user experience. The first option Convert emoticons like :-) and :-P to graphics on display will turn text-based emoticons into graphic-based emoticons. The second option WordPress should correct invalidly nested XHTML automatically corrects the invalid XHTML placed within the posts or pages. Formatting − This field defines two sub options for better user experience. The first option Convert emoticons like :-) and :-P to graphics on display will turn text-based emoticons into graphic-based emoticons. The first option Convert emoticons like :-) and :-P to graphics on display will turn text-based emoticons into graphic-based emoticons. The second option WordPress should correct invalidly nested XHTML automatically corrects the invalid XHTML placed within the posts or pages. The second option WordPress should correct invalidly nested XHTML automatically corrects the invalid XHTML placed within the posts or pages. Default Post Category − It is a category to be applied to a post and you can leave it as Uncategorized. Default Post Category − It is a category to be applied to a post and you can leave it as Uncategorized. Default Post Format − It is used by themes to select post format to be applied to a post or create different styles for different types of posts. Default Post Format − It is used by themes to select post format to be applied to a post or create different styles for different types of posts. Post via e-mail − This option uses e-mail address to create posts and publishes posts on your blog through e-mail. To use this, you'll need to set up a secret e-mail account with a POP3 access, and any mail received at this address will be posted. Post via e-mail − This option uses e-mail address to create posts and publishes posts on your blog through e-mail. To use this, you'll need to set up a secret e-mail account with a POP3 access, and any mail received at this address will be posted. Mail Server − It allows reading the e-mails that you send to WordPress and stores them for retrieval. For this, you need to have POP3 compatible mail server and it will have URI address such as mail.example.com, which you should enter here. Mail Server − It allows reading the e-mails that you send to WordPress and stores them for retrieval. For this, you need to have POP3 compatible mail server and it will have URI address such as mail.example.com, which you should enter here. Login Name − To create posts, WordPress will need its own e-mail account. The Login Name will use this e-mail address and should be kept as a secret as spammers will post links redirecting to their own websites. Login Name − To create posts, WordPress will need its own e-mail account. The Login Name will use this e-mail address and should be kept as a secret as spammers will post links redirecting to their own websites. Password − Set password for the above e-mail address. Password − Set password for the above e-mail address. Default Mail Category − It allows selecting custom category for all the posts that are published via Post by e-mail feature. Default Mail Category − It allows selecting custom category for all the posts that are published via Post by e-mail feature. Update Services − When you publish a new post, WordPress will automatically notify the site update services in the box. See the Update Services on the codex for the long list of possible services. Update Services − When you publish a new post, WordPress will automatically notify the site update services in the box. See the Update Services on the codex for the long list of possible services. Step (3) − After filling all the above information, click on Save Changes button to save your information. In this chapter, we will study about Reading Settings in WordPress. Reading Setting is used to set the content related to the front page. You can set the number of post to be displayed on the main page. Following are the steps to access the reading settings − Step (1) − Click on Settings → Reading option in WordPress. Step(2) − The Reading Settings page is displayed as shown in the following screen. Following are the details of the fields on reading settings. Front page displays − This section is used to display the front page in any of the following format − Front page displays − This section is used to display the front page in any of the following format − Your latest posts − It displays latest posts on the front page. Your latest posts − It displays latest posts on the front page. A static page − It displays the static pages on the front page. A static page − It displays the static pages on the front page. Front Page − You can select the actual page you want to display on front page from the drop down. Front Page − You can select the actual page you want to display on front page from the drop down. Posts Page − You can select the page from the drop down which contains posts. Posts Page − You can select the page from the drop down which contains posts. Blog pages show at most − The number of posts to be displayed per page or site. By default, it is set as 10. Blog pages show at most − The number of posts to be displayed per page or site. By default, it is set as 10. Syndication feeds show the most recent − The user can view the number of posts when they download one of the site feeds. By default, it is set as 10. Syndication feeds show the most recent − The user can view the number of posts when they download one of the site feeds. By default, it is set as 10. For each article in a feed, show − This section is used to display the post by selecting any of the following formats − For each article in a feed, show − This section is used to display the post by selecting any of the following formats − Full Text − It displays the complete post. It is set as default. Full Text − It displays the complete post. It is set as default. Summary − It displays the summary of the post. Summary − It displays the summary of the post. Search Engine Visibility − After clicking on the checkbox, Discourage search engines from indexing this site, your site will be ignored by the search engine. Search Engine Visibility − After clicking on the checkbox, Discourage search engines from indexing this site, your site will be ignored by the search engine. Step(3) − After filling all the information, click on Save Changes button to save your Reading Setting information. In this chapter, we will study about Discussion settings in WordPress. WordPress discussion setting can be defined as the interaction between the blogger and the visitors. These settings are done by the admin to have a control over the posts/pages that come in through users. Following are the steps to access the Discussion setting − Step (1) − Click on Settings → Discussion option in WordPress. Step (2) − The Discussion Settings page is displayed as shown in the following snapshot. Following fields are seen in Discussion settings. Default article settings − These settings are default to the new pages you create or new posts. This contains three more settings. They are − Default article settings − These settings are default to the new pages you create or new posts. This contains three more settings. They are − Attempt to notify any blogs linked to from the article − When you publish articles then it sends a notification (sends pings and trackback) to other blogs. Attempt to notify any blogs linked to from the article − When you publish articles then it sends a notification (sends pings and trackback) to other blogs. Allow link notifications from other blogs (pingbacks and trackbacks) − Accepts pings from other blogs. Allow link notifications from other blogs (pingbacks and trackbacks) − Accepts pings from other blogs. Allow people to post comments on new articles − You can allow or disallow other people to comment on your article using this setting. Allow people to post comments on new articles − You can allow or disallow other people to comment on your article using this setting. You can change the settings as per your will for individual articles. Other Comment Settings − This setting has the following options − Other Comment Settings − This setting has the following options − Comment author must fill out name and e-mail − When you check this box, it is mandatory for visitors to fill their name and email address. Comment author must fill out name and e-mail − When you check this box, it is mandatory for visitors to fill their name and email address. Users must be registered and logged in to comment − If you check this box, only those registered visitors can leave comments, if not checked anyone can leave any number of comments. Users must be registered and logged in to comment − If you check this box, only those registered visitors can leave comments, if not checked anyone can leave any number of comments. Automatically close comments on articles older than days − This option allows you to accept comments only for a particular time period as per your wish. Automatically close comments on articles older than days − This option allows you to accept comments only for a particular time period as per your wish. Enable threaded (nested) comments − When you check this option, visitors can reply or have a discussion and get responses. Enable threaded (nested) comments − When you check this option, visitors can reply or have a discussion and get responses. Break comments into pages with top level comments per page and the page displayed by default − If your pages are getting a lot of comments then you can split them into different pages by checking this box. Break comments into pages with top level comments per page and the page displayed by default − If your pages are getting a lot of comments then you can split them into different pages by checking this box. Comments should be displayed with the comments at the top of each page − You can arrange the comments in the form of ascending or descending order. Comments should be displayed with the comments at the top of each page − You can arrange the comments in the form of ascending or descending order. Email me whenever − This setting contains two options, namely − Anyone posts a comment − When you check into this box, the author gets an e-mail for every single comment that is posted. A comment is held for moderation − This is used in case you do not want your comment to be updated before it's moderated by the admin. Email me whenever − This setting contains two options, namely − Anyone posts a comment − When you check into this box, the author gets an e-mail for every single comment that is posted. Anyone posts a comment − When you check into this box, the author gets an e-mail for every single comment that is posted. A comment is held for moderation − This is used in case you do not want your comment to be updated before it's moderated by the admin. A comment is held for moderation − This is used in case you do not want your comment to be updated before it's moderated by the admin. Before a comment appears − This setting allows how your posts are controlled. There are two more settings as followed − Comment must be manually approved − If you check this box then only the approved comments by the admin can be displayed on the posts or pages. Comment author must have a previously approved comment − This can be checked when you want to approve a comment of an author whose has commented and his e-mail address matches the e-mail address of the previous posted comment. Otherwise the comment is held for moderation. Before a comment appears − This setting allows how your posts are controlled. There are two more settings as followed − Comment must be manually approved − If you check this box then only the approved comments by the admin can be displayed on the posts or pages. Comment must be manually approved − If you check this box then only the approved comments by the admin can be displayed on the posts or pages. Comment author must have a previously approved comment − This can be checked when you want to approve a comment of an author whose has commented and his e-mail address matches the e-mail address of the previous posted comment. Otherwise the comment is held for moderation. Comment author must have a previously approved comment − This can be checked when you want to approve a comment of an author whose has commented and his e-mail address matches the e-mail address of the previous posted comment. Otherwise the comment is held for moderation. Comment Moderation − Contain only a specific number of links that are allowed into a comment. Comment Moderation − Contain only a specific number of links that are allowed into a comment. Comment Blacklist − You can input your own spam words which you do not want your visitors to enter into the comments, URL, e-mail etc.; later it would filter the comments. Comment Blacklist − You can input your own spam words which you do not want your visitors to enter into the comments, URL, e-mail etc.; later it would filter the comments. Avatars − Avatar is a small image that displays at the top-right-hand corner of the dashboard screen beside your name. It is like your profile picture. Here you have a few more options where you can set your avatar for WordPress site. Avatar Display − It displays your avatar besides your name when it is checked. Maximum rating − You have a four other options of avatars you can use. They are G, PG, R and X. This is the age section where you select according to which type of audience you want to display your posts. Default Avatar − In this option, there are few more types of avatars with images; you can keep these avatars according to your visitors e-mail address. Avatars − Avatar is a small image that displays at the top-right-hand corner of the dashboard screen beside your name. It is like your profile picture. Here you have a few more options where you can set your avatar for WordPress site. Avatar Display − It displays your avatar besides your name when it is checked. Avatar Display − It displays your avatar besides your name when it is checked. Maximum rating − You have a four other options of avatars you can use. They are G, PG, R and X. This is the age section where you select according to which type of audience you want to display your posts. Maximum rating − You have a four other options of avatars you can use. They are G, PG, R and X. This is the age section where you select according to which type of audience you want to display your posts. Default Avatar − In this option, there are few more types of avatars with images; you can keep these avatars according to your visitors e-mail address. Default Avatar − In this option, there are few more types of avatars with images; you can keep these avatars according to your visitors e-mail address. Step (3) − Click on Save Changes button to save the changes. In this chapter, we will study about Media Settings in WordPress. It is used to set the height and width of the images which you're going to use on your website. Step (1) − Click on Settings → Media option in WordPress. Step (2) − The Media Settings page is displayed as seen in the following screenshot. Following are the details of the fields on Media settings − Thumbnail size − Set the size of the thumbnail. Thumbnail size − Set the size of the thumbnail. Medium size − Set the height and width of medium size images. Medium size − Set the height and width of medium size images. Large size − Set width and height of larger images. Large size − Set width and height of larger images. Uploading files − After checking this checkbox, the uploaded image will be arranged into year and month based folder. Uploading files − After checking this checkbox, the uploaded image will be arranged into year and month based folder. Step (3) − After setting the dimension in pixels, click on Save Changes button. It saves your media setting information. In this chapter, we will learn about Permalink settings in WordPress. Permalink is a permanent link to a particular blog post or category. It allows setting the default permalink structure. These settings are used to add permalinks to your posts in WordPress. Following are the steps to access permalink settings. Step (1) − Click on Settings → Permalinks option from the left navigation menu. Step (2) − When you click on Permalinks, the following page appears on the screen. Here are a few settings you can make − Common settings − Check any of the radio buttons to choose your permalink structure for your blogs Default − It sets the default URL structure in Wordpress. Day and name − It sets URL structure according to the date and name in your posts. Month and name − It sets the URL structure according to the month and name in your post. Numeric − It sets numbers in the URL structure in your post. Post name − It sets post name in the URL structure in your post. Custom Structure − It sets the URL structure of your choice by writing the desired name in the given text box. Common settings − Check any of the radio buttons to choose your permalink structure for your blogs Default − It sets the default URL structure in Wordpress. Default − It sets the default URL structure in Wordpress. Day and name − It sets URL structure according to the date and name in your posts. Day and name − It sets URL structure according to the date and name in your posts. Month and name − It sets the URL structure according to the month and name in your post. Month and name − It sets the URL structure according to the month and name in your post. Numeric − It sets numbers in the URL structure in your post. Numeric − It sets numbers in the URL structure in your post. Post name − It sets post name in the URL structure in your post. Post name − It sets post name in the URL structure in your post. Custom Structure − It sets the URL structure of your choice by writing the desired name in the given text box. Custom Structure − It sets the URL structure of your choice by writing the desired name in the given text box. Optional These are optional. You can add custom structure for main category or tag URL. If your text box is empty then default settings is used. Here you have two options. Category Base − Add custom prefix for your category URL. Tag Base − Add custom prefix to your Tags URL. Optional These are optional. You can add custom structure for main category or tag URL. If your text box is empty then default settings is used. Here you have two options. Category Base − Add custom prefix for your category URL. Category Base − Add custom prefix for your category URL. Tag Base − Add custom prefix to your Tags URL. Tag Base − Add custom prefix to your Tags URL. Step (3) − Once you are done with changes, click on Save Changes button to save the permalink settings. In this chapter, we will study how to use plugins in your WordPress site. Plugin allows to easily modify, customize or enhance WordPress blog or post. The WordPress Plugin is a software that can be uploaded to expand the functionality of the site. They add services or features to WordPress blog. Plugins are used to make your work easier. Following are the simple steps to add plugins. Step (1) − On the left side bar, Click on Plugins → Installed Plugins as shown in the screen. Step (2) − The following page appears. In this section, you can view the already installed plugins. Step (3) − Click on → Plugins → Add New menu as shown in the following screen. Step (4) − A list of plugins appears that are used in WordPress. Here you can directly install plugins from the available list or you can upload it by clicking on Upload Plugin. When you click on Upload Plugin you'll get the following page. Click on Browse, it goes back to the page where you can select plugins from WordPress site. And if you click on Choose File, you can add files from your system. Otherwise, you can directly choose the plugin that you need and click on Install now as seen in the following screenshot. When you click on Install Now, the package starts to download and gets installed. Then, click on Activate plugin to active that plugin to use in WordPress as seen in the following screen. After clicking on Activate Plugin you'll get a message as Plugin activated and you can also find the installed plugin in the list. Below the plugin activated message, you can view few options such as All, Active, Inactive and Update available. When you click on Active the following page appears. Here you can view all the activated plugins. When we click on Inactive, the plugins which are available but are not activated gets displayed. You can activate this plugin by clicking on Activate. When you click on Update available, you'll get a list of plugins that must be updated. Click on Update and you get a message as Updated. Click on Bulk Actions and select any of the options. Click on Apply button to update, delete, activate or deactivate each of the plugins by checking the boxes. In Search Installed Plugins you can just type your plugin name in the text box that is already installed and click on the Search Installed Plugins button. When you click on the Search installed Plugin button you get the following page with your respective plugin. Step (5) − Click on Plugins → Editor from the side bar. Step (6) − The following page gets displayed. This page lets you edit your plugins. A few options are explained. Select plugin to edit − Allows you to select a plugin from the dropdown and edit it. Select plugin to edit − Allows you to select a plugin from the dropdown and edit it. Documentation − Allows you to select the tools from the dropdown to edit the plugin. Documentation − Allows you to select the tools from the dropdown to edit the plugin. Plugin files − Allows you to select files from the list and edit accordingly. Plugin files − Allows you to select files from the list and edit accordingly. Finally, after editing the plugin files, click on Update file. In this chapter, we will study about how to Add Categories in WordPress. Category is used to indicate sections of your site and group related posts. It sorts the group content into different sections. It is a very convenient way to organize the posts. To access the Category section, follows the mentioned steps − Step (1) − Click on Posts → Categories option in WordPress. Step (2) − The Categories page is displayed as shown in the following screenshot. Following are the details of the fields on Categories. Name − Enter the unique name of categories. Name − Enter the unique name of categories. Slug − A word chosen to describe your post. It is specified in the tags URL. Slug − A word chosen to describe your post. It is specified in the tags URL. Parent − By selecting the parent category from dropdown, you can set the particular category as sub-category or can keep it as None. Parent − By selecting the parent category from dropdown, you can set the particular category as sub-category or can keep it as None. Description − Add brief description of your category. It is optional. Description − Add brief description of your category. It is optional. Step (3) − After filling all the information about Categories, click on Add New Category button. Step (4) − After clicking on Add New Category, the new created category will get displayed on the right side of the page as shown in the following screen. In this chapter, we will study the simple steps to Edit Categories in WordPress. Following are the simple steps to edit categories in WordPress. Step (1) − Click on Posts → Categories in WordPress. Step (2) − You can view Category1 (Category1 was created in the chapter WordPress - Add Category). When the cursor hovers on the Categories, then a few options get displayed below the Category name. There are two ways to edit the categories i.e. Edit and Quick Edit Edit − Click on Edit option in Categories section as seen in the following screenshot. You can edit any of the required field, and then click Update button as shown in the following screen. Category fields are same from the chapter WordPress - Add Category. Quick Edit − Click on Quick Edit option in Categories section as shown in the following screen. Here, you can only edit the Name and Slug of the category as seen in the following screen and then finally click on Update Category button. In this chapter, we will study about how to Delete Categories in WordPress. Following are the simple steps to delete categories in WordPress. Step (1) − Click on Posts → Categories in WordPress. Step (2) − You can delete Category1 (Category1 was created in the chapter Wordpress - Add Category). When the cursor hovers on the Categories, a few options get displayed below the Category name. Click on Delete button as shown in the following screen. When you click on delete, you will get a pop message asking for confirmation to delete the particular category as shown in the following screenshot. You can click on OK button and delete the category permanently. In this chapter, we will study about how to Arrange Categories in WordPress. You can't arrange categories directly in WordPress. Hence, you will need to install Category Order plugin to arrange the created categories in a particular way. Step (1) − Click on Posts → Category Order in WordPress. The Category Order menu displays after adding the Category Order plugin. You can study how to install plugins in the chapter Install Plugins. Step (2) − In the following screen, you can see that the create categories section are not in order. Step (3) − Now, you can rearrange your categories by just dragging the categories as per your choice. Click on Order categories button to save the ordered categories. In this chapter, we will study how to Add Posts in WordPress. Posts are also known as articles and sometimes referred as blogs or blog posts. These are used to popularize your blogs. Following are the simple steps to Add Posts in WordPress. Step (1) − Click on Posts → Add New in WordPress. Step (2) − You will get the editor page of the Post as shown in the following screen. You can use the WordPress WYSIWYG editor to add the actual content of your post. We will study in detail about WYSIWYG editor in the chapter WordPress - Add Pages. Following are the fields on the editor page of the Add Posts Page. Post Title − Enter the title of the post, i.e., Post1. Post Title − Enter the title of the post, i.e., Post1. Post Content − Enter the content of your post. Post Content − Enter the content of your post. Step (3) − Click on Publish button to publish your respective post. Following are the few other options present in the Publish section. Save Draft − It saves the post as a draft. Save Draft − It saves the post as a draft. Preview − You can preview your post before publishing. Preview − You can preview your post before publishing. Move to Trash − Deletes the post. Move to Trash − Deletes the post. Status − Change the status of your post to Published, Pending, or Reviewer Draft. Status − Change the status of your post to Published, Pending, or Reviewer Draft. Visibility − Change the visibility of the post to Public, Private or Password protected. Visibility − Change the visibility of the post to Public, Private or Password protected. Published − Change the publishded post date and time. Published − Change the publishded post date and time. In this chapter, we will study how to Edit Posts on WordPress. Following are the simple steps to Edit Posts in WordPress. Step (1) − Click on Posts → All Posts in WordPress. Step (2) − You can view Post1 (Post1 was created in the chapter WordPress - Add Posts). When the cursor hovers on the Post, few options get displayed below the Post name. There are two ways to edit the Post i.e. Edit and Quick Edit. Edit − Click on Edit option in Post1 as shown in the following screen. You can edit or change the content or title of the post as per your needs, and then click on Update button as shown in the following screen. Quick Edit − Click on Quick Edit option in Post1 as shown in the following screenshot. Here you can edit the Title, Slug and date of the posts and can also select the categories for your post as shown in the following screenshot and then click on Update button to confirm post edits. In this chapter, we will study how to Delete Posts in WordPress. Following are the steps to Delete Posts in WordPress. Step (1) − Click on Posts → All Post in WordPress. Step (2) − You can delete Post1 (Post1 was created in the chapter Wordpress - Add Posts). When the cursor hovers on the Post, then a few options get displayed below Post1. Click on Trash option to delete the post. Step (3) − You can view your post lists to confirm if the above post is deleted. In this chapter, we will study how to Preview Posts in WordPress. Preview Post is to view the post before it is published to the user. It is safer to preview your post and verify how your post looks on the website. You can edit or change the post as per your need after previewing. Following are the simple steps to Preview Posts in WordPress. Step (1) − Click on Posts → All Posts in wordPress. Step (2) − You can view Post1 (Post1 was created in the chapter Wordpress - Add Posts). When the cursor hovers on the Post, then a few options get displayed below the Post name. Click on the View option as shown in the following screenshot. Or else you can view your post directly while editing or adding post by clicking on the Preview button as shown in the following screen. Step (3) − You can view your post, when you click on View or Preview. In this chapter, we will study how to Publish Posts in WordPress. Publish is used to make the post available to all the users wherein every user can view that particular post. Publishing a new post in WordPress is an easy process. Following are the steps to Publish Posts in WordPress. Step (1) − Click on Posts → Add New in WordPress. Step (2) − You will get the editor page of the Post as shown in the following screenshot. You can use the WordPress WYSIWYG editor to add the actual content of your post. Step (3) − Click on Publish button to publish your respective post. After clicking on publish, your posts get published for the user to view it. In this chapter, we will learn about Media Library in WordPress. Media Library consists of the images, audios, videos and files that you can upload and add to the content when writing a Post or Page. Here you can view, add, edit or delete any media related objects if not needed. Following are the steps to understand about Media Library. Step (1) − Click on Media → Library in WordPress. Step (2) − You can view media files like images, audios, videos. Click on Add Media button. Step (3) − The Upload New Media page gets displayed. You can learn how to Add Media in the next chapter. Step (4) − You can view a bar as shown in the following screenshot. The various tabs that appear have the following functions − List View − Displays the images and videos in list form. Grid View − Displays all images in the grid format as shown in the following screen. Filter the images and videos − Filters the images and videos. Search Box − Helps to search a particular image by inserting the name into the box. In this chapter, we will study how to Add Media files in WordPress. WordPress allows you to add, all kind of media files like videos, audios and images. Following are the steps to Add Media. Step (1) − Click on Media → Add New in WordPress. Step (2) − Then, click on Select Files option to select the files from your local storage as shown in the following figure. Step (3) − Add Media files such as images and audios by selecting them and click open as shown in the following screenshot. Step (4) − You can view the list of media files added as shown in the following screenshot. In this chapter, we will study how to Insert Media in WordPress. Media files can be inserted to your Pages or Posts from libraries, from local storage or from URLs. Following are the steps to Insert Media in WordPress. Step (1) − Click on Posts → Add New in WordPress. Step (2) − Click on Add Media. Step (3) − You can select the files from the Media Library tab as shown in the following screenshot. Information about the selected media file will be displayed on the right side of the screen under the Attachment Details. Click on Insert Post button, the image will be inserted into the post. In Attachment Details section, you will find information about the images such as URL, Title, Caption, Alt Text and Description You can also insert an image directly from your system by clicking on Upload Files tab. Click on Insert into Post button. In this chapter, we will study how to Edit Media in wordPress. You can manage all the information about your media that is saved in the Media Library. Following are the steps to Edit Media in WordPress. Step (1) − Click on Media → Library and click on the name of the media item or the edit link. Step (2) − You will view a list of media files. Select any one image to edit. Step (3) − You can view the edit media page with few options on the right side. URL − You can read only a link from media file. URL − You can read only a link from media file. Title − This displays the name of the media. Title is often shown in galleries and attachment pages, if themes or plugins are designed to display it. Title − This displays the name of the media. Title is often shown in galleries and attachment pages, if themes or plugins are designed to display it. Permalink − Permalink is the URL of the media attachment page. This is also a link to view the attachment page. Permalink − Permalink is the URL of the media attachment page. This is also a link to view the attachment page. Edit image button − This allows you to edit the image position, such as rotate counter-clockwise, rotate clockwise, scale, crop, flip vertically, and flip horizontally. Edit image button − This allows you to edit the image position, such as rotate counter-clockwise, rotate clockwise, scale, crop, flip vertically, and flip horizontally. Caption − A brief explanation of the media. Caption − A brief explanation of the media. Alternate Text − The alt text for the image, which is used to describe media. Used for availability. Alternate Text − The alt text for the image, which is used to describe media. Used for availability. Description − An explanation of your media file. Description − An explanation of your media file. Delete Permanently − Delete your media file permanently. Delete Permanently − Delete your media file permanently. Step (4) − Once you complete editing the required fields, click on Update button to save the changes made to an image. In this chapter, we will study how to Add Pages into the WordPress. Adding pages is similar to adding posts in WordPress. Pages are static content and often do not change its displayed information. Following are the simple steps to add pages in WordPress. Step (1) − Click on Pages → Add New as shown in the following screenshot. Step (2) − You will get the editor page as seen in the following screenshot. The editor page has two tabs, Visual and Text. You can insert text in either of these. Here, we'll study about inserting text into Visual format. Following are the details of the fields on editor page of the Add New Page. It is used to write the title of the article, which is later displayed on the page. Permalink shows the potential URL for the page below the title. The URL generates as per the given title. It is a WYSIWYG Editor, which is similar to a word processor interface where you can edit the contents of the article. Following are the options present of WYSIWYG editor − Bold Button − Used to bold your font. Bold Button − Used to bold your font. Italic − Used to italicize the font. Italic − Used to italicize the font. Word Strike − Strikes through the content. Word Strike − Strikes through the content. Bullet List − Adds bullets to content. Bullet List − Adds bullets to content. Number List − Adds numbers to the list of the content. Number List − Adds numbers to the list of the content. Blockquote − Quotes the text. Blockquote − Quotes the text. Horizontal Line − Creates a horizontal line between sentences. Horizontal Line − Creates a horizontal line between sentences. Left Align − Sets the content on the left side of the page. Left Align − Sets the content on the left side of the page. Right Align − Sets the content to the right side of the page. Right Align − Sets the content to the right side of the page. Justify − Justifies the content of the page. Justify − Justifies the content of the page. Add Link − Adds a link to your content. When you click on this button, the following page gets displayed. Add Link − Adds a link to your content. When you click on this button, the following page gets displayed. Following are the fields present in the Insert/edit link. URL − Enter URL you want to link. URL − Enter URL you want to link. Link text − Insert text you want to enter into the link. Link text − Insert text you want to enter into the link. Open link in a new window/tab − Open your link page into the new tab or window. Check the box as required. Open link in a new window/tab − Open your link page into the new tab or window. Check the box as required. Or link to existing account − Links to an existing content page by selecting the page from the given list. When you click on existing page then you get a link created in the URL section as seen in the following screenshot. Or link to existing account − Links to an existing content page by selecting the page from the given list. When you click on existing page then you get a link created in the URL section as seen in the following screenshot. Remove Link − Deletes the particular link added for text or content. Remove Link − Deletes the particular link added for text or content. Read more tag − Adds Read More tag to your page. Read more tag − Adds Read More tag to your page. Toolbar toggle − Clicking on this you get another list of toolbar as shown in the following image. Toolbar toggle − Clicking on this you get another list of toolbar as shown in the following image. Paragraph − Selects the headings as required for the text from the dropdown. Paragraph − Selects the headings as required for the text from the dropdown. Underline − Underlines the sentences. Underline − Underlines the sentences. Justify − Justifies your content. Justify − Justifies your content. Text Color − Sets color for words or sentences. Text Color − Sets color for words or sentences. Paste as Text − Pastes your text. Paste as Text − Pastes your text. Clear Formatting − Deletes selected content. Clear Formatting − Deletes selected content. Special character − Inserts special characters needed in your content. Special character − Inserts special characters needed in your content. Increase Indent − Increases the indent of the page. Increase Indent − Increases the indent of the page. Decrease Indent − Decreases the indent of the page. Decrease Indent − Decreases the indent of the page. Undo − Reverses the most recent editing command. Undo − Reverses the most recent editing command. Redo − Opposite of undo, restores the most recent editing command. Redo − Opposite of undo, restores the most recent editing command. For writing the content of an article. To publish the page to the user on the website. Page attributes module allows you to select the parents for your particular page. You can also set order of the pages. Parent − Allows you to select parent page. Parent − Allows you to select parent page. Order − Sets the order of the page. Order − Sets the order of the page. Includes the images in the pages. In this chapter, we will study how to Publish Pages in WordPress. The command, “Publish” is used to make the pages available to all users wherein each user can view that particular page. Publishing a new page in WordPress is an easy process. Following are the steps to Publish Pages in WordPress. Step (1) − Click on Pages → Add New in WordPress. Step (2) − You will get the editor as shown in the following screenshot. You can use the WordPress WYSIWYG editor to add the actual content of your page. Step (3) − Click on Publish button as shown in the following screen. After clicking on publish, your posts get published for the user to view it. In this chapter, we will study how to Edit pages in WordPress. Step (1) − Click on Pages → All Pages in WordPress as shown in the following screen. Step (2) − You can view About Us (About Us was created in the chapter WordPress - Add Pages). When the cursor hovers on the pages, then few options get displayed below About Us. There are two ways to edit the Post, i.e., Edit and Quick Edit. Edit − Click on Edit option in About Us as shown in the following screenshot. You can edit or change the content or title from the page as per your need, and then click on Update button as shown in the following screen. Quick Edit − Click on Quick Edit option in About Us as shown in the following screen. You can edit the Title, Slug and date of the About Us page and can also select the parent for your page as shown in the following shot and then click on Update button. In this chapter, we will learn to Delete Pages in WordPress. Following are the steps to Delete pages in wordPress. Step (1) − Click on Pages → All Pages in WordPress. Step (2) − You can delete Sample Page (Sample Page is created by default in WordPress). When the cursor hovers on the pages, then a few options gets displayed below the Sample Page. Click on Trash option to delete the post. Or alternatively you can also delete your page directly while editing or adding page by clicking on the Move to Trash button as shown in the following screen. Step (3) − To confirm that you have deleted the page, view your page list. Tag is a small information attached to the main content or post for the purpose of identification. It tells the visitors what actually the post is about. If the tag is mentioned properly then it helps to find the content very easily. Following are the steps to Add Tags in WordPress. Step (1) − Click on Posts → Tags in WordPress. Step (2) − The Tags page is displayed. Following are the details of the fields on Tags. Name − Enter the name of tags. Name − Enter the name of tags. Slug − A word chosen to describe your post. It is specified in the tags URL. Slug − A word chosen to describe your post. It is specified in the tags URL. Description − Add brief description of your tag. It gets displayed when you hover on the tag. Description − Add brief description of your tag. It gets displayed when you hover on the tag. After filling all the information about Tags, click on Add New Tag button. Step (3) − The new created tags will get displayed on the right side of the page as shown in the following screenshot. In this chapter, we will study to Edit Tags in WordPress. You can learn how to add tags in the chapter WordPress - Add Tags. Following are the simple steps to Edit Tags in WordPress. Step (1) − Click on Posts → Tags in WordPress. Step (2) − You can view tag Food around the world (Food around the world was created in the chapter Wordpress - Add Tags). When the cursor hovers on the Tags, then a few options get displayed below the Tag name. There are two ways to edit the tags i.e. Edit and Quick Edit Edit − Click on Edit option in Tags section as shown in the following screen. You can edit any of the required field, and then click on Update button as shown in the following screen. Here tag fields are same from the chapter WordPress - Add Tags. Quick Edit − Click on Quick Edit option in Tags section as shown in the following screenshot. Here you can only edit the Name and Slug of the Tags as seen in the following screen and then click on Update Tag button. In this chapter, we will learn to Delete tags in WordPress. Following are the steps to delete tags in WordPress. Step (1) − Click on Posts → Tags in WordPress. Step (2) − You can delete tag Food around the world (Food around the world was created in the chapter WordPress - Add Tags), when the cursor hovers on the Tags, then a few options get displayed below the Tags name. Click on Delete in tags section as shown in the following screen. When you click on delete, you will get a pop message asking for confirmation to delete. You can click on OK button and delete the tag permanently. In this chapter, we will learn to Add Links in WordPress pages. Link is a connection from one resource to another. Adding links to your pages or blog posts help you to connect to other pages. Following are the simple steps to Add links in WordPress. Step (1) − Click on Pages → All Pages in WordPress. Step (2) − List of pages created in WordPress will get displayed as shown in the following screen. Select any of the pages to add links inside it. Here, we are going to add links in About Us page. Step (3) − Select any of the sentence or word where you want to add link. Here, we will add link to the word Lorem. Step (4) − When you click on the Insert/Edit link symbol then the following pop window gets displayed. Following are the fields present in the Insert/edit link. URL − Enter URL you want to link. URL − Enter URL you want to link. Link text − Insert text you want to enter into the link. Link text − Insert text you want to enter into the link. Open link in a new window/tab − Open your link page into the new tab or window. Check the box as required. Open link in a new window/tab − Open your link page into the new tab or window. Check the box as required. Or link to existing account − Add links to an existing content page by selecting the page from the given list. Click on Or link to existing account and the list of pages and posts gets displayed as shown in the following screen. Or link to existing account − Add links to an existing content page by selecting the page from the given list. Click on Or link to existing account and the list of pages and posts gets displayed as shown in the following screen. After selecting the particular page or post from the list, the links get created in the URL field as seen in the preceding screen. Click on Add Link. Step (5) − When you hover on the word Lorem then the link tooltip gets displayed as shown in the following screen. Click on Update button to update the changes in your page or post. In this chapter, we will study how to edit link in WordPress. Following are the simple steps to Edit Links in WordPress Step (1) − Click on Pages → All Pages as shown in the following screen. Step (2) − You can view the list of pages. When the cursor hovers on the About Us page, then a few options get displayed below About Us. Click on Edit as shown. Step (3) − Hover on the word Lorem (Link for word Lorem was created in the chapter WordPress - Add Links), and click on the pencil symbol to edit the link as shown in the following screen. Step (4) − You can change or edit your link by selecting the page from the existing list. In this case, we have selected the About Us page. After selecting the particular page or post from the list, then click on Update button. Step (5) − When you hover on the word Lorem then the link tooltip get displayed as seen in the following screen. Click on Update button to update the changes in your page or post. In this chapter, we will learn to Delete links from WordPress. You can remove the unwanted links which you don’t need for your website or article. Following are the steps to Delete Links in WordPress Step (1) − Click on Pages → All Pages in WordPress. Step (2) − You can view the list of pages. When the cursor hovers on the About Us page, then a few options gets displayed. Click on the Edit button as shown in the following screen. Step (3) − Select the word which you had already linked i.e. Lorem (Link for word Lorem was created in the chapter WordPress - Add Links), and click on the Remove Link Symbol as seen in the following screen. Step (4) − When you hover on the word Lorem, there will be no tooltip of the existing URL. The following screenshot shows that the link has been deleted. In this chapter, we will learn to Add Comments in WordPress. Adding comments allows your visitors to have a discussion with you. Comments are approved by the admin and then posted to be discussed further. Following are the steps to add comments to your blog posts. Step (1) − Click on Pages → All Pages in WordPress. Step (2) − The list of pages created in WordPress will get displayed as seen in the following screen. Select any of the pages you want to add comments to. Here, we are going to add comment in About Us page. Click on About Us. Step (3) − To add a comment on this page, click on Screen options present at the top right hand corner. Step (4) − The dropdown list of Screen Option gets displayed. Check the Discussion and Comments box as shown in the following screen. Step (5) − You can now view the Discussion and Comments box at the bottom of your page. In the Discussion section, there are two options present − Allow Comments − Allows visitors to comment on your blog posts and pages. Allow Comments − Allows visitors to comment on your blog posts and pages. Allow trackbacks and pingbacks on this page − Allows visitors to give pings and trackbacks. Allow trackbacks and pingbacks on this page − Allows visitors to give pings and trackbacks. In the Comment section, you can add comments by clicking on Add Comment button. Step (6) − Click on Update button after adding the comment box. In this chapter, we will learn about how to Edit comments in WordPress. Editing comments can be done only by the admin. Following are the steps to Edit Comments in WordPress. Step (1) − Click on Comments in WordPress. Step (2) − You can view the comments list for the various pages. Select any comment, you want to edit. Click on edit. Step (3) − The Edit comment page gets displayed. You can edit the comment and click on Update Button. Here you can edit the name, e-mail, URL or the comment from the comment box. In this chapter, we will learn to Moderate Comments in WordPress. Comment moderation is a process where, when visitors comment on posts, the comment is not published directly until and unless it is approved by the admin to be posted. It manages your comments so that there is no comment spamming. Step (1) − Click on Settings → Discussion in WordPress. Step (2) − The Discussion Setting page gets displayed. In the Comment Moderation field, enter those words or URLs you do not want any visitor to add comments. Whenever a visitor gives any comments it would be moderated by the admin first and then published. Step (3) − Click on Save Changes. In this chapter, we will study how to View Plugins in WordPress. It helps you to enable and disable WordPress Plugins. This adds the unique features to an existing web site. Plugins extend and enlarge the functionality of WordPress. Following are the simple steps to View Plugins in WordPress. Step (1) − Click on Plugins → Installed Plugins in WordPress administrator. Step (2) − You will see the list of existing plugins on your site as seen in the following screen. A table of Plugin and Description is displayed. Names of the plugins are defined in Plugin column and a brief description about the plugin is defined under Description column. Following functions appear as Plugin toolbar options on the page − Active − Shows the active plugins on the website. Active − Shows the active plugins on the website. Inactive − Shows the installed but inactive plugins on the website. Inactive − Shows the installed but inactive plugins on the website. Update Available − Shows, if a new version is available or asks to update now. Update Available − Shows, if a new version is available or asks to update now. In this chapter, we will study how to install plugins in WordPress. It is really easy to install plugins. All the plugins are free to download; the only condition is that a plugin must be in the WordPress directory. Following are the simple steps to Install Plugins in WordPress. Step (1) − Click on Plugins → Add New in WordPress. Step (2) − Enter your required plugin name in the search box as shown in the following screen. List of plugins which are relevant to the plugins name will get displayed as seen in the following screen. Select the required plugin you want to use. Here, we have searched All in one SEO Pack plugin, which happens to be the first plugin as shown in the preceding screen. Click on install now button to install the plugin on your website. Step (3) − The plugins automatically start downloading and installing. Click on Activate Plugin to activate the plugin on your website, which makes your task much easier using this plugin. Step (4) − Once activated, you will see the installed plugin in the list of plugins as seen in the following screen. In this chapter, we will study how to Customize Plugins in WordPress without writing any HTML or CSS. It's usually a large addition for multi-user sites. This new method allows you to customize your login page by using the WordPress theme customizer (no coding skills required). Following are the simple steps to Customize Plugins in WordPress. Step (1) − Click on Plugins → Add New. Step (2) − Install and activate the Custom Login Page Customizer Plugin. Step (3) − Click on Appearance → Login Customize section. Step (4) − Click on Start Customizing button to proceed further. Step (5) − It will launch the built-in WordPress theme customizer. You can customize the theme and make it look the way you want. Click on the new Login Customizer tab in the side panel. Login customizer page will get displayed. On the login customizer page, you can customize your login page in the same way as you customize your WordPress theme. Step (6) − The customized login page will appear as shown in the following screen. Logo − Upload logo of your choice to replace the default WordPress logo. Logo − Upload logo of your choice to replace the default WordPress logo. Background − Add background image or you can choose a background color of your choice. Background − Add background image or you can choose a background color of your choice. Form Background − Select form background image or color for login form container of your choice. Form Background − Select form background image or color for login form container of your choice. Most of the selections in the customizer panel are transparent. You can check all the selections in the customizer to adjust the setting as per your requirement of your login page. Click on Save and Publish button. In this chapter, we will learn about the roles of users in WordPress. Every user has their own role in WordPress. Roles are like permissions given to a particular user to access the WordPress site. These roles can be allotted only by the Admin. Here are few pre-defined roles available in WordPress − Administrator − The Administrator has all the rights. An Admin can do anything and everything on the WordPress site such as creating more admins, inviting more users and also removing them. Administrator − The Administrator has all the rights. An Admin can do anything and everything on the WordPress site such as creating more admins, inviting more users and also removing them. Editor − The Editor has access to all the posts, pages, comments, categories, tags, and links. They can create, publish, edit or delete any posts or pages. Editor − The Editor has access to all the posts, pages, comments, categories, tags, and links. They can create, publish, edit or delete any posts or pages. Author − The Author can only write posts, upload pictures, edit, and publish their own posts. Author − The Author can only write posts, upload pictures, edit, and publish their own posts. Contributor − The Contributor can only write and edit their posts until published. They can create their own posts and pages but cannot publish them. They cannot upload images or files but can see your site's status. When they want to publish any post, it must be first notified personally to the administrator for review. When the post is approved, the contributor cannot make any changes once published. Contributor − The Contributor can only write and edit their posts until published. They can create their own posts and pages but cannot publish them. They cannot upload images or files but can see your site's status. When they want to publish any post, it must be first notified personally to the administrator for review. When the post is approved, the contributor cannot make any changes once published. Follower − The Follower can only read and comment on the posts. Followers are the ones who have signed in to your account to receive updates. Follower − The Follower can only read and comment on the posts. Followers are the ones who have signed in to your account to receive updates. Viewer − Viewers can only view your posts; they cannot edit but can only comment on the posts. Viewer − Viewers can only view your posts; they cannot edit but can only comment on the posts. In this chapter, we will study how to Add users to your WordPress blog or website. When users register on your WordPress blog or website, you get an e-mail notification, so you always know when new users register, and you can then get into your Dashboard and edit the users’ role. Following are the simple steps to Add Users in WordPress. Step (1) − Click on Users → Add New in WordPress. Step (2) − You can fill the user detail on the Add New User page. Fill in all the required fields (as seen in the following screen) to proceed further. Username (required) − Enter the unique username, which you want to display on website. Username (required) − Enter the unique username, which you want to display on website. E-mail (required) − Enter the valid e-mail address. The user receives notifications from the site at this e-mail address. E-mail (required) − Enter the valid e-mail address. The user receives notifications from the site at this e-mail address. First Name − Enter the user’s first name. First Name − Enter the user’s first name. Last Name − Enter the user’s last name. Last Name − Enter the user’s last name. Website − Enter the URL for the user’s website. Website − Enter the URL for the user’s website. Password (required) − Enter the password. Password (required) − Enter the password. Repeat Password (required) − Repeat the same password as the previous password for authentication. Repeat Password (required) − Repeat the same password as the previous password for authentication. Send Password − Send password to the New User by e-mail checkbox. The user will receive an e-mail with the new password. Send Password − Send password to the New User by e-mail checkbox. The user will receive an e-mail with the new password. Role − Select the particular role from the dropdown, i.e., Subscriber, Contributor, Author, Editor, or Administrator. Role − Select the particular role from the dropdown, i.e., Subscriber, Contributor, Author, Editor, or Administrator. Click on Add New User button to add user to your users list. Step (3) − You can view the user list to see whether the users have been added. A message will be displayed as New User Created as seen in the following screen. In this chapter, we will study about User Photo in WordPress. To add user photo in WordPress, you must install plugin User Photo from WordPress plugins. It helps you add a photo of your own to your WordPress profile. Following are the simple steps to add a User photo. Step (1) − Click on Settings → User Photo. Step (2) − The User Photo Options page gets displayed. Set the dimension for your thumbnails and make the required changes and then click on Update Options button. Step (3) − To view the plugin User Photo is activated, go to Users → Your Profile. In your Profile page you can see Your Photo section is added. Here you can upload your photo to display as profile image. In this chapter, we will study how to Edit Users in WordPress. Following are the simple steps to Edit Users in WordPress. Step (1) − Click on Users → All Users. Step (2) − You will see a list of users. There are two more tabs seen on the toolbar − Administrator − List of administrators will be displayed. Administrator − List of administrators will be displayed. Subscriber − List of subscribers will be displayed. Subscriber − List of subscribers will be displayed. When we click on the Change role to box, a dropdown list appears as seen in the preceding screenshot. Subscriber − A person who can only manage his profile. Subscriber − A person who can only manage his profile. Contributor − A person who can write and supervise own posts, but cannot publish them. Contributor − A person who can write and supervise own posts, but cannot publish them. Author − A person who can publish and manage his own posts. Author − A person who can publish and manage his own posts. Editor − A person who can publish and manage posts, including the posts of other users. Editor − A person who can publish and manage posts, including the posts of other users. Administrator − A person who has access to all the administration features within a single website. Administrator − A person who has access to all the administration features within a single website. Click on the check box of the user name to change the role of the user. Then, click on change button and the user's role will be changed accordingly. Step (3) − Click on Edit option as shown in the following screen to edit the user. Step (4) − The Edit User page is displayed. Here you can edit or modify all the fields as per your need and click on Update User to save the changes. In this chapter, we will learn how to delete users in WordPress. Following are the steps to Delete Users. Step (1) − Click on Users → All Users. Step (2) − List of Users gets displayed as shown in the following screen. Step (3) − Select the one you want to delete. And click on Delete. Step (4) − When you click on Delete you get the following page. Step (5) − Select options as required and click on Confirm Deletion. Your user will be deleted. Step (6) − We have another method of deleting users. A screen as shown in the following shot appears. Here you can select the users to delete, check the boxes and click on Delete from the dropdown list and click on Apply. Step (7) − Once you click on Apply, the users selected will be deleted. In this chapter, we will learn how to create a Personal profile in WordPress. Following are the steps to Personal Profile. Step(1) − Click on Users → Your Profile from the left navigation bar. Step (2) − When you click on ‘Your profile’ the following screen will be displayed. The following Personal options appear on the screen − Visual editor − While you are adding posts/pages to your site you can enable this setting if you wish to create, format, or edit your post. If you disable this setting, you won’t be able to use this option. Visual editor − While you are adding posts/pages to your site you can enable this setting if you wish to create, format, or edit your post. If you disable this setting, you won’t be able to use this option. Admin color scheme − You can change the color of your WordPress site by selecting any of the following. Admin color scheme − You can change the color of your WordPress site by selecting any of the following. Keyboard Shortcuts − If you are too fast at getting your work done and need keyboard shortcuts then you can check this box. Keyboard Shortcuts − If you are too fast at getting your work done and need keyboard shortcuts then you can check this box. Toolbar − If you check this box, you can view the toolbar while using WordPress. Toolbar − If you check this box, you can view the toolbar while using WordPress. Name Username − Enter your user name. Username − Enter your user name. First Name/ Last Name − Enter your first name and last name. First Name/ Last Name − Enter your first name and last name. Nick name − Enter nick names if any. Nick name − Enter nick names if any. Display name publicly as − Check the box if you want your name to be displayed publicly. Display name publicly as − Check the box if you want your name to be displayed publicly. Contact Info E-mail − Enter a valid e-mail address. E-mail − Enter a valid e-mail address. Website − Type in your web address. Website − Type in your web address. About yourself Biographical Info − Some details about you. Biographical Info − Some details about you. New password − Enter a password of your choice. New password − Enter a password of your choice. Repeat password − Re-enter the password for authentication. Password must contain 7 characters. Repeat password − Re-enter the password for authentication. Password must contain 7 characters. Your photo − You can upload an image of your own from your computer. This will be your profile picture. Your photo − You can upload an image of your own from your computer. This will be your profile picture. Step (3) − After you have updated all the changes, click on Update Profile. In this chapter, we will learn about Theme management. It includes image files, templates, CSS stylesheets, etc. that can help to make your website look great. This chapter discusses how to install, add new, or customize themes in WordPress. Following are the steps for Theme Management. Step (1) − Select Appearance → Themes from the dashboard. Step (2) − The following screen will be displayed. Hover over any theme and click on Theme Details. Step (3) − When you click on Theme Detail the following page appears. It consists of details related to the theme. Details like version, description, tags etc. If you want to add this theme to your page/website then click on Activate, and if you want to just check the theme, then click on Live preview. If you click on activate then you get a pop-up message as − Step (4) − Click on Customize. Step (5) − On the left side of the page, you can customize your theme. Any changes you make or anything new you add is displayed on the right side of the page. We will learn about customizing the appearance of the themes in the next chapter i.e.; WordPress Customize Theme. In this chapter, we will learn how to customize themes. Customizing themes help you to give a new look to your website. Here you can change background images/colors, add titles, and do much more. Following are the steps of Customize theme. Step (1) − Click on Appearance → Customize. Step (2) − The following screen will be displayed. As can be seen, on the left side we have the customizing section, and on the right side we have the theme you have chosen. So any changes you make on the left side will be displayed on the right side of the page. Here are a few options you must know − Active theme − In this section, you can change the current theme just by clicking on ‘Change’. When you click on ‘Change’ you get a list of themes, click on any of the themes, and then click ‘Save & Continue’. Your theme will be saved. Site Title & Tagline − In this section, you can add the site title and tagline you want to add to your website. Add your title name in the ‘Site Title’ section. And your tagline in the ‘Tagline’ box. Colors − You can change your header text color using this section. As you scroll through the colors you find changes happening on the right side of your page. You can even add a color of your own into the box that is situated in between ‘Current color’ and ‘Default’. Header Image − Add a header image either by selecting from the suggestions or you can add an image of your own by clicking on ‘Add new image’. Widgets − Add widgets to your site from here. When you click on the arrow mark the following image appears. Here, there are two options − First is the ‘Main Widget Area’, when you click on this you get another list of widgets that are to be displayed in the footer area. When you click on any of the widgets a dropdown appears where you can edit more or add more. For example − If you want to add categories then the following image appears. In this image, as you can see, you can add your category in the ‘Title’ section. Check any of the required boxes. If you do not want to add any, then say ‘Remove’. Same goes for other widgets too. Secondary Widget − Here you must click on ‘Add a widget’ and you get a side bar with a list of different widgets. Click on any and it adds up to your widget list. If you want to add more widgets then click on ‘Add a widget’ again and you can add as many widgets as you want. Static Front − Select either latest posts or static front page for your site. In this chapter, we will study about Widget Management. Widgets are small blocks that perform specific functions. These give design and structure control to the WordPress theme. Some specific features of a widget are − They help you add content and features. They can be easily dragged and dropped in widget area. They vary from theme to theme. They are not same for every theme. Step (1) − Click on Appearance → Widgets. Step (2) − The following screen showing available widgets appear. The following functions appear on the page − Available Widgets − You can use these to add into your sidebar main. Available Widgets − You can use these to add into your sidebar main. Inactive Sidebar (not used) − These are not used and can be removed permanently from the widget list. Inactive Sidebar (not used) − These are not used and can be removed permanently from the widget list. Inactive Widgets − Removes the widgets from sidebar but keep it in the settings. Inactive Widgets − Removes the widgets from sidebar but keep it in the settings. Sidebar Main − Any widget you add here will appear on your site. Sidebar Main − Any widget you add here will appear on your site. Manage in Customizer − Takes you back to customization page. Manage in Customizer − Takes you back to customization page. Step (3) − Drag and drop in the Sidebar Main. Any widget you add here, shows up on your site. In this chapter, we will study about background images, background colors and background opacity. Step (1) − Click on Appearance → Background. Step (2) − The following page appears where the Background Image section shows up. Step (3) − There’s no image selected for background. If you want to do so, then click on Select Image. You get the following page. Here you can upload images using two options. Upload Files Media Library Step (4) − Upload Files − When you click on Upload files the following screen is displayed. Select files from your desktop and then click on Choose Image if satisfied with the image. Step (5) − Media Library − When you click on Media Library the following page appears. Select files from the WordPress media library, which means, if you already have images updated then you can select any of them directly. After selecting an image, on the right side you will get a few options − Edit Image − When you click on this you are taken to another page where you can edit the scale image, dimensions, crop image, and thumbnail settings, etc. As shown in the following image, make the required changes, click on Save and then click on Update. Edit Image − When you click on this you are taken to another page where you can edit the scale image, dimensions, crop image, and thumbnail settings, etc. As shown in the following image, make the required changes, click on Save and then click on Update. Delete Permanently − If you want your image off the library then click on this button. Delete Permanently − If you want your image off the library then click on this button. URL − Enter your image URL into this box. URL − Enter your image URL into this box. Title − If you want to make any changes in the title of the image you can do it right here. Title − If you want to make any changes in the title of the image you can do it right here. Caption − You can explain briefly about your image in this section. Caption − You can explain briefly about your image in this section. Alt text − Give an alternative text to your image so that it is easily available for the users during search. Alt text − Give an alternative text to your image so that it is easily available for the users during search. Description − A little description about your image. Description − A little description about your image. Step (6) − Click on Colors → Background Color on the same page. Change your background color accordingly. Background Opacity is not used for all themes. Theme customization is not same for every theme we use. It changes from theme to theme. In this chapter, we will study how to transfer WordPress to a new hosting platform. Here, we have used Hostinger web hosting to transfer the WordPress site to another host. Just follow the simple steps given below to transfer your WordPress site to another host. Step (1) − Keep the backup of WordPress files and export the database. We will study about this in detail in the chapter WordPress - Backup & Restore Step (2) − Login to your cPanel and click on MySQL Databases as shown in the following screen. Step (3) − Create a new database and MySQL user as shown in the following screen. The page has the following fields − MySQL Database Name − Enter your database name. MySQL Database Name − Enter your database name. MySQL Username − Enter your username. MySQL Username − Enter your username. Password − Set password for your database. Password − Set password for your database. Password again − Once again set the same password as previous for authentication. Password again − Once again set the same password as previous for authentication. After filling all the fields, Click on Create button. Step (4) − You can view your created MySQL database, User and Host as shown in the following screen. Step (5) − Click on + symbol. Step (6) − Click on phpMyAdmin. Step (7) − Click on Import tab on the phpMyAdmin page. Step (8) − Click on Choose File button to select the backup file from your system and click on Go button. Step (9) − You can view the tables of database uploaded as shown in the following screen. Step (10) − Upload your WordPress files by using file transfer protocol(FileZilla) as shown in the chapter WordPress - Backup & Restore in Restoring WordPress Files section. Step (11) − Edit wp-config.php file as mentioned in the Restoring WordPress Files section in chapter Wordpress - Backup & Restore. Step (12) − Inside the Website section of hostinger, Click on Auto Installer. Step (13) − You can view the uploaded file of the WordPress. Click on the URL link as shown in the following screen. Step (14) − You can view the login page of WordPress. In this chapter, we will study how to update version in WordPress. Here, we will upgrade WordPress to the latest version through the admin panel. Following are a few simple steps to update the version in WordPress. Step (1) − Click on Please Update Now as shown in the following screen. You will get notifications in WordPress admin panel when there is a newer version available for WordPress. Before updating, it is advised to keep WordPress backup. Step (2) − After clicking on the update link, the following page gets displayed. Click on Update Now button. Step (3) − The following message gets displayed during the upgradation of WordPress. Note − While updating the version, if you get an error as then you need to take the following actions − Open your WordPress folder → wp-includes folder Open your WordPress folder → wp-includes folder Open class-http.php file and add the following line at the beginning: set_time_limit (0); Open class-http.php file and add the following line at the beginning: set_time_limit (0); Save the file. Save the file. Now your WordPress is successfully upgraded. In this chapter, we will learn how to protect your WordPress blog or website from spam. Make sure that your WordPress script is updated to the latest stable version. WordPress comes with a preinstalled antispam solution - Akismet. You can activate Akismet, for which you should have a WordPress API key. You have to register at the official WordPress website. The key will be sent to your mail box. Following are the steps to follow to enable Akismet Spam Protection plugin for your website or blog. Step (1) − Go to your WordPress admin area → Plugins → Installed. The following screen will be displayed. Step (2) − Click on Activate button as shown in the following screen. Step (3) − The Akismet plugin will be activated and then Click on Activate your Akismet account button as shown in the following screen. Step (4) − Click on Get your API key as seen in the following screen to get a new key or enter manually, if you already have API key. Step (5) − If you don't have API key then, click on GET AN AKISMET API KEY tab to move further. Step (6) − Fill up the required fields and click on Sign up button as shown in the following screen. Step (7) − Once you complete with signup process. You will get an API key in your registered e-mail id. Enter API key manually and click on Use this key button as seen in the following screen. Step (8) − If you have entered a correct API key, it will be verified and you will get a confirmation message as reflected in the following screen. Step (9) − Now your blog will be protected from spam by Akismet. You will be able to check the comments in your blog for spam, as well as manually mark comments as spam from the blog admin area → Comments. You can keep a track of how many spam posts have been stopped by Akismet and you can secure your posts, blogs, comments, etc. Furthermore, you can prevent your website from spammers, who can harm your site. In this chapter, we will study how to Backup & Restore files and database in WordPress. In WordPress there are two parts of backing up such as − WordPress Files Backup WordPress Database Backup WordPress Files Restore WordPress Database Restore To get the backup files of WordPress, you need to install FileZilla Client on your system. Following are the simple steps used for files backup operation in WordPress − Step (1) − Open the FileZilla Client as shown in the following screenshot. Step (2) − Enter the Host, Username, Password and Port like you have used to log-in to your cPanel. After filling all the fields, click on Quickconnect button. Step (3) − You will get all files and folders of your WordPress site on the right side as seen in the following screen. Step (4) − Select all the files and folders and right click on the mouse and click on Download. After downloading the WordPress files from cPanel, it will be saved on your system. Following are the simple steps for database backup in WordPress − Step (1) − Type the path http://localhost/phpmyadmin in your browser. You will get the following screen. Step (2) − Click on the database name ‘wordpress’ which you have created for WordPress. Step (3) − After clicking on database wordpress, it will open the following page. Click on Export tab. Step (4) − You will get two methods to export the database i.e. Quick and Custom. Select any one of the methods and click on Go button. After exporting the database file, it will get saved on your system. Following are the simple steps used to restore the files in WordPress using ftp − Step (1) − Open the FileZilla Client and login to your site using ftp as shown in the following screen. Step (2) − Open the local directory in ftp and upload all WordPress files to your website as shown in the following screen. Step (3) − Then, go to your wordpress folder → wp-config.php file. Copy and rename wp-config.php file before editing, in case of some mistake you can restore this file back. Open the wp-config.php file and locate the following code. define('DB_NAME', 'db_name'); Replace the db_name with your database name which you have created. define('DB_USER', 'db_user'); Replace the db_user with your username of MySql. define('DB_PASSWORD', 'db_password'); Replace the db_password with your password of MySql. Save your wp-config file after editing and upload it to your WordPress site through ftp. Following are the steps used to restore the database in WordPress − Step (1) − Type the path http://localhost/phpmyadmin in the browser. The following screen will pop up. You can create a new database or import your backup in the existing database. Here we'll create a new database name, i.e., new_wordpress and click on Create button. Step (2) − You can view your created database as shown in the following screen. Click on the database name new_wordpress. Step (3) − Click on Import. Step (4) − Click on Choose File button to select the backup file from your system. After uploading the sql file, select format as SQL as shown in the following screen. Click on Go button. Step (5) − Once you click on Go, you will get a message after the sql file is uploaded successfully. In this chapter, we will study how to Optimize WordPress site. Here are a few simple tips to optimize your WordPress site. Ensure high quality and meaningful content. Have the right names for images. Use short permalinks that contain keywords. Have optimized themes. Sitemap should be in XML format. Connect posts to social networks. Beware of black hat techniques. Delete your trash box. Keep Checking Your Site Statistics Keep checking your plugins. Use CSS and JavaScript effectively. Any page you create, the most important thing that matters is the content. You must have good content with keywords that can be helpful for users, not for the search engines. Content should be understandable and not complicated or difficult to read. The names you choose for your images must be unique; consider choosing images keeping the user in mind. Use keywords that might be helpful for the users. Have some specific names for your images and don’t forget to add your alt tags and title tags to your images. For example − If your image is about Chocolate sundae Ice-cream then do not mention the name as DSC12346, instead put it as ‘Chocolate-sundae-High-street-restaurant-new-york.jpg’. This would be much easier to search. The permalinks you use must be understandable. For example − http://www.mywebsite.com/tutorialspoint/telangana/ instead of http://www.mywebsite.com/page-id?5631456325 Use those themes that are fast and are optimized for WordPress so that when applied to a website, it must not have low speed. Google has many tools that can be useful. Tools like Website Optimizer, Webmaster Central, and Google XML sitemaps are very easy to use. Social media is a very important aspect today. So have them connected to your blog posts, pages, etc., to have good ranks and popularity. Help promote others posts and pages too and they will do the same in return. Don’t trick Google as it finds you in no time. Don’t put yourself in trouble and create problems for your site by using black hat techniques. Be sure to use genuine SEO techniques. Always consider clearing your trash for more speed and to have a good flow with your website. Size of page matters a lot. The more images, flash, videos or media related posts on your page, the more it would be slower to load. Yslowi> module plugin is recommended to help you get a faster page browsing. Having many plugins in WordPress may also be the reason for your page to slow load. So keep a check on your plugins which you’re working on. Consider checking your plugins before you add them. Always keep your CSS at the upper side of the page and JavaScript at the bottom. Let CSS load first and then JavaScript. Here is a plugin that will help you get your JavaScript’s at the bottom of the page. It is Footer javaScript. In this chapter, we will learn how to reset your passwords in WordPress. We have two methods of resetting passwords in WordPress − User User Lost your password Lost your password Let's look how to set password through the User section. Step (1) − Login to your wordPress admin panel and click on Users → All Users from the dashboard. Step (2) − When you click on All Users you get a page with a list of users. From this select the one you want to reset password of and click on edit. When you click on edit, the following page gets displayed. Now let's look into resetting your password using Lost your password section. Step (3) − In this page you can type in your new password that must contain 7 characters. Once you are done with setting your new password click on Update Profile. Step (3.1) − When you try logging into your WordPress admin panel, you forget your password and need to reset it, you get the following message on the page. Step (3.2) − Click on Lost your password? The following page appears. Update your e-mail and say Get New Password. Step (3.3) − After you click, you get a message saying a Link has been sent to the e-mail address you provided. Step (3.4) − Go to your e-mail and open the (Wordpress Site) Password Reset mail and click on the link that is provided. Step (3.5) − Type your new password, confirm again if required and then click on Reset Password. 57 Lectures 2 hours Amit Diwan 23 Lectures 2.5 hours Sasha Miller 23 Lectures 1.5 hours Zach Miller 45 Lectures 2 hours Zach Miller 19 Lectures 4 hours Eduonix Learning Solutions 145 Lectures 12.5 hours Theo McArthur Print Add Notes Bookmark this page
[ { "code": null, "e": 3519, "s": 3245, "text": "WordPress is an open source Content Management System (CMS), which allows the users to build dynamic websites and blogs. WordPress is the most popular blogging system on the web and allows updating, customizing and managing the website from its back-end CMS and components." }, { "code": null, "e": 3753, "s": 3519, "text": "The Content Management System (CMS) is a software which stores all the data such as text, photos, music, documents, etc. and is made available on your website. It helps in editing, publishing and modifying the content of the website." }, { "code": null, "e": 3895, "s": 3753, "text": "WordPress was initially released on 27th May, 2003 by Matt Mullenweg and Mike Little. WordPress was announced as open source in October 2009." }, { "code": null, "e": 4177, "s": 3895, "text": "User Management − It allows managing the user information such as changing the role of the users to (subscriber, contributor, author, editor or administrator), create or delete the user, change the password and user information. The main role of the user manager is Authentication." }, { "code": null, "e": 4459, "s": 4177, "text": "User Management − It allows managing the user information such as changing the role of the users to (subscriber, contributor, author, editor or administrator), create or delete the user, change the password and user information. The main role of the user manager is Authentication." }, { "code": null, "e": 4619, "s": 4459, "text": "Media Management − It is the tool for managing the media files and folder, in which you can easily upload, organize and manage the media files on your website." }, { "code": null, "e": 4779, "s": 4619, "text": "Media Management − It is the tool for managing the media files and folder, in which you can easily upload, organize and manage the media files on your website." }, { "code": null, "e": 4912, "s": 4779, "text": "Theme System − It allows modifying the site view and functionality. It includes images, stylesheet, template files and custom pages." }, { "code": null, "e": 5045, "s": 4912, "text": "Theme System − It allows modifying the site view and functionality. It includes images, stylesheet, template files and custom pages." }, { "code": null, "e": 5171, "s": 5045, "text": "Extend with Plugins − Several plugins are available which provides custom functions and features according to the users need." }, { "code": null, "e": 5297, "s": 5171, "text": "Extend with Plugins − Several plugins are available which provides custom functions and features according to the users need." }, { "code": null, "e": 5417, "s": 5297, "text": "Search Engine Optimization − It provides several search engine optimization (SEO) tools which makes on-site SEO simple." }, { "code": null, "e": 5537, "s": 5417, "text": "Search Engine Optimization − It provides several search engine optimization (SEO) tools which makes on-site SEO simple." }, { "code": null, "e": 5634, "s": 5537, "text": "Multilingual − It allows translating the entire content into the language preferred by the user." }, { "code": null, "e": 5731, "s": 5634, "text": "Multilingual − It allows translating the entire content into the language preferred by the user." }, { "code": null, "e": 5846, "s": 5731, "text": "Importers − It allows importing data in the form of posts. It imports custom files, comments, post pages and tags." }, { "code": null, "e": 5961, "s": 5846, "text": "Importers − It allows importing data in the form of posts. It imports custom files, comments, post pages and tags." }, { "code": null, "e": 6015, "s": 5961, "text": "It is an open source platform and available for free." }, { "code": null, "e": 6069, "s": 6015, "text": "It is an open source platform and available for free." }, { "code": null, "e": 6138, "s": 6069, "text": "CSS files can be modified according to the design as per users need." }, { "code": null, "e": 6207, "s": 6138, "text": "CSS files can be modified according to the design as per users need." }, { "code": null, "e": 6323, "s": 6207, "text": "There are many plugins and templates available for free. Users can customize the various plugins as per their need." }, { "code": null, "e": 6439, "s": 6323, "text": "There are many plugins and templates available for free. Users can customize the various plugins as per their need." }, { "code": null, "e": 6652, "s": 6439, "text": "It is very easy to edit the content as it uses WYSIWYG editor (What You See Is What You Get is a user interface that allows the user to directly manipulate the layout of document without having a layout command)." }, { "code": null, "e": 6865, "s": 6652, "text": "It is very easy to edit the content as it uses WYSIWYG editor (What You See Is What You Get is a user interface that allows the user to directly manipulate the layout of document without having a layout command)." }, { "code": null, "e": 6913, "s": 6865, "text": "Media files can be uploaded easily and quickly." }, { "code": null, "e": 6961, "s": 6913, "text": "Media files can be uploaded easily and quickly." }, { "code": null, "e": 7021, "s": 6961, "text": "It offers several SEO tools which makes on-site SEO simple." }, { "code": null, "e": 7081, "s": 7021, "text": "It offers several SEO tools which makes on-site SEO simple." }, { "code": null, "e": 7134, "s": 7081, "text": "Customization is easy according to the user's needs." }, { "code": null, "e": 7187, "s": 7134, "text": "Customization is easy according to the user's needs." }, { "code": null, "e": 7291, "s": 7187, "text": "It allows creating different roles for users for website such as admin, author, editor and contributor." }, { "code": null, "e": 7395, "s": 7291, "text": "It allows creating different roles for users for website such as admin, author, editor and contributor." }, { "code": null, "e": 7461, "s": 7395, "text": "Using several plugins can make the website heavy to load and run." }, { "code": null, "e": 7527, "s": 7461, "text": "Using several plugins can make the website heavy to load and run." }, { "code": null, "e": 7612, "s": 7527, "text": "PHP knowledge is required to make modifications or changes in the WordPress website." }, { "code": null, "e": 7697, "s": 7612, "text": "PHP knowledge is required to make modifications or changes in the WordPress website." }, { "code": null, "e": 7910, "s": 7697, "text": "Sometimes software needs to be updated to keep the WordPress up-to-date with the current browsers and mobile devices. Updating WordPress version leads to loss of data, so a backup copy of the website is required." }, { "code": null, "e": 8123, "s": 7910, "text": "Sometimes software needs to be updated to keep the WordPress up-to-date with the current browsers and mobile devices. Updating WordPress version leads to loss of data, so a backup copy of the website is required." }, { "code": null, "e": 8192, "s": 8123, "text": "Modifying and formatting the graphic images and tables is difficult." }, { "code": null, "e": 8261, "s": 8192, "text": "Modifying and formatting the graphic images and tables is difficult." }, { "code": null, "e": 8284, "s": 8261, "text": "Database − MySQL 5.0 +" }, { "code": null, "e": 8307, "s": 8284, "text": "Database − MySQL 5.0 +" }, { "code": null, "e": 8320, "s": 8307, "text": "Web Server −" }, { "code": null, "e": 8333, "s": 8320, "text": "Web Server −" }, { "code": null, "e": 8348, "s": 8333, "text": "WAMP (Windows)" }, { "code": null, "e": 8363, "s": 8348, "text": "WAMP (Windows)" }, { "code": null, "e": 8376, "s": 8363, "text": "LAMP (Linux)" }, { "code": null, "e": 8389, "s": 8376, "text": "LAMP (Linux)" }, { "code": null, "e": 8411, "s": 8389, "text": "XAMP (Multi-platform)" }, { "code": null, "e": 8433, "s": 8411, "text": "XAMP (Multi-platform)" }, { "code": null, "e": 8450, "s": 8433, "text": "MAMP (Macintosh)" }, { "code": null, "e": 8467, "s": 8450, "text": "MAMP (Macintosh)" }, { "code": null, "e": 8501, "s": 8467, "text": "Operating System − Cross-platform" }, { "code": null, "e": 8535, "s": 8501, "text": "Operating System − Cross-platform" }, { "code": null, "e": 8618, "s": 8535, "text": "Browser Support − IE (Internet Explorer 8+), Firefox, Google chrome, Safari, Opera" }, { "code": null, "e": 8701, "s": 8618, "text": "Browser Support − IE (Internet Explorer 8+), Firefox, Google chrome, Safari, Opera" }, { "code": null, "e": 8730, "s": 8701, "text": "PHP Compatibility − PHP 5.2+" }, { "code": null, "e": 8759, "s": 8730, "text": "PHP Compatibility − PHP 5.2+" }, { "code": null, "e": 8872, "s": 8759, "text": "When you open the link https://wordpress.org/download/, you will get to see a screen as the following snapshot −" }, { "code": null, "e": 9055, "s": 8872, "text": "WordPress requires MySQL database. So create a new empty database with user/password (for example, user as \"root\" and password as \"root\" or else you can set as per your convenience)." }, { "code": null, "e": 9238, "s": 9055, "text": "WordPress requires MySQL database. So create a new empty database with user/password (for example, user as \"root\" and password as \"root\" or else you can set as per your convenience)." }, { "code": null, "e": 9313, "s": 9238, "text": "Then, you can continue with the installation process as discussed further." }, { "code": null, "e": 9388, "s": 9313, "text": "Then, you can continue with the installation process as discussed further." }, { "code": null, "e": 9518, "s": 9388, "text": "It's very easy to set up WordPress into your system. The following steps describe how to set up WordPress locally on your system." }, { "code": null, "e": 9618, "s": 9518, "text": "Step (1) − Extract the downloaded WordPress folder and upload it into your web server or localhost." }, { "code": null, "e": 9847, "s": 9618, "text": "Step (2) − Open your browser and navigate to your WordPress file path, then you will get the first screen of the WordPress installer as shown in the following screen. In our case, the path is localhost/< Your_wordpress_folder >." }, { "code": null, "e": 9909, "s": 9847, "text": "Select your language for the WordPress and click on Continue." }, { "code": null, "e": 10034, "s": 9909, "text": "Step (3) − In this step, you can view the information needed for the database before proceeding with WordPress installation." }, { "code": null, "e": 10053, "s": 10034, "text": "Click on Let's go!" }, { "code": null, "e": 10167, "s": 10053, "text": "Step (4) − Here, you have to enter the information about the MySQL database as described in the following screen." }, { "code": null, "e": 10263, "s": 10167, "text": "Database Name − Enter the database name which you have created in MySQL database for WordPress." }, { "code": null, "e": 10359, "s": 10263, "text": "Database Name − Enter the database name which you have created in MySQL database for WordPress." }, { "code": null, "e": 10414, "s": 10359, "text": "Username − Enter the user name of your MySQL database." }, { "code": null, "e": 10469, "s": 10414, "text": "Username − Enter the user name of your MySQL database." }, { "code": null, "e": 10537, "s": 10469, "text": "Password − Enter the password which you had set for MySQL database." }, { "code": null, "e": 10605, "s": 10537, "text": "Password − Enter the password which you had set for MySQL database." }, { "code": null, "e": 10675, "s": 10605, "text": "Database Host − Write the host name, by default it will be localhost." }, { "code": null, "e": 10745, "s": 10675, "text": "Database Host − Write the host name, by default it will be localhost." }, { "code": null, "e": 10892, "s": 10745, "text": "Table Prefix − It is used to add prefix in the database tables which helps to run multiple sites on the same database. It takes the default value." }, { "code": null, "e": 11039, "s": 10892, "text": "Table Prefix − It is used to add prefix in the database tables which helps to run multiple sites on the same database. It takes the default value." }, { "code": null, "e": 11094, "s": 11039, "text": "After filling all information, click on Submit button." }, { "code": null, "e": 11217, "s": 11094, "text": "Step (5) − WordPress checks the database setting and gives you the confirmation screen as shown in the following snapshot." }, { "code": null, "e": 11242, "s": 11217, "text": "Click on Run the install" }, { "code": null, "e": 11287, "s": 11242, "text": "Step (6) − Enter administrative information." }, { "code": null, "e": 11322, "s": 11287, "text": "It contains the following fields −" }, { "code": null, "e": 11406, "s": 11322, "text": "Site Title − Enter the name of the site which you are going to create in WordPress." }, { "code": null, "e": 11490, "s": 11406, "text": "Site Title − Enter the name of the site which you are going to create in WordPress." }, { "code": null, "e": 11571, "s": 11490, "text": "Username − Enter the username as per your choice while logging in the WordPress." }, { "code": null, "e": 11652, "s": 11571, "text": "Username − Enter the username as per your choice while logging in the WordPress." }, { "code": null, "e": 11716, "s": 11652, "text": "Password twice − Enter password two times to protect your site." }, { "code": null, "e": 11780, "s": 11716, "text": "Password twice − Enter password two times to protect your site." }, { "code": null, "e": 11871, "s": 11780, "text": "Your E-mail − Enter your e-mail address which helps to recover the password or any update." }, { "code": null, "e": 11962, "s": 11871, "text": "Your E-mail − Enter your e-mail address which helps to recover the password or any update." }, { "code": null, "e": 12048, "s": 11962, "text": "Privacy − It allows the search engine to index this site after checking the checkbox." }, { "code": null, "e": 12134, "s": 12048, "text": "Privacy − It allows the search engine to index this site after checking the checkbox." }, { "code": null, "e": 12208, "s": 12134, "text": "After filling all the information, click on the Install WordPress button." }, { "code": null, "e": 12334, "s": 12208, "text": "Step (7) − After installation being successful, you will get a screen of the stating success as seen in the following screen." }, { "code": null, "e": 12401, "s": 12334, "text": "You can view your username and password detail added in WordPress." }, { "code": null, "e": 12425, "s": 12401, "text": "Click on Log In button." }, { "code": null, "e": 12535, "s": 12425, "text": "Step (8) − After clicking on login, you will get a WordPress Admin Panel as depicted in the following screen." }, { "code": null, "e": 12662, "s": 12535, "text": "Enter the username and password which you had mentioned during installation as shown in step 6 and click on the Log In button." }, { "code": null, "e": 13058, "s": 12662, "text": "The WordPress Dashboard is a first screen which will be seen when you log into the administration area of your blog which will display the overview of the website. It is a collection of gadgets that provide information and provide an overview of what's happening with your blog. You can customize your needs by using some quick links such as writing quick draft, replying to latest comment, etc." }, { "code": null, "e": 13190, "s": 13058, "text": "Dashboard can be categorized as shown in the following snapshot. Each of these categories are discussed in the following sections −" }, { "code": null, "e": 13391, "s": 13190, "text": "The WordPress Dashboard provides navigation menu that contains some menu options such as posts, media library, pages, comments, appearance options, plugins, users, tools and settings on the left side." }, { "code": null, "e": 13604, "s": 13391, "text": "The dashboard contains different types of widgets which can be shown or hidden on some screens. It contains check boxes to show or hide screen options and also allows us to customize sections on the admin screen." }, { "code": null, "e": 13986, "s": 13604, "text": "It includes the Customize Your Site button which allows customizing your WordPress theme. The center column provides some of the useful links such as creating a blog post, creating a page and view the front end of your website. Last column contains links to widgets, menus, settings related to comments and also a link to the First Steps With WordPress page in the WordPress codex." }, { "code": null, "e": 14185, "s": 13986, "text": "The Quick Draft is a mini post editor which allows writing, saving and publishing a post from admin dashboard. It includes the title for the draft, some notes about the draft and save it as a Draft." }, { "code": null, "e": 14353, "s": 14185, "text": "The WordPress News widget displays the latest news such as latest software version, updates, alerts, news regarding the software etc. from the official WordPress blog." }, { "code": null, "e": 14573, "s": 14353, "text": "The Activity widget includes latest comments on your blog, recent posts and recently published posts. It allows you to approve, disapprove, reply, edit, or delete a comment. It also allows you to move a comment to spam." }, { "code": null, "e": 14867, "s": 14573, "text": "This section gives an overview of your blog's posts, number of published posts and pages, and number of comments. When you click on these links, you will be taken to the respective screen. It displays the current version of running WordPress along with the currently running theme on the site." }, { "code": null, "e": 15094, "s": 14867, "text": "In this chapter, we will study about General Settings in WordPress. WordPress general setting is used to set the basic configuration settings for your site. In the setting administration screen, it is a default setting screen." }, { "code": null, "e": 15151, "s": 15094, "text": "Following are the steps to access the general settings −" }, { "code": null, "e": 15209, "s": 15151, "text": "Step 1 − Click on Settings → General option in WordPress." }, { "code": null, "e": 15292, "s": 15209, "text": "Step 2 − The General Setting page is displayed as shown in the following snapshot." }, { "code": null, "e": 15358, "s": 15292, "text": "Following are the details of the fields on general settings page." }, { "code": null, "e": 15428, "s": 15358, "text": "Site Title − It displays the name of the site in the template header." }, { "code": null, "e": 15498, "s": 15428, "text": "Site Title − It displays the name of the site in the template header." }, { "code": null, "e": 15551, "s": 15498, "text": "Tagline − Displays a short sentence about your site." }, { "code": null, "e": 15604, "s": 15551, "text": "Tagline − Displays a short sentence about your site." }, { "code": null, "e": 15718, "s": 15604, "text": "WordPress Address (URL) − It is the URL of WordPress directory where your all core application files are present." }, { "code": null, "e": 15832, "s": 15718, "text": "WordPress Address (URL) − It is the URL of WordPress directory where your all core application files are present." }, { "code": null, "e": 15923, "s": 15832, "text": "Site Address(URL) − Enter the site URL which you want your site to display on the browser." }, { "code": null, "e": 16014, "s": 15923, "text": "Site Address(URL) − Enter the site URL which you want your site to display on the browser." }, { "code": null, "e": 16110, "s": 16014, "text": "E-mail Address − Enter your e-mail address which helps to recover your password or any update." }, { "code": null, "e": 16206, "s": 16110, "text": "E-mail Address − Enter your e-mail address which helps to recover your password or any update." }, { "code": null, "e": 16294, "s": 16206, "text": "Membership − Anyone can register an account on your site after you check this checkbox." }, { "code": null, "e": 16382, "s": 16294, "text": "Membership − Anyone can register an account on your site after you check this checkbox." }, { "code": null, "e": 16472, "s": 16382, "text": "New User Default Role − The default role is set for the newly registered user or members." }, { "code": null, "e": 16562, "s": 16472, "text": "New User Default Role − The default role is set for the newly registered user or members." }, { "code": null, "e": 16622, "s": 16562, "text": "Timezone − Sets the time zone based on the particular city." }, { "code": null, "e": 16682, "s": 16622, "text": "Timezone − Sets the time zone based on the particular city." }, { "code": null, "e": 16753, "s": 16682, "text": "Date Format − Sets the date format as you need to display on the site." }, { "code": null, "e": 16824, "s": 16753, "text": "Date Format − Sets the date format as you need to display on the site." }, { "code": null, "e": 16895, "s": 16824, "text": "Time Format − Sets the time format as you need to display on the site." }, { "code": null, "e": 16966, "s": 16895, "text": "Time Format − Sets the time format as you need to display on the site." }, { "code": null, "e": 17085, "s": 16966, "text": "Week Starts On − Select the week day which you prefer to start for WordPress calendar. By default it is set as Monday." }, { "code": null, "e": 17204, "s": 17085, "text": "Week Starts On − Select the week day which you prefer to start for WordPress calendar. By default it is set as Monday." }, { "code": null, "e": 17267, "s": 17204, "text": "Site Language − Sets the language for the WordPress dashboard." }, { "code": null, "e": 17330, "s": 17267, "text": "Site Language − Sets the language for the WordPress dashboard." }, { "code": null, "e": 17473, "s": 17330, "text": "Step3 − After filling all the information about general settings, click on Save Changes button. It saves all your general setting information." }, { "code": null, "e": 17767, "s": 17473, "text": "The writing settings controls the writing experience and provides options for customizing WordPress site. These settings control the features in the adding and editing posts, Pages, and Post Types, as well as the optional functions like Remote Publishing, Post via e-mail, and Update Services." }, { "code": null, "e": 17824, "s": 17767, "text": "Following are the steps to access the writing settings −" }, { "code": null, "e": 17896, "s": 17824, "text": "Step (1) − To change writing settings, go to Settings → Writing option." }, { "code": null, "e": 17979, "s": 17896, "text": "Step (2) − The Writing Setting page is displayed as shown in the following screen." }, { "code": null, "e": 18032, "s": 17979, "text": "Following are the details of the fields on the page." }, { "code": null, "e": 18387, "s": 18032, "text": "Formatting − This field defines two sub options for better user experience.\n\nThe first option Convert emoticons like :-) and :-P to graphics on display will turn text-based emoticons into graphic-based emoticons.\nThe second option WordPress should correct invalidly nested XHTML automatically corrects the invalid XHTML placed within the posts or pages.\n" }, { "code": null, "e": 18463, "s": 18387, "text": "Formatting − This field defines two sub options for better user experience." }, { "code": null, "e": 18599, "s": 18463, "text": "The first option Convert emoticons like :-) and :-P to graphics on display will turn text-based emoticons into graphic-based emoticons." }, { "code": null, "e": 18735, "s": 18599, "text": "The first option Convert emoticons like :-) and :-P to graphics on display will turn text-based emoticons into graphic-based emoticons." }, { "code": null, "e": 18876, "s": 18735, "text": "The second option WordPress should correct invalidly nested XHTML automatically corrects the invalid XHTML placed within the posts or pages." }, { "code": null, "e": 19017, "s": 18876, "text": "The second option WordPress should correct invalidly nested XHTML automatically corrects the invalid XHTML placed within the posts or pages." }, { "code": null, "e": 19121, "s": 19017, "text": "Default Post Category − It is a category to be applied to a post and you can leave it as Uncategorized." }, { "code": null, "e": 19225, "s": 19121, "text": "Default Post Category − It is a category to be applied to a post and you can leave it as Uncategorized." }, { "code": null, "e": 19372, "s": 19225, "text": "Default Post Format − It is used by themes to select post format to be applied to a post or create different styles for different types of posts. " }, { "code": null, "e": 19519, "s": 19372, "text": "Default Post Format − It is used by themes to select post format to be applied to a post or create different styles for different types of posts. " }, { "code": null, "e": 19767, "s": 19519, "text": "Post via e-mail − This option uses e-mail address to create posts and publishes posts on your blog through e-mail. To use this, you'll need to set up a secret e-mail account with a POP3 access, and any mail received at this address will be posted." }, { "code": null, "e": 20015, "s": 19767, "text": "Post via e-mail − This option uses e-mail address to create posts and publishes posts on your blog through e-mail. To use this, you'll need to set up a secret e-mail account with a POP3 access, and any mail received at this address will be posted." }, { "code": null, "e": 20256, "s": 20015, "text": "Mail Server − It allows reading the e-mails that you send to WordPress and stores them for retrieval. For this, you need to have POP3 compatible mail server and it will have URI address such as mail.example.com, which you should enter here." }, { "code": null, "e": 20497, "s": 20256, "text": "Mail Server − It allows reading the e-mails that you send to WordPress and stores them for retrieval. For this, you need to have POP3 compatible mail server and it will have URI address such as mail.example.com, which you should enter here." }, { "code": null, "e": 20709, "s": 20497, "text": "Login Name − To create posts, WordPress will need its own e-mail account. The Login Name will use this e-mail address and should be kept as a secret as spammers will post links redirecting to their own websites." }, { "code": null, "e": 20921, "s": 20709, "text": "Login Name − To create posts, WordPress will need its own e-mail account. The Login Name will use this e-mail address and should be kept as a secret as spammers will post links redirecting to their own websites." }, { "code": null, "e": 20975, "s": 20921, "text": "Password − Set password for the above e-mail address." }, { "code": null, "e": 21029, "s": 20975, "text": "Password − Set password for the above e-mail address." }, { "code": null, "e": 21154, "s": 21029, "text": "Default Mail Category − It allows selecting custom category for all the posts that are published via Post by e-mail feature." }, { "code": null, "e": 21279, "s": 21154, "text": "Default Mail Category − It allows selecting custom category for all the posts that are published via Post by e-mail feature." }, { "code": null, "e": 21476, "s": 21279, "text": "Update Services − When you publish a new post, WordPress will automatically notify the site update services in the box. See the Update Services on the codex for the long list of possible services." }, { "code": null, "e": 21673, "s": 21476, "text": "Update Services − When you publish a new post, WordPress will automatically notify the site update services in the box. See the Update Services on the codex for the long list of possible services." }, { "code": null, "e": 21780, "s": 21673, "text": "Step (3) − After filling all the above information, click on Save Changes button to save your information." }, { "code": null, "e": 21983, "s": 21780, "text": "In this chapter, we will study about Reading Settings in WordPress. Reading Setting is used to set the content related to the front page. You can set the number of post to be displayed on the main page." }, { "code": null, "e": 22040, "s": 21983, "text": "Following are the steps to access the reading settings −" }, { "code": null, "e": 22100, "s": 22040, "text": "Step (1) − Click on Settings → Reading option in WordPress." }, { "code": null, "e": 22183, "s": 22100, "text": "Step(2) − The Reading Settings page is displayed as shown in the following screen." }, { "code": null, "e": 22244, "s": 22183, "text": "Following are the details of the fields on reading settings." }, { "code": null, "e": 22346, "s": 22244, "text": "Front page displays − This section is used to display the front page in any of the following format −" }, { "code": null, "e": 22448, "s": 22346, "text": "Front page displays − This section is used to display the front page in any of the following format −" }, { "code": null, "e": 22512, "s": 22448, "text": "Your latest posts − It displays latest posts on the front page." }, { "code": null, "e": 22576, "s": 22512, "text": "Your latest posts − It displays latest posts on the front page." }, { "code": null, "e": 22640, "s": 22576, "text": "A static page − It displays the static pages on the front page." }, { "code": null, "e": 22704, "s": 22640, "text": "A static page − It displays the static pages on the front page." }, { "code": null, "e": 22802, "s": 22704, "text": "Front Page − You can select the actual page you want to display on front page from the drop down." }, { "code": null, "e": 22900, "s": 22802, "text": "Front Page − You can select the actual page you want to display on front page from the drop down." }, { "code": null, "e": 22978, "s": 22900, "text": "Posts Page − You can select the page from the drop down which contains posts." }, { "code": null, "e": 23056, "s": 22978, "text": "Posts Page − You can select the page from the drop down which contains posts." }, { "code": null, "e": 23165, "s": 23056, "text": "Blog pages show at most − The number of posts to be displayed per page or site. By default, it is set as 10." }, { "code": null, "e": 23274, "s": 23165, "text": "Blog pages show at most − The number of posts to be displayed per page or site. By default, it is set as 10." }, { "code": null, "e": 23424, "s": 23274, "text": "Syndication feeds show the most recent − The user can view the number of posts when they download one of the site feeds. By default, it is set as 10." }, { "code": null, "e": 23574, "s": 23424, "text": "Syndication feeds show the most recent − The user can view the number of posts when they download one of the site feeds. By default, it is set as 10." }, { "code": null, "e": 23694, "s": 23574, "text": "For each article in a feed, show − This section is used to display the post by selecting any of the following formats −" }, { "code": null, "e": 23814, "s": 23694, "text": "For each article in a feed, show − This section is used to display the post by selecting any of the following formats −" }, { "code": null, "e": 23879, "s": 23814, "text": "Full Text − It displays the complete post. It is set as default." }, { "code": null, "e": 23944, "s": 23879, "text": "Full Text − It displays the complete post. It is set as default." }, { "code": null, "e": 23991, "s": 23944, "text": "Summary − It displays the summary of the post." }, { "code": null, "e": 24038, "s": 23991, "text": "Summary − It displays the summary of the post." }, { "code": null, "e": 24196, "s": 24038, "text": "Search Engine Visibility − After clicking on the checkbox, Discourage search engines from indexing this site, your site will be ignored by the search engine." }, { "code": null, "e": 24354, "s": 24196, "text": "Search Engine Visibility − After clicking on the checkbox, Discourage search engines from indexing this site, your site will be ignored by the search engine." }, { "code": null, "e": 24470, "s": 24354, "text": "Step(3) − After filling all the information, click on Save Changes button to save your Reading Setting information." }, { "code": null, "e": 24746, "s": 24470, "text": "In this chapter, we will study about Discussion settings in WordPress. WordPress discussion setting can be defined as the interaction between the blogger and the visitors. These settings are done by the admin to have a control over the posts/pages that come in through users." }, { "code": null, "e": 24805, "s": 24746, "text": "Following are the steps to access the Discussion setting −" }, { "code": null, "e": 24868, "s": 24805, "text": "Step (1) − Click on Settings → Discussion option in WordPress." }, { "code": null, "e": 24957, "s": 24868, "text": "Step (2) − The Discussion Settings page is displayed as shown in the following snapshot." }, { "code": null, "e": 25007, "s": 24957, "text": "Following fields are seen in Discussion settings." }, { "code": null, "e": 25149, "s": 25007, "text": "Default article settings − These settings are default to the new pages you create or new posts. This contains three more settings. They are −" }, { "code": null, "e": 25291, "s": 25149, "text": "Default article settings − These settings are default to the new pages you create or new posts. This contains three more settings. They are −" }, { "code": null, "e": 25447, "s": 25291, "text": "Attempt to notify any blogs linked to from the article − When you publish articles then it sends a notification (sends pings and trackback) to other blogs." }, { "code": null, "e": 25603, "s": 25447, "text": "Attempt to notify any blogs linked to from the article − When you publish articles then it sends a notification (sends pings and trackback) to other blogs." }, { "code": null, "e": 25706, "s": 25603, "text": "Allow link notifications from other blogs (pingbacks and trackbacks) − Accepts pings from other blogs." }, { "code": null, "e": 25809, "s": 25706, "text": "Allow link notifications from other blogs (pingbacks and trackbacks) − Accepts pings from other blogs." }, { "code": null, "e": 25943, "s": 25809, "text": "Allow people to post comments on new articles − You can allow or disallow other people to comment on your article using this setting." }, { "code": null, "e": 26077, "s": 25943, "text": "Allow people to post comments on new articles − You can allow or disallow other people to comment on your article using this setting." }, { "code": null, "e": 26147, "s": 26077, "text": "You can change the settings as per your will for individual articles." }, { "code": null, "e": 26213, "s": 26147, "text": "Other Comment Settings − This setting has the following options −" }, { "code": null, "e": 26279, "s": 26213, "text": "Other Comment Settings − This setting has the following options −" }, { "code": null, "e": 26418, "s": 26279, "text": "Comment author must fill out name and e-mail − When you check this box, it is mandatory for visitors to fill their name and email address." }, { "code": null, "e": 26557, "s": 26418, "text": "Comment author must fill out name and e-mail − When you check this box, it is mandatory for visitors to fill their name and email address." }, { "code": null, "e": 26739, "s": 26557, "text": "Users must be registered and logged in to comment − If you check this box, only those registered visitors can leave comments, if not checked anyone can leave any number of comments." }, { "code": null, "e": 26921, "s": 26739, "text": "Users must be registered and logged in to comment − If you check this box, only those registered visitors can leave comments, if not checked anyone can leave any number of comments." }, { "code": null, "e": 27074, "s": 26921, "text": "Automatically close comments on articles older than days − This option allows you to accept comments only for a particular time period as per your wish." }, { "code": null, "e": 27227, "s": 27074, "text": "Automatically close comments on articles older than days − This option allows you to accept comments only for a particular time period as per your wish." }, { "code": null, "e": 27350, "s": 27227, "text": "Enable threaded (nested) comments − When you check this option, visitors can reply or have a discussion and get responses." }, { "code": null, "e": 27473, "s": 27350, "text": "Enable threaded (nested) comments − When you check this option, visitors can reply or have a discussion and get responses." }, { "code": null, "e": 27679, "s": 27473, "text": "Break comments into pages with top level comments per page and the page displayed by default − If your pages are getting a lot of comments then you can split them into different pages by checking this box." }, { "code": null, "e": 27885, "s": 27679, "text": "Break comments into pages with top level comments per page and the page displayed by default − If your pages are getting a lot of comments then you can split them into different pages by checking this box." }, { "code": null, "e": 28033, "s": 27885, "text": "Comments should be displayed with the comments at the top of each page − You can arrange the comments in the form of ascending or descending order." }, { "code": null, "e": 28181, "s": 28033, "text": "Comments should be displayed with the comments at the top of each page − You can arrange the comments in the form of ascending or descending order." }, { "code": null, "e": 28505, "s": 28181, "text": "Email me whenever − This setting contains two options, namely −\n\nAnyone posts a comment − When you check into this box, the author gets an e-mail for every single comment that is posted.\nA comment is held for moderation − This is used in case you do not want your comment to be updated before it's moderated by the admin.\n\n" }, { "code": null, "e": 28569, "s": 28505, "text": "Email me whenever − This setting contains two options, namely −" }, { "code": null, "e": 28691, "s": 28569, "text": "Anyone posts a comment − When you check into this box, the author gets an e-mail for every single comment that is posted." }, { "code": null, "e": 28813, "s": 28691, "text": "Anyone posts a comment − When you check into this box, the author gets an e-mail for every single comment that is posted." }, { "code": null, "e": 28948, "s": 28813, "text": "A comment is held for moderation − This is used in case you do not want your comment to be updated before it's moderated by the admin." }, { "code": null, "e": 29083, "s": 28948, "text": "A comment is held for moderation − This is used in case you do not want your comment to be updated before it's moderated by the admin." }, { "code": null, "e": 29622, "s": 29083, "text": "Before a comment appears − This setting allows how your posts are controlled. There are two more settings as followed −\n\nComment must be manually approved − If you check this box then only the approved comments by the admin can be displayed on the posts or pages.\nComment author must have a previously approved comment − This can be checked when you want to approve a comment of an author whose has commented and his e-mail address matches the e-mail address of the previous posted comment. Otherwise the comment is held for moderation.\n\n" }, { "code": null, "e": 29742, "s": 29622, "text": "Before a comment appears − This setting allows how your posts are controlled. There are two more settings as followed −" }, { "code": null, "e": 29885, "s": 29742, "text": "Comment must be manually approved − If you check this box then only the approved comments by the admin can be displayed on the posts or pages." }, { "code": null, "e": 30028, "s": 29885, "text": "Comment must be manually approved − If you check this box then only the approved comments by the admin can be displayed on the posts or pages." }, { "code": null, "e": 30301, "s": 30028, "text": "Comment author must have a previously approved comment − This can be checked when you want to approve a comment of an author whose has commented and his e-mail address matches the e-mail address of the previous posted comment. Otherwise the comment is held for moderation." }, { "code": null, "e": 30574, "s": 30301, "text": "Comment author must have a previously approved comment − This can be checked when you want to approve a comment of an author whose has commented and his e-mail address matches the e-mail address of the previous posted comment. Otherwise the comment is held for moderation." }, { "code": null, "e": 30668, "s": 30574, "text": "Comment Moderation − Contain only a specific number of links that are allowed into a comment." }, { "code": null, "e": 30762, "s": 30668, "text": "Comment Moderation − Contain only a specific number of links that are allowed into a comment." }, { "code": null, "e": 30934, "s": 30762, "text": "Comment Blacklist − You can input your own spam words which you do not want your visitors to enter into the comments, URL, e-mail etc.; later it would filter the comments." }, { "code": null, "e": 31106, "s": 30934, "text": "Comment Blacklist − You can input your own spam words which you do not want your visitors to enter into the comments, URL, e-mail etc.; later it would filter the comments." }, { "code": null, "e": 31780, "s": 31106, "text": "Avatars − Avatar is a small image that displays at the top-right-hand corner of the dashboard screen beside your name. It is like your profile picture. Here you have a few more options where you can set your avatar for WordPress site.\n\nAvatar Display − It displays your avatar besides your name when it is checked.\nMaximum rating − You have a four other options of avatars you can use. They are G, PG, R and X. This is the age section where you select according to which type of audience you want to display your posts.\nDefault Avatar − In this option, there are few more types of avatars with images; you can keep these avatars according to your visitors e-mail address.\n\n" }, { "code": null, "e": 32015, "s": 31780, "text": "Avatars − Avatar is a small image that displays at the top-right-hand corner of the dashboard screen beside your name. It is like your profile picture. Here you have a few more options where you can set your avatar for WordPress site." }, { "code": null, "e": 32094, "s": 32015, "text": "Avatar Display − It displays your avatar besides your name when it is checked." }, { "code": null, "e": 32173, "s": 32094, "text": "Avatar Display − It displays your avatar besides your name when it is checked." }, { "code": null, "e": 32378, "s": 32173, "text": "Maximum rating − You have a four other options of avatars you can use. They are G, PG, R and X. This is the age section where you select according to which type of audience you want to display your posts." }, { "code": null, "e": 32583, "s": 32378, "text": "Maximum rating − You have a four other options of avatars you can use. They are G, PG, R and X. This is the age section where you select according to which type of audience you want to display your posts." }, { "code": null, "e": 32735, "s": 32583, "text": "Default Avatar − In this option, there are few more types of avatars with images; you can keep these avatars according to your visitors e-mail address." }, { "code": null, "e": 32887, "s": 32735, "text": "Default Avatar − In this option, there are few more types of avatars with images; you can keep these avatars according to your visitors e-mail address." }, { "code": null, "e": 32948, "s": 32887, "text": "Step (3) − Click on Save Changes button to save the changes." }, { "code": null, "e": 33110, "s": 32948, "text": "In this chapter, we will study about Media Settings in WordPress. It is used to set the height and width of the images which you're going to use on your website." }, { "code": null, "e": 33168, "s": 33110, "text": "Step (1) − Click on Settings → Media option in WordPress." }, { "code": null, "e": 33253, "s": 33168, "text": "Step (2) − The Media Settings page is displayed as seen in the following screenshot." }, { "code": null, "e": 33313, "s": 33253, "text": "Following are the details of the fields on Media settings −" }, { "code": null, "e": 33361, "s": 33313, "text": "Thumbnail size − Set the size of the thumbnail." }, { "code": null, "e": 33409, "s": 33361, "text": "Thumbnail size − Set the size of the thumbnail." }, { "code": null, "e": 33471, "s": 33409, "text": "Medium size − Set the height and width of medium size images." }, { "code": null, "e": 33533, "s": 33471, "text": "Medium size − Set the height and width of medium size images." }, { "code": null, "e": 33585, "s": 33533, "text": "Large size − Set width and height of larger images." }, { "code": null, "e": 33637, "s": 33585, "text": "Large size − Set width and height of larger images." }, { "code": null, "e": 33755, "s": 33637, "text": "Uploading files − After checking this checkbox, the uploaded image will be arranged into year and month based folder." }, { "code": null, "e": 33873, "s": 33755, "text": "Uploading files − After checking this checkbox, the uploaded image will be arranged into year and month based folder." }, { "code": null, "e": 33994, "s": 33873, "text": "Step (3) − After setting the dimension in pixels, click on Save Changes button. It saves your media setting information." }, { "code": null, "e": 34308, "s": 33994, "text": "In this chapter, we will learn about Permalink settings in WordPress. Permalink is a permanent link to a particular blog post or category. It allows setting the default permalink structure. These settings are used to add permalinks to your posts in WordPress. Following are the steps to access permalink settings." }, { "code": null, "e": 34388, "s": 34308, "text": "Step (1) − Click on Settings → Permalinks option from the left navigation menu." }, { "code": null, "e": 34471, "s": 34388, "text": "Step (2) − When you click on Permalinks, the following page appears on the screen." }, { "code": null, "e": 34510, "s": 34471, "text": "Here are a few settings you can make −" }, { "code": null, "e": 35078, "s": 34510, "text": "Common settings −\nCheck any of the radio buttons to choose your permalink structure for your blogs\n\nDefault − It sets the default URL structure in Wordpress.\nDay and name − It sets URL structure according to the date and name in your posts.\nMonth and name − It sets the URL structure according to the month and name in your post.\nNumeric − It sets numbers in the URL structure in your post.\nPost name − It sets post name in the URL structure in your post.\nCustom Structure − It sets the URL structure of your choice by writing the desired name in the given text box.\n" }, { "code": null, "e": 35096, "s": 35078, "text": "Common settings −" }, { "code": null, "e": 35177, "s": 35096, "text": "Check any of the radio buttons to choose your permalink structure for your blogs" }, { "code": null, "e": 35235, "s": 35177, "text": "Default − It sets the default URL structure in Wordpress." }, { "code": null, "e": 35293, "s": 35235, "text": "Default − It sets the default URL structure in Wordpress." }, { "code": null, "e": 35376, "s": 35293, "text": "Day and name − It sets URL structure according to the date and name in your posts." }, { "code": null, "e": 35459, "s": 35376, "text": "Day and name − It sets URL structure according to the date and name in your posts." }, { "code": null, "e": 35548, "s": 35459, "text": "Month and name − It sets the URL structure according to the month and name in your post." }, { "code": null, "e": 35637, "s": 35548, "text": "Month and name − It sets the URL structure according to the month and name in your post." }, { "code": null, "e": 35698, "s": 35637, "text": "Numeric − It sets numbers in the URL structure in your post." }, { "code": null, "e": 35759, "s": 35698, "text": "Numeric − It sets numbers in the URL structure in your post." }, { "code": null, "e": 35824, "s": 35759, "text": "Post name − It sets post name in the URL structure in your post." }, { "code": null, "e": 35889, "s": 35824, "text": "Post name − It sets post name in the URL structure in your post." }, { "code": null, "e": 36000, "s": 35889, "text": "Custom Structure − It sets the URL structure of your choice by writing the desired name in the given text box." }, { "code": null, "e": 36111, "s": 36000, "text": "Custom Structure − It sets the URL structure of your choice by writing the desired name in the given text box." }, { "code": null, "e": 36389, "s": 36111, "text": "Optional\nThese are optional. You can add custom structure for main category or tag URL. If your text box is empty then default settings is used. Here you have two options.\n\nCategory Base − Add custom prefix for your category URL.\nTag Base − Add custom prefix to your Tags URL.\n" }, { "code": null, "e": 36398, "s": 36389, "text": "Optional" }, { "code": null, "e": 36561, "s": 36398, "text": "These are optional. You can add custom structure for main category or tag URL. If your text box is empty then default settings is used. Here you have two options." }, { "code": null, "e": 36618, "s": 36561, "text": "Category Base − Add custom prefix for your category URL." }, { "code": null, "e": 36675, "s": 36618, "text": "Category Base − Add custom prefix for your category URL." }, { "code": null, "e": 36722, "s": 36675, "text": "Tag Base − Add custom prefix to your Tags URL." }, { "code": null, "e": 36769, "s": 36722, "text": "Tag Base − Add custom prefix to your Tags URL." }, { "code": null, "e": 36873, "s": 36769, "text": "Step (3) − Once you are done with changes, click on Save Changes button to save the permalink settings." }, { "code": null, "e": 37260, "s": 36873, "text": "In this chapter, we will study how to use plugins in your WordPress site. Plugin allows to easily modify, customize or enhance WordPress blog or post. The WordPress Plugin is a software that can be uploaded to expand the functionality of the site. They add services or features to WordPress blog. Plugins are used to make your work easier. Following are the simple steps to add plugins." }, { "code": null, "e": 37354, "s": 37260, "text": "Step (1) − On the left side bar, Click on Plugins → Installed Plugins as shown in the screen." }, { "code": null, "e": 37393, "s": 37354, "text": "Step (2) − The following page appears." }, { "code": null, "e": 37454, "s": 37393, "text": "In this section, you can view the already installed plugins." }, { "code": null, "e": 37533, "s": 37454, "text": "Step (3) − Click on → Plugins → Add New menu as shown in the following screen." }, { "code": null, "e": 37711, "s": 37533, "text": "Step (4) − A list of plugins appears that are used in WordPress. Here you can directly install plugins from the available list or you can upload it by clicking on Upload Plugin." }, { "code": null, "e": 37774, "s": 37711, "text": "When you click on Upload Plugin you'll get the following page." }, { "code": null, "e": 38057, "s": 37774, "text": "Click on Browse, it goes back to the page where you can select plugins from WordPress site. And if you click on Choose File, you can add files from your system. Otherwise, you can directly choose the plugin that you need and click on Install now as seen in the following screenshot." }, { "code": null, "e": 38245, "s": 38057, "text": "When you click on Install Now, the package starts to download and gets installed. Then, click on Activate plugin to active that plugin to use in WordPress as seen in the following screen." }, { "code": null, "e": 38376, "s": 38245, "text": "After clicking on Activate Plugin you'll get a message as Plugin activated and you can also find the installed plugin in the list." }, { "code": null, "e": 38489, "s": 38376, "text": "Below the plugin activated message, you can view few options such as All, Active, Inactive and Update available." }, { "code": null, "e": 38587, "s": 38489, "text": "When you click on Active the following page appears. Here you can view all the activated plugins." }, { "code": null, "e": 38738, "s": 38587, "text": "When we click on Inactive, the plugins which are available but are not activated gets displayed. You can activate this plugin by clicking on Activate." }, { "code": null, "e": 38875, "s": 38738, "text": "When you click on Update available, you'll get a list of plugins that must be updated. Click on Update and you get a message as Updated." }, { "code": null, "e": 39035, "s": 38875, "text": "Click on Bulk Actions and select any of the options. Click on Apply button to update, delete, activate or deactivate each of the plugins by checking the boxes." }, { "code": null, "e": 39190, "s": 39035, "text": "In Search Installed Plugins you can just type your plugin name in the text box that is already installed and click on the Search Installed Plugins button." }, { "code": null, "e": 39299, "s": 39190, "text": "When you click on the Search installed Plugin button you get the following page with your respective plugin." }, { "code": null, "e": 39355, "s": 39299, "text": "Step (5) − Click on Plugins → Editor from the side bar." }, { "code": null, "e": 39401, "s": 39355, "text": "Step (6) − The following page gets displayed." }, { "code": null, "e": 39468, "s": 39401, "text": "This page lets you edit your plugins. A few options are explained." }, { "code": null, "e": 39553, "s": 39468, "text": "Select plugin to edit − Allows you to select a plugin from the dropdown and edit it." }, { "code": null, "e": 39638, "s": 39553, "text": "Select plugin to edit − Allows you to select a plugin from the dropdown and edit it." }, { "code": null, "e": 39723, "s": 39638, "text": "Documentation − Allows you to select the tools from the dropdown to edit the plugin." }, { "code": null, "e": 39808, "s": 39723, "text": "Documentation − Allows you to select the tools from the dropdown to edit the plugin." }, { "code": null, "e": 39886, "s": 39808, "text": "Plugin files − Allows you to select files from the list and edit accordingly." }, { "code": null, "e": 39964, "s": 39886, "text": "Plugin files − Allows you to select files from the list and edit accordingly." }, { "code": null, "e": 40027, "s": 39964, "text": "Finally, after editing the plugin files, click on Update file." }, { "code": null, "e": 40279, "s": 40027, "text": "In this chapter, we will study about how to Add Categories in WordPress. Category is used to indicate sections of your site and group related posts. It sorts the group content into different sections. It is a very convenient way to organize the posts." }, { "code": null, "e": 40341, "s": 40279, "text": "To access the Category section, follows the mentioned steps −" }, { "code": null, "e": 40401, "s": 40341, "text": "Step (1) − Click on Posts → Categories option in WordPress." }, { "code": null, "e": 40483, "s": 40401, "text": "Step (2) − The Categories page is displayed as shown in the following screenshot." }, { "code": null, "e": 40538, "s": 40483, "text": "Following are the details of the fields on Categories." }, { "code": null, "e": 40582, "s": 40538, "text": "Name − Enter the unique name of categories." }, { "code": null, "e": 40626, "s": 40582, "text": "Name − Enter the unique name of categories." }, { "code": null, "e": 40703, "s": 40626, "text": "Slug − A word chosen to describe your post. It is specified in the tags URL." }, { "code": null, "e": 40780, "s": 40703, "text": "Slug − A word chosen to describe your post. It is specified in the tags URL." }, { "code": null, "e": 40913, "s": 40780, "text": "Parent − By selecting the parent category from dropdown, you can set the particular category as sub-category or can keep it as None." }, { "code": null, "e": 41046, "s": 40913, "text": "Parent − By selecting the parent category from dropdown, you can set the particular category as sub-category or can keep it as None." }, { "code": null, "e": 41116, "s": 41046, "text": "Description − Add brief description of your category. It is optional." }, { "code": null, "e": 41186, "s": 41116, "text": "Description − Add brief description of your category. It is optional." }, { "code": null, "e": 41283, "s": 41186, "text": "Step (3) − After filling all the information about Categories, click on Add New Category button." }, { "code": null, "e": 41438, "s": 41283, "text": "Step (4) − After clicking on Add New Category, the new created category will get displayed on the right side of the page as shown in the following screen." }, { "code": null, "e": 41519, "s": 41438, "text": "In this chapter, we will study the simple steps to Edit Categories in WordPress." }, { "code": null, "e": 41583, "s": 41519, "text": "Following are the simple steps to edit categories in WordPress." }, { "code": null, "e": 41636, "s": 41583, "text": "Step (1) − Click on Posts → Categories in WordPress." }, { "code": null, "e": 41902, "s": 41636, "text": "Step (2) − You can view Category1 (Category1 was created in the chapter WordPress - Add Category). When the cursor hovers on the Categories, then a few options get displayed below the Category name. There are two ways to edit the categories i.e. Edit and Quick Edit" }, { "code": null, "e": 41989, "s": 41902, "text": "Edit − Click on Edit option in Categories section as seen in the following screenshot." }, { "code": null, "e": 42092, "s": 41989, "text": "You can edit any of the required field, and then click Update button as shown in the following screen." }, { "code": null, "e": 42160, "s": 42092, "text": "Category fields are same from the chapter WordPress - Add Category." }, { "code": null, "e": 42256, "s": 42160, "text": "Quick Edit − Click on Quick Edit option in Categories section as shown in the following screen." }, { "code": null, "e": 42397, "s": 42256, "text": "Here, you can only edit the Name and Slug of the category as seen in the following screen and then finally click on Update Category button." }, { "code": null, "e": 42473, "s": 42397, "text": "In this chapter, we will study about how to Delete Categories in WordPress." }, { "code": null, "e": 42539, "s": 42473, "text": "Following are the simple steps to delete categories in WordPress." }, { "code": null, "e": 42592, "s": 42539, "text": "Step (1) − Click on Posts → Categories in WordPress." }, { "code": null, "e": 42845, "s": 42592, "text": "Step (2) − You can delete Category1 (Category1 was created in the chapter Wordpress - Add Category). When the cursor hovers on the Categories, a few options get displayed below the Category name. Click on Delete button as shown in the following screen." }, { "code": null, "e": 42994, "s": 42845, "text": "When you click on delete, you will get a pop message asking for confirmation to delete the particular category as shown in the following screenshot." }, { "code": null, "e": 43058, "s": 42994, "text": "You can click on OK button and delete the category permanently." }, { "code": null, "e": 43296, "s": 43058, "text": "In this chapter, we will study about how to Arrange Categories in WordPress. You can't arrange categories directly in WordPress. Hence, you will need to install Category Order plugin to arrange the created categories in a particular way." }, { "code": null, "e": 43495, "s": 43296, "text": "Step (1) − Click on Posts → Category Order in WordPress. The Category Order menu displays after adding the Category Order plugin. You can study how to install plugins in the chapter Install Plugins." }, { "code": null, "e": 43596, "s": 43495, "text": "Step (2) − In the following screen, you can see that the create categories section are not in order." }, { "code": null, "e": 43764, "s": 43596, "text": "Step (3) − Now, you can rearrange your categories by just dragging the categories as per your choice. Click on Order categories button to save the ordered categories." }, { "code": null, "e": 43947, "s": 43764, "text": "In this chapter, we will study how to Add Posts in WordPress. Posts are also known as articles and sometimes referred as blogs or blog posts. These are used to popularize your blogs." }, { "code": null, "e": 44005, "s": 43947, "text": "Following are the simple steps to Add Posts in WordPress." }, { "code": null, "e": 44055, "s": 44005, "text": "Step (1) − Click on Posts → Add New in WordPress." }, { "code": null, "e": 44305, "s": 44055, "text": "Step (2) − You will get the editor page of the Post as shown in the following screen. You can use the WordPress WYSIWYG editor to add the actual content of your post. We will study in detail about WYSIWYG editor in the chapter WordPress - Add Pages." }, { "code": null, "e": 44372, "s": 44305, "text": "Following are the fields on the editor page of the Add Posts Page." }, { "code": null, "e": 44427, "s": 44372, "text": "Post Title − Enter the title of the post, i.e., Post1." }, { "code": null, "e": 44482, "s": 44427, "text": "Post Title − Enter the title of the post, i.e., Post1." }, { "code": null, "e": 44529, "s": 44482, "text": "Post Content − Enter the content of your post." }, { "code": null, "e": 44576, "s": 44529, "text": "Post Content − Enter the content of your post." }, { "code": null, "e": 44644, "s": 44576, "text": "Step (3) − Click on Publish button to publish your respective post." }, { "code": null, "e": 44712, "s": 44644, "text": "Following are the few other options present in the Publish section." }, { "code": null, "e": 44755, "s": 44712, "text": "Save Draft − It saves the post as a draft." }, { "code": null, "e": 44798, "s": 44755, "text": "Save Draft − It saves the post as a draft." }, { "code": null, "e": 44853, "s": 44798, "text": "Preview − You can preview your post before publishing." }, { "code": null, "e": 44908, "s": 44853, "text": "Preview − You can preview your post before publishing." }, { "code": null, "e": 44942, "s": 44908, "text": "Move to Trash − Deletes the post." }, { "code": null, "e": 44976, "s": 44942, "text": "Move to Trash − Deletes the post." }, { "code": null, "e": 45059, "s": 44976, "text": "Status − Change the status of your post to Published, Pending, or Reviewer Draft. " }, { "code": null, "e": 45142, "s": 45059, "text": "Status − Change the status of your post to Published, Pending, or Reviewer Draft. " }, { "code": null, "e": 45231, "s": 45142, "text": "Visibility − Change the visibility of the post to Public, Private or Password protected." }, { "code": null, "e": 45320, "s": 45231, "text": "Visibility − Change the visibility of the post to Public, Private or Password protected." }, { "code": null, "e": 45374, "s": 45320, "text": "Published − Change the publishded post date and time." }, { "code": null, "e": 45428, "s": 45374, "text": "Published − Change the publishded post date and time." }, { "code": null, "e": 45491, "s": 45428, "text": "In this chapter, we will study how to Edit Posts on WordPress." }, { "code": null, "e": 45550, "s": 45491, "text": "Following are the simple steps to Edit Posts in WordPress." }, { "code": null, "e": 45602, "s": 45550, "text": "Step (1) − Click on Posts → All Posts in WordPress." }, { "code": null, "e": 45836, "s": 45602, "text": "Step (2) − You can view Post1 (Post1 was created in the chapter WordPress - Add Posts). When the cursor hovers on the Post, few options get displayed below the Post name. There are two ways to edit the Post i.e. Edit and Quick Edit." }, { "code": null, "e": 45907, "s": 45836, "text": "Edit − Click on Edit option in Post1 as shown in the following screen." }, { "code": null, "e": 46048, "s": 45907, "text": "You can edit or change the content or title of the post as per your needs, and then click on Update button as shown in the following screen." }, { "code": null, "e": 46135, "s": 46048, "text": "Quick Edit − Click on Quick Edit option in Post1 as shown in the following screenshot." }, { "code": null, "e": 46332, "s": 46135, "text": "Here you can edit the Title, Slug and date of the posts and can also select the categories for your post as shown in the following screenshot and then click on Update button to confirm post edits." }, { "code": null, "e": 46397, "s": 46332, "text": "In this chapter, we will study how to Delete Posts in WordPress." }, { "code": null, "e": 46451, "s": 46397, "text": "Following are the steps to Delete Posts in WordPress." }, { "code": null, "e": 46502, "s": 46451, "text": "Step (1) − Click on Posts → All Post in WordPress." }, { "code": null, "e": 46716, "s": 46502, "text": "Step (2) − You can delete Post1 (Post1 was created in the chapter Wordpress - Add Posts). When the cursor hovers on the Post, then a few options get displayed below Post1. Click on Trash option to delete the post." }, { "code": null, "e": 46797, "s": 46716, "text": "Step (3) − You can view your post lists to confirm if the above post is deleted." }, { "code": null, "e": 47079, "s": 46797, "text": "In this chapter, we will study how to Preview Posts in WordPress. Preview Post is to view the post before it is published to the user. It is safer to preview your post and verify how your post looks on the website. You can edit or change the post as per your need after previewing." }, { "code": null, "e": 47141, "s": 47079, "text": "Following are the simple steps to Preview Posts in WordPress." }, { "code": null, "e": 47193, "s": 47141, "text": "Step (1) − Click on Posts → All Posts in wordPress." }, { "code": null, "e": 47434, "s": 47193, "text": "Step (2) − You can view Post1 (Post1 was created in the chapter Wordpress - Add Posts). When the cursor hovers on the Post, then a few options get displayed below the Post name. Click on the View option as shown in the following screenshot." }, { "code": null, "e": 47571, "s": 47434, "text": "Or else you can view your post directly while editing or adding post by clicking on the Preview button as shown in the following screen." }, { "code": null, "e": 47641, "s": 47571, "text": "Step (3) − You can view your post, when you click on View or Preview." }, { "code": null, "e": 47872, "s": 47641, "text": "In this chapter, we will study how to Publish Posts in WordPress. Publish is used to make the post available to all the users wherein every user can view that particular post. Publishing a new post in WordPress is an easy process." }, { "code": null, "e": 47927, "s": 47872, "text": "Following are the steps to Publish Posts in WordPress." }, { "code": null, "e": 47977, "s": 47927, "text": "Step (1) − Click on Posts → Add New in WordPress." }, { "code": null, "e": 48148, "s": 47977, "text": "Step (2) − You will get the editor page of the Post as shown in the following screenshot. You can use the WordPress WYSIWYG editor to add the actual content of your post." }, { "code": null, "e": 48216, "s": 48148, "text": "Step (3) − Click on Publish button to publish your respective post." }, { "code": null, "e": 48293, "s": 48216, "text": "After clicking on publish, your posts get published for the user to view it." }, { "code": null, "e": 48573, "s": 48293, "text": "In this chapter, we will learn about Media Library in WordPress. Media Library consists of the images, audios, videos and files that you can upload and add to the content when writing a Post or Page. Here you can view, add, edit or delete any media related objects if not needed." }, { "code": null, "e": 48632, "s": 48573, "text": "Following are the steps to understand about Media Library." }, { "code": null, "e": 48682, "s": 48632, "text": "Step (1) − Click on Media → Library in WordPress." }, { "code": null, "e": 48774, "s": 48682, "text": "Step (2) − You can view media files like images, audios, videos. Click on Add Media button." }, { "code": null, "e": 48879, "s": 48774, "text": "Step (3) − The Upload New Media page gets displayed. You can learn how to Add Media in the next chapter." }, { "code": null, "e": 48947, "s": 48879, "text": "Step (4) − You can view a bar as shown in the following screenshot." }, { "code": null, "e": 49007, "s": 48947, "text": "The various tabs that appear have the following functions −" }, { "code": null, "e": 49064, "s": 49007, "text": "List View − Displays the images and videos in list form." }, { "code": null, "e": 49149, "s": 49064, "text": "Grid View − Displays all images in the grid format as shown in the following screen." }, { "code": null, "e": 49211, "s": 49149, "text": "Filter the images and videos − Filters the images and videos." }, { "code": null, "e": 49295, "s": 49211, "text": "Search Box − Helps to search a particular image by inserting the name into the box." }, { "code": null, "e": 49448, "s": 49295, "text": "In this chapter, we will study how to Add Media files in WordPress. WordPress allows you to add, all kind of media files like videos, audios and images." }, { "code": null, "e": 49486, "s": 49448, "text": "Following are the steps to Add Media." }, { "code": null, "e": 49536, "s": 49486, "text": "Step (1) − Click on Media → Add New in WordPress." }, { "code": null, "e": 49660, "s": 49536, "text": "Step (2) − Then, click on Select Files option to select the files from your local storage as shown in the following figure." }, { "code": null, "e": 49784, "s": 49660, "text": "Step (3) − Add Media files such as images and audios by selecting them and click open as shown in the following screenshot." }, { "code": null, "e": 49876, "s": 49784, "text": "Step (4) − You can view the list of media files added as shown in the following screenshot." }, { "code": null, "e": 50041, "s": 49876, "text": "In this chapter, we will study how to Insert Media in WordPress. Media files can be inserted to your Pages or Posts from libraries, from local storage or from URLs." }, { "code": null, "e": 50095, "s": 50041, "text": "Following are the steps to Insert Media in WordPress." }, { "code": null, "e": 50145, "s": 50095, "text": "Step (1) − Click on Posts → Add New in WordPress." }, { "code": null, "e": 50176, "s": 50145, "text": "Step (2) − Click on Add Media." }, { "code": null, "e": 50277, "s": 50176, "text": "Step (3) − You can select the files from the Media Library tab as shown in the following screenshot." }, { "code": null, "e": 50598, "s": 50277, "text": "Information about the selected media file will be displayed on the right side of the screen under the Attachment Details. Click on Insert Post button, the image will be inserted into the post. In Attachment Details section, you will find information about the images such as URL, Title, Caption, Alt Text and Description" }, { "code": null, "e": 50720, "s": 50598, "text": "You can also insert an image directly from your system by clicking on Upload Files tab. Click on Insert into Post button." }, { "code": null, "e": 50871, "s": 50720, "text": "In this chapter, we will study how to Edit Media in wordPress. You can manage all the information about your media that is saved in the Media Library." }, { "code": null, "e": 50923, "s": 50871, "text": "Following are the steps to Edit Media in WordPress." }, { "code": null, "e": 51017, "s": 50923, "text": "Step (1) − Click on Media → Library and click on the name of the media item or the edit link." }, { "code": null, "e": 51095, "s": 51017, "text": "Step (2) − You will view a list of media files. Select any one image to edit." }, { "code": null, "e": 51175, "s": 51095, "text": "Step (3) − You can view the edit media page with few options on the right side." }, { "code": null, "e": 51223, "s": 51175, "text": "URL − You can read only a link from media file." }, { "code": null, "e": 51271, "s": 51223, "text": "URL − You can read only a link from media file." }, { "code": null, "e": 51421, "s": 51271, "text": "Title − This displays the name of the media. Title is often shown in galleries and attachment pages, if themes or plugins are designed to display it." }, { "code": null, "e": 51571, "s": 51421, "text": "Title − This displays the name of the media. Title is often shown in galleries and attachment pages, if themes or plugins are designed to display it." }, { "code": null, "e": 51683, "s": 51571, "text": "Permalink − Permalink is the URL of the media attachment page. This is also a link to view the attachment page." }, { "code": null, "e": 51795, "s": 51683, "text": "Permalink − Permalink is the URL of the media attachment page. This is also a link to view the attachment page." }, { "code": null, "e": 51964, "s": 51795, "text": "Edit image button − This allows you to edit the image position, such as rotate counter-clockwise, rotate clockwise, scale, crop, flip vertically, and flip horizontally." }, { "code": null, "e": 52133, "s": 51964, "text": "Edit image button − This allows you to edit the image position, such as rotate counter-clockwise, rotate clockwise, scale, crop, flip vertically, and flip horizontally." }, { "code": null, "e": 52177, "s": 52133, "text": "Caption − A brief explanation of the media." }, { "code": null, "e": 52221, "s": 52177, "text": "Caption − A brief explanation of the media." }, { "code": null, "e": 52322, "s": 52221, "text": "Alternate Text − The alt text for the image, which is used to describe media. Used for availability." }, { "code": null, "e": 52423, "s": 52322, "text": "Alternate Text − The alt text for the image, which is used to describe media. Used for availability." }, { "code": null, "e": 52472, "s": 52423, "text": "Description − An explanation of your media file." }, { "code": null, "e": 52521, "s": 52472, "text": "Description − An explanation of your media file." }, { "code": null, "e": 52578, "s": 52521, "text": "Delete Permanently − Delete your media file permanently." }, { "code": null, "e": 52635, "s": 52578, "text": "Delete Permanently − Delete your media file permanently." }, { "code": null, "e": 52754, "s": 52635, "text": "Step (4) − Once you complete editing the required fields, click on Update button to save the changes made to an image." }, { "code": null, "e": 52952, "s": 52754, "text": "In this chapter, we will study how to Add Pages into the WordPress. Adding pages is similar to adding posts in WordPress. Pages are static content and often do not change its displayed information." }, { "code": null, "e": 53010, "s": 52952, "text": "Following are the simple steps to add pages in WordPress." }, { "code": null, "e": 53084, "s": 53010, "text": "Step (1) − Click on Pages → Add New as shown in the following screenshot." }, { "code": null, "e": 53307, "s": 53084, "text": "Step (2) − You will get the editor page as seen in the following screenshot. The editor page has two tabs, Visual and Text. You can insert text in either of these. Here, we'll study about inserting text into Visual format." }, { "code": null, "e": 53383, "s": 53307, "text": "Following are the details of the fields on editor page of the Add New Page." }, { "code": null, "e": 53467, "s": 53383, "text": "It is used to write the title of the article, which is later displayed on the page." }, { "code": null, "e": 53573, "s": 53467, "text": "Permalink shows the potential URL for the page below the title. The URL generates as per the given title." }, { "code": null, "e": 53692, "s": 53573, "text": "It is a WYSIWYG Editor, which is similar to a word processor interface where you can edit the contents of the article." }, { "code": null, "e": 53746, "s": 53692, "text": "Following are the options present of WYSIWYG editor −" }, { "code": null, "e": 53784, "s": 53746, "text": "Bold Button − Used to bold your font." }, { "code": null, "e": 53822, "s": 53784, "text": "Bold Button − Used to bold your font." }, { "code": null, "e": 53859, "s": 53822, "text": "Italic − Used to italicize the font." }, { "code": null, "e": 53896, "s": 53859, "text": "Italic − Used to italicize the font." }, { "code": null, "e": 53939, "s": 53896, "text": "Word Strike − Strikes through the content." }, { "code": null, "e": 53982, "s": 53939, "text": "Word Strike − Strikes through the content." }, { "code": null, "e": 54021, "s": 53982, "text": "Bullet List − Adds bullets to content." }, { "code": null, "e": 54060, "s": 54021, "text": "Bullet List − Adds bullets to content." }, { "code": null, "e": 54115, "s": 54060, "text": "Number List − Adds numbers to the list of the content." }, { "code": null, "e": 54170, "s": 54115, "text": "Number List − Adds numbers to the list of the content." }, { "code": null, "e": 54200, "s": 54170, "text": "Blockquote − Quotes the text." }, { "code": null, "e": 54230, "s": 54200, "text": "Blockquote − Quotes the text." }, { "code": null, "e": 54293, "s": 54230, "text": "Horizontal Line − Creates a horizontal line between sentences." }, { "code": null, "e": 54356, "s": 54293, "text": "Horizontal Line − Creates a horizontal line between sentences." }, { "code": null, "e": 54416, "s": 54356, "text": "Left Align − Sets the content on the left side of the page." }, { "code": null, "e": 54476, "s": 54416, "text": "Left Align − Sets the content on the left side of the page." }, { "code": null, "e": 54538, "s": 54476, "text": "Right Align − Sets the content to the right side of the page." }, { "code": null, "e": 54600, "s": 54538, "text": "Right Align − Sets the content to the right side of the page." }, { "code": null, "e": 54645, "s": 54600, "text": "Justify − Justifies the content of the page." }, { "code": null, "e": 54690, "s": 54645, "text": "Justify − Justifies the content of the page." }, { "code": null, "e": 54796, "s": 54690, "text": "Add Link − Adds a link to your content. When you click on this button, the following page gets displayed." }, { "code": null, "e": 54902, "s": 54796, "text": "Add Link − Adds a link to your content. When you click on this button, the following page gets displayed." }, { "code": null, "e": 54960, "s": 54902, "text": "Following are the fields present in the Insert/edit link." }, { "code": null, "e": 54994, "s": 54960, "text": "URL − Enter URL you want to link." }, { "code": null, "e": 55028, "s": 54994, "text": "URL − Enter URL you want to link." }, { "code": null, "e": 55085, "s": 55028, "text": "Link text − Insert text you want to enter into the link." }, { "code": null, "e": 55142, "s": 55085, "text": "Link text − Insert text you want to enter into the link." }, { "code": null, "e": 55249, "s": 55142, "text": "Open link in a new window/tab − Open your link page into the new tab or window. Check the box as required." }, { "code": null, "e": 55356, "s": 55249, "text": "Open link in a new window/tab − Open your link page into the new tab or window. Check the box as required." }, { "code": null, "e": 55579, "s": 55356, "text": "Or link to existing account − Links to an existing content page by selecting the page from the given list. When you click on existing page then you get a link created in the URL section as seen in the following screenshot." }, { "code": null, "e": 55802, "s": 55579, "text": "Or link to existing account − Links to an existing content page by selecting the page from the given list. When you click on existing page then you get a link created in the URL section as seen in the following screenshot." }, { "code": null, "e": 55871, "s": 55802, "text": "Remove Link − Deletes the particular link added for text or content." }, { "code": null, "e": 55940, "s": 55871, "text": "Remove Link − Deletes the particular link added for text or content." }, { "code": null, "e": 55989, "s": 55940, "text": "Read more tag − Adds Read More tag to your page." }, { "code": null, "e": 56038, "s": 55989, "text": "Read more tag − Adds Read More tag to your page." }, { "code": null, "e": 56137, "s": 56038, "text": "Toolbar toggle − Clicking on this you get another list of toolbar as shown in the following image." }, { "code": null, "e": 56236, "s": 56137, "text": "Toolbar toggle − Clicking on this you get another list of toolbar as shown in the following image." }, { "code": null, "e": 56313, "s": 56236, "text": "Paragraph − Selects the headings as required for the text from the dropdown." }, { "code": null, "e": 56390, "s": 56313, "text": "Paragraph − Selects the headings as required for the text from the dropdown." }, { "code": null, "e": 56428, "s": 56390, "text": "Underline − Underlines the sentences." }, { "code": null, "e": 56466, "s": 56428, "text": "Underline − Underlines the sentences." }, { "code": null, "e": 56500, "s": 56466, "text": "Justify − Justifies your content." }, { "code": null, "e": 56534, "s": 56500, "text": "Justify − Justifies your content." }, { "code": null, "e": 56582, "s": 56534, "text": "Text Color − Sets color for words or sentences." }, { "code": null, "e": 56630, "s": 56582, "text": "Text Color − Sets color for words or sentences." }, { "code": null, "e": 56664, "s": 56630, "text": "Paste as Text − Pastes your text." }, { "code": null, "e": 56698, "s": 56664, "text": "Paste as Text − Pastes your text." }, { "code": null, "e": 56743, "s": 56698, "text": "Clear Formatting − Deletes selected content." }, { "code": null, "e": 56788, "s": 56743, "text": "Clear Formatting − Deletes selected content." }, { "code": null, "e": 56859, "s": 56788, "text": "Special character − Inserts special characters needed in your content." }, { "code": null, "e": 56930, "s": 56859, "text": "Special character − Inserts special characters needed in your content." }, { "code": null, "e": 56982, "s": 56930, "text": "Increase Indent − Increases the indent of the page." }, { "code": null, "e": 57034, "s": 56982, "text": "Increase Indent − Increases the indent of the page." }, { "code": null, "e": 57086, "s": 57034, "text": "Decrease Indent − Decreases the indent of the page." }, { "code": null, "e": 57138, "s": 57086, "text": "Decrease Indent − Decreases the indent of the page." }, { "code": null, "e": 57187, "s": 57138, "text": "Undo − Reverses the most recent editing command." }, { "code": null, "e": 57236, "s": 57187, "text": "Undo − Reverses the most recent editing command." }, { "code": null, "e": 57303, "s": 57236, "text": "Redo − Opposite of undo, restores the most recent editing command." }, { "code": null, "e": 57370, "s": 57303, "text": "Redo − Opposite of undo, restores the most recent editing command." }, { "code": null, "e": 57409, "s": 57370, "text": "For writing the content of an article." }, { "code": null, "e": 57457, "s": 57409, "text": "To publish the page to the user on the website." }, { "code": null, "e": 57576, "s": 57457, "text": "Page attributes module allows you to select the parents for your particular page. You can also set order of the pages." }, { "code": null, "e": 57619, "s": 57576, "text": "Parent − Allows you to select parent page." }, { "code": null, "e": 57662, "s": 57619, "text": "Parent − Allows you to select parent page." }, { "code": null, "e": 57698, "s": 57662, "text": "Order − Sets the order of the page." }, { "code": null, "e": 57734, "s": 57698, "text": "Order − Sets the order of the page." }, { "code": null, "e": 57768, "s": 57734, "text": "Includes the images in the pages." }, { "code": null, "e": 58010, "s": 57768, "text": "In this chapter, we will study how to Publish Pages in WordPress. The command, “Publish” is used to make the pages available to all users wherein each user can view that particular page. Publishing a new page in WordPress is an easy process." }, { "code": null, "e": 58065, "s": 58010, "text": "Following are the steps to Publish Pages in WordPress." }, { "code": null, "e": 58116, "s": 58065, "text": "Step (1) − Click on Pages → Add New in WordPress." }, { "code": null, "e": 58270, "s": 58116, "text": "Step (2) − You will get the editor as shown in the following screenshot. You can use the WordPress WYSIWYG editor to add the actual content of your page." }, { "code": null, "e": 58339, "s": 58270, "text": "Step (3) − Click on Publish button as shown in the following screen." }, { "code": null, "e": 58416, "s": 58339, "text": "After clicking on publish, your posts get published for the user to view it." }, { "code": null, "e": 58479, "s": 58416, "text": "In this chapter, we will study how to Edit pages in WordPress." }, { "code": null, "e": 58564, "s": 58479, "text": "Step (1) − Click on Pages → All Pages in WordPress as shown in the following screen." }, { "code": null, "e": 58806, "s": 58564, "text": "Step (2) − You can view About Us (About Us was created in the chapter WordPress - Add Pages). When the cursor hovers on the pages, then few options get displayed below About Us. There are two ways to edit the Post, i.e., Edit and Quick Edit." }, { "code": null, "e": 58884, "s": 58806, "text": "Edit − Click on Edit option in About Us as shown in the following screenshot." }, { "code": null, "e": 59026, "s": 58884, "text": "You can edit or change the content or title from the page as per your need, and then click on Update button as shown in the following screen." }, { "code": null, "e": 59112, "s": 59026, "text": "Quick Edit − Click on Quick Edit option in About Us as shown in the following screen." }, { "code": null, "e": 59280, "s": 59112, "text": "You can edit the Title, Slug and date of the About Us page and can also select the parent for your page as shown in the following shot and then click on Update button." }, { "code": null, "e": 59341, "s": 59280, "text": "In this chapter, we will learn to Delete Pages in WordPress." }, { "code": null, "e": 59395, "s": 59341, "text": "Following are the steps to Delete pages in wordPress." }, { "code": null, "e": 59447, "s": 59395, "text": "Step (1) − Click on Pages → All Pages in WordPress." }, { "code": null, "e": 59671, "s": 59447, "text": "Step (2) − You can delete Sample Page (Sample Page is created by default in WordPress). When the cursor hovers on the pages, then a few options gets displayed below the Sample Page. Click on Trash option to delete the post." }, { "code": null, "e": 59830, "s": 59671, "text": "Or alternatively you can also delete your page directly while editing or adding page by clicking on the Move to Trash button as shown in the following screen." }, { "code": null, "e": 59905, "s": 59830, "text": "Step (3) − To confirm that you have deleted the page, view your page list." }, { "code": null, "e": 60139, "s": 59905, "text": "Tag is a small information attached to the main content or post for the purpose of identification. It tells the visitors what actually the post is about. If the tag is mentioned properly then it helps to find the content very easily." }, { "code": null, "e": 60189, "s": 60139, "text": "Following are the steps to Add Tags in WordPress." }, { "code": null, "e": 60236, "s": 60189, "text": "Step (1) − Click on Posts → Tags in WordPress." }, { "code": null, "e": 60275, "s": 60236, "text": "Step (2) − The Tags page is displayed." }, { "code": null, "e": 60324, "s": 60275, "text": "Following are the details of the fields on Tags." }, { "code": null, "e": 60355, "s": 60324, "text": "Name − Enter the name of tags." }, { "code": null, "e": 60386, "s": 60355, "text": "Name − Enter the name of tags." }, { "code": null, "e": 60463, "s": 60386, "text": "Slug − A word chosen to describe your post. It is specified in the tags URL." }, { "code": null, "e": 60540, "s": 60463, "text": "Slug − A word chosen to describe your post. It is specified in the tags URL." }, { "code": null, "e": 60634, "s": 60540, "text": "Description − Add brief description of your tag. It gets displayed when you hover on the tag." }, { "code": null, "e": 60728, "s": 60634, "text": "Description − Add brief description of your tag. It gets displayed when you hover on the tag." }, { "code": null, "e": 60803, "s": 60728, "text": "After filling all the information about Tags, click on Add New Tag button." }, { "code": null, "e": 60922, "s": 60803, "text": "Step (3) − The new created tags will get displayed on the right side of the page as shown in the following screenshot." }, { "code": null, "e": 61047, "s": 60922, "text": "In this chapter, we will study to Edit Tags in WordPress. You can learn how to add tags in the chapter WordPress - Add Tags." }, { "code": null, "e": 61105, "s": 61047, "text": "Following are the simple steps to Edit Tags in WordPress." }, { "code": null, "e": 61152, "s": 61105, "text": "Step (1) − Click on Posts → Tags in WordPress." }, { "code": null, "e": 61425, "s": 61152, "text": "Step (2) − You can view tag Food around the world (Food around the world was created in the chapter Wordpress - Add Tags). When the cursor hovers on the Tags, then a few options get displayed below the Tag name. There are two ways to edit the tags i.e. Edit and Quick Edit" }, { "code": null, "e": 61503, "s": 61425, "text": "Edit − Click on Edit option in Tags section as shown in the following screen." }, { "code": null, "e": 61609, "s": 61503, "text": "You can edit any of the required field, and then click on Update button as shown in the following screen." }, { "code": null, "e": 61673, "s": 61609, "text": "Here tag fields are same from the chapter WordPress - Add Tags." }, { "code": null, "e": 61767, "s": 61673, "text": "Quick Edit − Click on Quick Edit option in Tags section as shown in the following screenshot." }, { "code": null, "e": 61889, "s": 61767, "text": "Here you can only edit the Name and Slug of the Tags as seen in the following screen and then click on Update Tag button." }, { "code": null, "e": 61949, "s": 61889, "text": "In this chapter, we will learn to Delete tags in WordPress." }, { "code": null, "e": 62002, "s": 61949, "text": "Following are the steps to delete tags in WordPress." }, { "code": null, "e": 62049, "s": 62002, "text": "Step (1) − Click on Posts → Tags in WordPress." }, { "code": null, "e": 62330, "s": 62049, "text": "Step (2) − You can delete tag Food around the world (Food around the world was created in the chapter WordPress - Add Tags), when the cursor hovers on the Tags, then a few options get displayed below the Tags name. Click on Delete in tags section as shown in the following screen." }, { "code": null, "e": 62418, "s": 62330, "text": "When you click on delete, you will get a pop message asking for confirmation to delete." }, { "code": null, "e": 62477, "s": 62418, "text": "You can click on OK button and delete the tag permanently." }, { "code": null, "e": 62669, "s": 62477, "text": "In this chapter, we will learn to Add Links in WordPress pages. Link is a connection from one resource to another. Adding links to your pages or blog posts help you to connect to other pages." }, { "code": null, "e": 62727, "s": 62669, "text": "Following are the simple steps to Add links in WordPress." }, { "code": null, "e": 62779, "s": 62727, "text": "Step (1) − Click on Pages → All Pages in WordPress." }, { "code": null, "e": 62976, "s": 62779, "text": "Step (2) − List of pages created in WordPress will get displayed as shown in the following screen. Select any of the pages to add links inside it. Here, we are going to add links in About Us page." }, { "code": null, "e": 63092, "s": 62976, "text": "Step (3) − Select any of the sentence or word where you want to add link. Here, we will add link to the word Lorem." }, { "code": null, "e": 63195, "s": 63092, "text": "Step (4) − When you click on the Insert/Edit link symbol then the following pop window gets displayed." }, { "code": null, "e": 63253, "s": 63195, "text": "Following are the fields present in the Insert/edit link." }, { "code": null, "e": 63287, "s": 63253, "text": "URL − Enter URL you want to link." }, { "code": null, "e": 63321, "s": 63287, "text": "URL − Enter URL you want to link." }, { "code": null, "e": 63378, "s": 63321, "text": "Link text − Insert text you want to enter into the link." }, { "code": null, "e": 63435, "s": 63378, "text": "Link text − Insert text you want to enter into the link." }, { "code": null, "e": 63542, "s": 63435, "text": "Open link in a new window/tab − Open your link page into the new tab or window. Check the box as required." }, { "code": null, "e": 63649, "s": 63542, "text": "Open link in a new window/tab − Open your link page into the new tab or window. Check the box as required." }, { "code": null, "e": 63878, "s": 63649, "text": "Or link to existing account − Add links to an existing content page by selecting the page from the given list. Click on Or link to existing account and the list of pages and posts gets displayed as shown in the following screen." }, { "code": null, "e": 64107, "s": 63878, "text": "Or link to existing account − Add links to an existing content page by selecting the page from the given list. Click on Or link to existing account and the list of pages and posts gets displayed as shown in the following screen." }, { "code": null, "e": 64257, "s": 64107, "text": "After selecting the particular page or post from the list, the links get created in the URL field as seen in the preceding screen. Click on Add Link." }, { "code": null, "e": 64372, "s": 64257, "text": "Step (5) − When you hover on the word Lorem then the link tooltip gets displayed as shown in the following screen." }, { "code": null, "e": 64439, "s": 64372, "text": "Click on Update button to update the changes in your page or post." }, { "code": null, "e": 64501, "s": 64439, "text": "In this chapter, we will study how to edit link in WordPress." }, { "code": null, "e": 64559, "s": 64501, "text": "Following are the simple steps to Edit Links in WordPress" }, { "code": null, "e": 64631, "s": 64559, "text": "Step (1) − Click on Pages → All Pages as shown in the following screen." }, { "code": null, "e": 64792, "s": 64631, "text": "Step (2) − You can view the list of pages. When the cursor hovers on the About Us page, then a few options get displayed below About Us. Click on Edit as shown." }, { "code": null, "e": 64981, "s": 64792, "text": "Step (3) − Hover on the word Lorem (Link for word Lorem was created in the chapter WordPress - Add Links), and click on the pencil symbol to edit the link as shown in the following screen." }, { "code": null, "e": 65121, "s": 64981, "text": "Step (4) − You can change or edit your link by selecting the page from the existing list. In this case, we have selected the About Us page." }, { "code": null, "e": 65209, "s": 65121, "text": "After selecting the particular page or post from the list, then click on Update button." }, { "code": null, "e": 65322, "s": 65209, "text": "Step (5) − When you hover on the word Lorem then the link tooltip get displayed as seen in the following screen." }, { "code": null, "e": 65389, "s": 65322, "text": "Click on Update button to update the changes in your page or post." }, { "code": null, "e": 65536, "s": 65389, "text": "In this chapter, we will learn to Delete links from WordPress. You can remove the unwanted links which you don’t need for your website or article." }, { "code": null, "e": 65589, "s": 65536, "text": "Following are the steps to Delete Links in WordPress" }, { "code": null, "e": 65641, "s": 65589, "text": "Step (1) − Click on Pages → All Pages in WordPress." }, { "code": null, "e": 65823, "s": 65641, "text": "Step (2) − You can view the list of pages. When the cursor hovers on the About Us page, then a few options gets displayed. Click on the Edit button as shown in the following screen." }, { "code": null, "e": 66031, "s": 65823, "text": "Step (3) − Select the word which you had already linked i.e. Lorem (Link for word Lorem was created in the chapter WordPress - Add Links), and click on the Remove Link Symbol as seen in the following screen." }, { "code": null, "e": 66185, "s": 66031, "text": "Step (4) − When you hover on the word Lorem, there will be no tooltip of the existing URL. The following screenshot shows that the link has been deleted." }, { "code": null, "e": 66390, "s": 66185, "text": "In this chapter, we will learn to Add Comments in WordPress. Adding comments allows your visitors to have a discussion with you. Comments are approved by the admin and then posted to be discussed further." }, { "code": null, "e": 66450, "s": 66390, "text": "Following are the steps to add comments to your blog posts." }, { "code": null, "e": 66502, "s": 66450, "text": "Step (1) − Click on Pages → All Pages in WordPress." }, { "code": null, "e": 66728, "s": 66502, "text": "Step (2) − The list of pages created in WordPress will get displayed as seen in the following screen. Select any of the pages you want to add comments to. Here, we are going to add comment in About Us page. Click on About Us." }, { "code": null, "e": 66832, "s": 66728, "text": "Step (3) − To add a comment on this page, click on Screen options present at the top right hand corner." }, { "code": null, "e": 66966, "s": 66832, "text": "Step (4) − The dropdown list of Screen Option gets displayed. Check the Discussion and Comments box as shown in the following screen." }, { "code": null, "e": 67054, "s": 66966, "text": "Step (5) − You can now view the Discussion and Comments box at the bottom of your page." }, { "code": null, "e": 67113, "s": 67054, "text": "In the Discussion section, there are two options present −" }, { "code": null, "e": 67187, "s": 67113, "text": "Allow Comments − Allows visitors to comment on your blog posts and pages." }, { "code": null, "e": 67261, "s": 67187, "text": "Allow Comments − Allows visitors to comment on your blog posts and pages." }, { "code": null, "e": 67353, "s": 67261, "text": "Allow trackbacks and pingbacks on this page − Allows visitors to give pings and trackbacks." }, { "code": null, "e": 67445, "s": 67353, "text": "Allow trackbacks and pingbacks on this page − Allows visitors to give pings and trackbacks." }, { "code": null, "e": 67525, "s": 67445, "text": "In the Comment section, you can add comments by clicking on Add Comment button." }, { "code": null, "e": 67589, "s": 67525, "text": "Step (6) − Click on Update button after adding the comment box." }, { "code": null, "e": 67709, "s": 67589, "text": "In this chapter, we will learn about how to Edit comments in WordPress. Editing comments can be done only by the admin." }, { "code": null, "e": 67764, "s": 67709, "text": "Following are the steps to Edit Comments in WordPress." }, { "code": null, "e": 67807, "s": 67764, "text": "Step (1) − Click on Comments in WordPress." }, { "code": null, "e": 67925, "s": 67807, "text": "Step (2) − You can view the comments list for the various pages. Select any comment, you want to edit. Click on edit." }, { "code": null, "e": 68027, "s": 67925, "text": "Step (3) − The Edit comment page gets displayed. You can edit the comment and click on Update Button." }, { "code": null, "e": 68104, "s": 68027, "text": "Here you can edit the name, e-mail, URL or the comment from the comment box." }, { "code": null, "e": 68401, "s": 68104, "text": "In this chapter, we will learn to Moderate Comments in WordPress. Comment moderation is a process where, when visitors comment on posts, the comment is not published directly until and unless it is approved by the admin to be posted. It manages your comments so that there is no comment spamming." }, { "code": null, "e": 68457, "s": 68401, "text": "Step (1) − Click on Settings → Discussion in WordPress." }, { "code": null, "e": 68512, "s": 68457, "text": "Step (2) − The Discussion Setting page gets displayed." }, { "code": null, "e": 68715, "s": 68512, "text": "In the Comment Moderation field, enter those words or URLs you do not want any visitor to add comments. Whenever a visitor gives any comments it would be moderated by the admin first and then published." }, { "code": null, "e": 68749, "s": 68715, "text": "Step (3) − Click on Save Changes." }, { "code": null, "e": 68982, "s": 68749, "text": "In this chapter, we will study how to View Plugins in WordPress. It helps you to enable and disable WordPress Plugins. This adds the unique features to an existing web site. Plugins extend and enlarge the functionality of WordPress." }, { "code": null, "e": 69043, "s": 68982, "text": "Following are the simple steps to View Plugins in WordPress." }, { "code": null, "e": 69119, "s": 69043, "text": "Step (1) − Click on Plugins → Installed Plugins in WordPress administrator." }, { "code": null, "e": 69218, "s": 69119, "text": "Step (2) − You will see the list of existing plugins on your site as seen in the following screen." }, { "code": null, "e": 69394, "s": 69218, "text": "A table of Plugin and Description is displayed. Names of the plugins are defined in Plugin column and a brief description about the plugin is defined under Description column." }, { "code": null, "e": 69461, "s": 69394, "text": "Following functions appear as Plugin toolbar options on the page −" }, { "code": null, "e": 69511, "s": 69461, "text": "Active − Shows the active plugins on the website." }, { "code": null, "e": 69561, "s": 69511, "text": "Active − Shows the active plugins on the website." }, { "code": null, "e": 69629, "s": 69561, "text": "Inactive − Shows the installed but inactive plugins on the website." }, { "code": null, "e": 69697, "s": 69629, "text": "Inactive − Shows the installed but inactive plugins on the website." }, { "code": null, "e": 69776, "s": 69697, "text": "Update Available − Shows, if a new version is available or asks to update now." }, { "code": null, "e": 69855, "s": 69776, "text": "Update Available − Shows, if a new version is available or asks to update now." }, { "code": null, "e": 70071, "s": 69855, "text": "In this chapter, we will study how to install plugins in WordPress. It is really easy to install plugins. All the plugins are free to download; the only condition is that a plugin must be in the WordPress directory." }, { "code": null, "e": 70135, "s": 70071, "text": "Following are the simple steps to Install Plugins in WordPress." }, { "code": null, "e": 70187, "s": 70135, "text": "Step (1) − Click on Plugins → Add New in WordPress." }, { "code": null, "e": 70389, "s": 70187, "text": "Step (2) − Enter your required plugin name in the search box as shown in the following screen. List of plugins which are relevant to the plugins name will get displayed as seen in the following screen." }, { "code": null, "e": 70622, "s": 70389, "text": "Select the required plugin you want to use. Here, we have searched All in one SEO Pack plugin, which happens to be the first plugin as shown in the preceding screen. Click on install now button to install the plugin on your website." }, { "code": null, "e": 70693, "s": 70622, "text": "Step (3) − The plugins automatically start downloading and installing." }, { "code": null, "e": 70811, "s": 70693, "text": "Click on Activate Plugin to activate the plugin on your website, which makes your task much easier using this plugin." }, { "code": null, "e": 70928, "s": 70811, "text": "Step (4) − Once activated, you will see the installed plugin in the list of plugins as seen in the following screen." }, { "code": null, "e": 71207, "s": 70928, "text": "In this chapter, we will study how to Customize Plugins in WordPress without writing any HTML or CSS. It's usually a large addition for multi-user sites. This new method allows you to customize your login page by using the WordPress theme customizer (no coding skills required)." }, { "code": null, "e": 71273, "s": 71207, "text": "Following are the simple steps to Customize Plugins in WordPress." }, { "code": null, "e": 71312, "s": 71273, "text": "Step (1) − Click on Plugins → Add New." }, { "code": null, "e": 71385, "s": 71312, "text": "Step (2) − Install and activate the Custom Login Page Customizer Plugin." }, { "code": null, "e": 71443, "s": 71385, "text": "Step (3) − Click on Appearance → Login Customize section." }, { "code": null, "e": 71508, "s": 71443, "text": "Step (4) − Click on Start Customizing button to proceed further." }, { "code": null, "e": 71638, "s": 71508, "text": "Step (5) − It will launch the built-in WordPress theme customizer. You can customize the theme and make it look the way you want." }, { "code": null, "e": 71856, "s": 71638, "text": "Click on the new Login Customizer tab in the side panel. Login customizer page will get displayed. On the login customizer page, you can customize your login page in the same way as you customize your WordPress theme." }, { "code": null, "e": 71939, "s": 71856, "text": "Step (6) − The customized login page will appear as shown in the following screen." }, { "code": null, "e": 72012, "s": 71939, "text": "Logo − Upload logo of your choice to replace the default WordPress logo." }, { "code": null, "e": 72085, "s": 72012, "text": "Logo − Upload logo of your choice to replace the default WordPress logo." }, { "code": null, "e": 72172, "s": 72085, "text": "Background − Add background image or you can choose a background color of your choice." }, { "code": null, "e": 72259, "s": 72172, "text": "Background − Add background image or you can choose a background color of your choice." }, { "code": null, "e": 72356, "s": 72259, "text": "Form Background − Select form background image or color for login form container of your choice." }, { "code": null, "e": 72453, "s": 72356, "text": "Form Background − Select form background image or color for login form container of your choice." }, { "code": null, "e": 72668, "s": 72453, "text": "Most of the selections in the customizer panel are transparent. You can check all the selections in the customizer to adjust the setting as per your requirement of your login page. Click on Save and Publish button." }, { "code": null, "e": 72913, "s": 72668, "text": "In this chapter, we will learn about the roles of users in WordPress. Every user has their own role in WordPress. Roles are like permissions given to a particular user to access the WordPress site. These roles can be allotted only by the Admin." }, { "code": null, "e": 72969, "s": 72913, "text": "Here are few pre-defined roles available in WordPress −" }, { "code": null, "e": 73159, "s": 72969, "text": "Administrator − The Administrator has all the rights. An Admin can do anything and everything on the WordPress site such as creating more admins, inviting more users and also removing them." }, { "code": null, "e": 73349, "s": 73159, "text": "Administrator − The Administrator has all the rights. An Admin can do anything and everything on the WordPress site such as creating more admins, inviting more users and also removing them." }, { "code": null, "e": 73505, "s": 73349, "text": "Editor − The Editor has access to all the posts, pages, comments, categories, tags, and links. They can create, publish, edit or delete any posts or pages." }, { "code": null, "e": 73661, "s": 73505, "text": "Editor − The Editor has access to all the posts, pages, comments, categories, tags, and links. They can create, publish, edit or delete any posts or pages." }, { "code": null, "e": 73755, "s": 73661, "text": "Author − The Author can only write posts, upload pictures, edit, and publish their own posts." }, { "code": null, "e": 73849, "s": 73755, "text": "Author − The Author can only write posts, upload pictures, edit, and publish their own posts." }, { "code": null, "e": 74255, "s": 73849, "text": "Contributor − The Contributor can only write and edit their posts until published. They can create their own posts and pages but cannot publish them. They cannot upload images or files but can see your site's status. When they want to publish any post, it must be first notified personally to the administrator for review. When the post is approved, the contributor cannot make any changes once published." }, { "code": null, "e": 74661, "s": 74255, "text": "Contributor − The Contributor can only write and edit their posts until published. They can create their own posts and pages but cannot publish them. They cannot upload images or files but can see your site's status. When they want to publish any post, it must be first notified personally to the administrator for review. When the post is approved, the contributor cannot make any changes once published." }, { "code": null, "e": 74803, "s": 74661, "text": "Follower − The Follower can only read and comment on the posts. Followers are the ones who have signed in to your account to receive updates." }, { "code": null, "e": 74945, "s": 74803, "text": "Follower − The Follower can only read and comment on the posts. Followers are the ones who have signed in to your account to receive updates." }, { "code": null, "e": 75040, "s": 74945, "text": "Viewer − Viewers can only view your posts; they cannot edit but can only comment on the posts." }, { "code": null, "e": 75135, "s": 75040, "text": "Viewer − Viewers can only view your posts; they cannot edit but can only comment on the posts." }, { "code": null, "e": 75416, "s": 75135, "text": "In this chapter, we will study how to Add users to your WordPress blog or website. When users register on your WordPress blog or website, you get an e-mail notification, so you always know when new users register, and you can then get into your Dashboard and edit the users’ role." }, { "code": null, "e": 75474, "s": 75416, "text": "Following are the simple steps to Add Users in WordPress." }, { "code": null, "e": 75524, "s": 75474, "text": "Step (1) − Click on Users → Add New in WordPress." }, { "code": null, "e": 75677, "s": 75524, "text": "Step (2) − You can fill the user detail on the Add New User page. Fill in all the required fields (as seen in the following screen) to proceed further." }, { "code": null, "e": 75764, "s": 75677, "text": "Username (required) − Enter the unique username, which you want to display on website." }, { "code": null, "e": 75851, "s": 75764, "text": "Username (required) − Enter the unique username, which you want to display on website." }, { "code": null, "e": 75973, "s": 75851, "text": "E-mail (required) − Enter the valid e-mail address. The user receives notifications from the site at this e-mail address." }, { "code": null, "e": 76095, "s": 75973, "text": "E-mail (required) − Enter the valid e-mail address. The user receives notifications from the site at this e-mail address." }, { "code": null, "e": 76137, "s": 76095, "text": "First Name − Enter the user’s first name." }, { "code": null, "e": 76179, "s": 76137, "text": "First Name − Enter the user’s first name." }, { "code": null, "e": 76219, "s": 76179, "text": "Last Name − Enter the user’s last name." }, { "code": null, "e": 76259, "s": 76219, "text": "Last Name − Enter the user’s last name." }, { "code": null, "e": 76307, "s": 76259, "text": "Website − Enter the URL for the user’s website." }, { "code": null, "e": 76355, "s": 76307, "text": "Website − Enter the URL for the user’s website." }, { "code": null, "e": 76397, "s": 76355, "text": "Password (required) − Enter the password." }, { "code": null, "e": 76439, "s": 76397, "text": "Password (required) − Enter the password." }, { "code": null, "e": 76538, "s": 76439, "text": "Repeat Password (required) − Repeat the same password as the previous password for authentication." }, { "code": null, "e": 76637, "s": 76538, "text": "Repeat Password (required) − Repeat the same password as the previous password for authentication." }, { "code": null, "e": 76758, "s": 76637, "text": "Send Password − Send password to the New User by e-mail checkbox. The user will receive an e-mail with the new password." }, { "code": null, "e": 76879, "s": 76758, "text": "Send Password − Send password to the New User by e-mail checkbox. The user will receive an e-mail with the new password." }, { "code": null, "e": 76997, "s": 76879, "text": "Role − Select the particular role from the dropdown, i.e., Subscriber, Contributor, Author, Editor, or Administrator." }, { "code": null, "e": 77115, "s": 76997, "text": "Role − Select the particular role from the dropdown, i.e., Subscriber, Contributor, Author, Editor, or Administrator." }, { "code": null, "e": 77176, "s": 77115, "text": "Click on Add New User button to add user to your users list." }, { "code": null, "e": 77337, "s": 77176, "text": "Step (3) − You can view the user list to see whether the users have been added. A message will be displayed as New User Created as seen in the following screen." }, { "code": null, "e": 77554, "s": 77337, "text": "In this chapter, we will study about User Photo in WordPress. To add user photo in WordPress, you must install plugin User Photo from WordPress plugins. It helps you add a photo of your own to your WordPress profile." }, { "code": null, "e": 77606, "s": 77554, "text": "Following are the simple steps to add a User photo." }, { "code": null, "e": 77649, "s": 77606, "text": "Step (1) − Click on Settings → User Photo." }, { "code": null, "e": 77704, "s": 77649, "text": "Step (2) − The User Photo Options page gets displayed." }, { "code": null, "e": 77813, "s": 77704, "text": "Set the dimension for your thumbnails and make the required changes and then click on Update Options button." }, { "code": null, "e": 78018, "s": 77813, "text": "Step (3) − To view the plugin User Photo is activated, go to Users → Your Profile. In your Profile page you can see Your Photo section is added. Here you can upload your photo to display as profile image." }, { "code": null, "e": 78081, "s": 78018, "text": "In this chapter, we will study how to Edit Users in WordPress." }, { "code": null, "e": 78140, "s": 78081, "text": "Following are the simple steps to Edit Users in WordPress." }, { "code": null, "e": 78179, "s": 78140, "text": "Step (1) − Click on Users → All Users." }, { "code": null, "e": 78220, "s": 78179, "text": "Step (2) − You will see a list of users." }, { "code": null, "e": 78266, "s": 78220, "text": "There are two more tabs seen on the toolbar −" }, { "code": null, "e": 78324, "s": 78266, "text": "Administrator − List of administrators will be displayed." }, { "code": null, "e": 78382, "s": 78324, "text": "Administrator − List of administrators will be displayed." }, { "code": null, "e": 78434, "s": 78382, "text": "Subscriber − List of subscribers will be displayed." }, { "code": null, "e": 78486, "s": 78434, "text": "Subscriber − List of subscribers will be displayed." }, { "code": null, "e": 78588, "s": 78486, "text": "When we click on the Change role to box, a dropdown list appears as seen in the preceding screenshot." }, { "code": null, "e": 78643, "s": 78588, "text": "Subscriber − A person who can only manage his profile." }, { "code": null, "e": 78698, "s": 78643, "text": "Subscriber − A person who can only manage his profile." }, { "code": null, "e": 78785, "s": 78698, "text": "Contributor − A person who can write and supervise own posts, but cannot publish them." }, { "code": null, "e": 78872, "s": 78785, "text": "Contributor − A person who can write and supervise own posts, but cannot publish them." }, { "code": null, "e": 78932, "s": 78872, "text": "Author − A person who can publish and manage his own posts." }, { "code": null, "e": 78992, "s": 78932, "text": "Author − A person who can publish and manage his own posts." }, { "code": null, "e": 79080, "s": 78992, "text": "Editor − A person who can publish and manage posts, including the posts of other users." }, { "code": null, "e": 79168, "s": 79080, "text": "Editor − A person who can publish and manage posts, including the posts of other users." }, { "code": null, "e": 79268, "s": 79168, "text": "Administrator − A person who has access to all the administration features within a single website." }, { "code": null, "e": 79368, "s": 79268, "text": "Administrator − A person who has access to all the administration features within a single website." }, { "code": null, "e": 79518, "s": 79368, "text": "Click on the check box of the user name to change the role of the user. Then, click on change button and the user's role will be changed accordingly." }, { "code": null, "e": 79601, "s": 79518, "text": "Step (3) − Click on Edit option as shown in the following screen to edit the user." }, { "code": null, "e": 79751, "s": 79601, "text": "Step (4) − The Edit User page is displayed. Here you can edit or modify all the fields as per your need and click on Update User to save the changes." }, { "code": null, "e": 79816, "s": 79751, "text": "In this chapter, we will learn how to delete users in WordPress." }, { "code": null, "e": 79857, "s": 79816, "text": "Following are the steps to Delete Users." }, { "code": null, "e": 79896, "s": 79857, "text": "Step (1) − Click on Users → All Users." }, { "code": null, "e": 79970, "s": 79896, "text": "Step (2) − List of Users gets displayed as shown in the following screen." }, { "code": null, "e": 80037, "s": 79970, "text": "Step (3) − Select the one you want to delete. And click on Delete." }, { "code": null, "e": 80101, "s": 80037, "text": "Step (4) − When you click on Delete you get the following page." }, { "code": null, "e": 80198, "s": 80101, "text": "Step (5) − Select options as required and click on Confirm Deletion. Your user will be deleted." }, { "code": null, "e": 80300, "s": 80198, "text": "Step (6) − We have another method of deleting users. A screen as shown in the following shot appears." }, { "code": null, "e": 80420, "s": 80300, "text": "Here you can select the users to delete, check the boxes and click on Delete from the dropdown list and click on Apply." }, { "code": null, "e": 80492, "s": 80420, "text": "Step (7) − Once you click on Apply, the users selected will be deleted." }, { "code": null, "e": 80570, "s": 80492, "text": "In this chapter, we will learn how to create a Personal profile in WordPress." }, { "code": null, "e": 80615, "s": 80570, "text": "Following are the steps to Personal Profile." }, { "code": null, "e": 80685, "s": 80615, "text": "Step(1) − Click on Users → Your Profile from the left navigation bar." }, { "code": null, "e": 80769, "s": 80685, "text": "Step (2) − When you click on ‘Your profile’ the following screen will be displayed." }, { "code": null, "e": 80823, "s": 80769, "text": "The following Personal options appear on the screen −" }, { "code": null, "e": 81030, "s": 80823, "text": "Visual editor − While you are adding posts/pages to your site you can enable this setting if you wish to create, format, or edit your post. If you disable this setting, you won’t be able to use this option." }, { "code": null, "e": 81237, "s": 81030, "text": "Visual editor − While you are adding posts/pages to your site you can enable this setting if you wish to create, format, or edit your post. If you disable this setting, you won’t be able to use this option." }, { "code": null, "e": 81341, "s": 81237, "text": "Admin color scheme − You can change the color of your WordPress site by selecting any of the following." }, { "code": null, "e": 81445, "s": 81341, "text": "Admin color scheme − You can change the color of your WordPress site by selecting any of the following." }, { "code": null, "e": 81569, "s": 81445, "text": "Keyboard Shortcuts − If you are too fast at getting your work done and need keyboard shortcuts then you can check this box." }, { "code": null, "e": 81693, "s": 81569, "text": "Keyboard Shortcuts − If you are too fast at getting your work done and need keyboard shortcuts then you can check this box." }, { "code": null, "e": 81774, "s": 81693, "text": "Toolbar − If you check this box, you can view the toolbar while using WordPress." }, { "code": null, "e": 81855, "s": 81774, "text": "Toolbar − If you check this box, you can view the toolbar while using WordPress." }, { "code": null, "e": 81860, "s": 81855, "text": "Name" }, { "code": null, "e": 81893, "s": 81860, "text": "Username − Enter your user name." }, { "code": null, "e": 81926, "s": 81893, "text": "Username − Enter your user name." }, { "code": null, "e": 81987, "s": 81926, "text": "First Name/ Last Name − Enter your first name and last name." }, { "code": null, "e": 82048, "s": 81987, "text": "First Name/ Last Name − Enter your first name and last name." }, { "code": null, "e": 82085, "s": 82048, "text": "Nick name − Enter nick names if any." }, { "code": null, "e": 82122, "s": 82085, "text": "Nick name − Enter nick names if any." }, { "code": null, "e": 82211, "s": 82122, "text": "Display name publicly as − Check the box if you want your name to be displayed publicly." }, { "code": null, "e": 82300, "s": 82211, "text": "Display name publicly as − Check the box if you want your name to be displayed publicly." }, { "code": null, "e": 82313, "s": 82300, "text": "Contact Info" }, { "code": null, "e": 82352, "s": 82313, "text": "E-mail − Enter a valid e-mail address." }, { "code": null, "e": 82391, "s": 82352, "text": "E-mail − Enter a valid e-mail address." }, { "code": null, "e": 82427, "s": 82391, "text": "Website − Type in your web address." }, { "code": null, "e": 82463, "s": 82427, "text": "Website − Type in your web address." }, { "code": null, "e": 82478, "s": 82463, "text": "About yourself" }, { "code": null, "e": 82522, "s": 82478, "text": "Biographical Info − Some details about you." }, { "code": null, "e": 82566, "s": 82522, "text": "Biographical Info − Some details about you." }, { "code": null, "e": 82614, "s": 82566, "text": "New password − Enter a password of your choice." }, { "code": null, "e": 82662, "s": 82614, "text": "New password − Enter a password of your choice." }, { "code": null, "e": 82758, "s": 82662, "text": "Repeat password − Re-enter the password for authentication. Password must contain 7 characters." }, { "code": null, "e": 82854, "s": 82758, "text": "Repeat password − Re-enter the password for authentication. Password must contain 7 characters." }, { "code": null, "e": 82958, "s": 82854, "text": "Your photo − You can upload an image of your own from your computer. This will be your profile picture." }, { "code": null, "e": 83062, "s": 82958, "text": "Your photo − You can upload an image of your own from your computer. This will be your profile picture." }, { "code": null, "e": 83138, "s": 83062, "text": "Step (3) − After you have updated all the changes, click on Update Profile." }, { "code": null, "e": 83380, "s": 83138, "text": "In this chapter, we will learn about Theme management. It includes image files, templates, CSS stylesheets, etc. that can help to make your website look great. This chapter discusses how to install, add new, or customize themes in WordPress." }, { "code": null, "e": 83426, "s": 83380, "text": "Following are the steps for Theme Management." }, { "code": null, "e": 83484, "s": 83426, "text": "Step (1) − Select Appearance → Themes from the dashboard." }, { "code": null, "e": 83584, "s": 83484, "text": "Step (2) − The following screen will be displayed. Hover over any theme and click on Theme Details." }, { "code": null, "e": 83744, "s": 83584, "text": "Step (3) − When you click on Theme Detail the following page appears. It consists of details related to the theme. Details like version, description, tags etc." }, { "code": null, "e": 83888, "s": 83744, "text": "If you want to add this theme to your page/website then click on Activate, and if you want to just check the theme, then click on Live preview." }, { "code": null, "e": 83948, "s": 83888, "text": "If you click on activate then you get a pop-up message as −" }, { "code": null, "e": 83979, "s": 83948, "text": "Step (4) − Click on Customize." }, { "code": null, "e": 84139, "s": 83979, "text": "Step (5) − On the left side of the page, you can customize your theme. Any changes you make or anything new you add is displayed on the right side of the page." }, { "code": null, "e": 84253, "s": 84139, "text": "We will learn about customizing the appearance of the themes in the next chapter i.e.; WordPress Customize Theme." }, { "code": null, "e": 84449, "s": 84253, "text": "In this chapter, we will learn how to customize themes. Customizing themes help you to give a new look to your website. Here you can change background images/colors, add titles, and do much more." }, { "code": null, "e": 84493, "s": 84449, "text": "Following are the steps of Customize theme." }, { "code": null, "e": 84537, "s": 84493, "text": "Step (1) − Click on Appearance → Customize." }, { "code": null, "e": 84588, "s": 84537, "text": "Step (2) − The following screen will be displayed." }, { "code": null, "e": 84840, "s": 84588, "text": "As can be seen, on the left side we have the customizing section, and on the right side we have the theme you have chosen. So any changes you make on the left side will be displayed on the right side of the page. Here are a few options you must know −" }, { "code": null, "e": 84935, "s": 84840, "text": "Active theme − In this section, you can change the current theme just by clicking on ‘Change’." }, { "code": null, "e": 85076, "s": 84935, "text": "When you click on ‘Change’ you get a list of themes, click on any of the themes, and then click ‘Save & Continue’. Your theme will be saved." }, { "code": null, "e": 85188, "s": 85076, "text": "Site Title & Tagline − In this section, you can add the site title and tagline you want to add to your website." }, { "code": null, "e": 85276, "s": 85188, "text": "Add your title name in the ‘Site Title’ section. And your tagline in the ‘Tagline’ box." }, { "code": null, "e": 85544, "s": 85276, "text": "Colors − You can change your header text color using this section. As you scroll through the colors you find changes happening on the right side of your page. You can even add a color of your own into the box that is situated in between ‘Current color’ and ‘Default’." }, { "code": null, "e": 85687, "s": 85544, "text": "Header Image − Add a header image either by selecting from the suggestions or you can add an image of your own by clicking on ‘Add new image’." }, { "code": null, "e": 85733, "s": 85687, "text": "Widgets − Add widgets to your site from here." }, { "code": null, "e": 85795, "s": 85733, "text": "When you click on the arrow mark the following image appears." }, { "code": null, "e": 85825, "s": 85795, "text": "Here, there are two options −" }, { "code": null, "e": 85958, "s": 85825, "text": "First is the ‘Main Widget Area’, when you click on this you get another list of widgets that are to be displayed in the footer area." }, { "code": null, "e": 86129, "s": 85958, "text": "When you click on any of the widgets a dropdown appears where you can edit more or add more. For example − If you want to add categories then the following image appears." }, { "code": null, "e": 86326, "s": 86129, "text": "In this image, as you can see, you can add your category in the ‘Title’ section. Check any of the required boxes. If you do not want to add any, then say ‘Remove’. Same goes for other widgets too." }, { "code": null, "e": 86489, "s": 86326, "text": "Secondary Widget − Here you must click on ‘Add a widget’ and you get a side bar with a list of different widgets. Click on any and it adds up to your widget list." }, { "code": null, "e": 86601, "s": 86489, "text": "If you want to add more widgets then click on ‘Add a widget’ again and you can add as many widgets as you want." }, { "code": null, "e": 86679, "s": 86601, "text": "Static Front − Select either latest posts or static front page for your site." }, { "code": null, "e": 86898, "s": 86679, "text": "In this chapter, we will study about Widget Management. Widgets are small blocks that perform specific functions. These give design and structure control to the WordPress theme. Some specific features of a widget are −" }, { "code": null, "e": 86938, "s": 86898, "text": "They help you add content and features." }, { "code": null, "e": 86993, "s": 86938, "text": "They can be easily dragged and dropped in widget area." }, { "code": null, "e": 87059, "s": 86993, "text": "They vary from theme to theme. They are not same for every theme." }, { "code": null, "e": 87101, "s": 87059, "text": "Step (1) − Click on Appearance → Widgets." }, { "code": null, "e": 87167, "s": 87101, "text": "Step (2) − The following screen showing available widgets appear." }, { "code": null, "e": 87212, "s": 87167, "text": "The following functions appear on the page −" }, { "code": null, "e": 87281, "s": 87212, "text": "Available Widgets − You can use these to add into your sidebar main." }, { "code": null, "e": 87350, "s": 87281, "text": "Available Widgets − You can use these to add into your sidebar main." }, { "code": null, "e": 87452, "s": 87350, "text": "Inactive Sidebar (not used) − These are not used and can be removed permanently from the widget list." }, { "code": null, "e": 87554, "s": 87452, "text": "Inactive Sidebar (not used) − These are not used and can be removed permanently from the widget list." }, { "code": null, "e": 87635, "s": 87554, "text": "Inactive Widgets − Removes the widgets from sidebar but keep it in the settings." }, { "code": null, "e": 87716, "s": 87635, "text": "Inactive Widgets − Removes the widgets from sidebar but keep it in the settings." }, { "code": null, "e": 87781, "s": 87716, "text": "Sidebar Main − Any widget you add here will appear on your site." }, { "code": null, "e": 87846, "s": 87781, "text": "Sidebar Main − Any widget you add here will appear on your site." }, { "code": null, "e": 87907, "s": 87846, "text": "Manage in Customizer − Takes you back to customization page." }, { "code": null, "e": 87968, "s": 87907, "text": "Manage in Customizer − Takes you back to customization page." }, { "code": null, "e": 88062, "s": 87968, "text": "Step (3) − Drag and drop in the Sidebar Main. Any widget you add here, shows up on your site." }, { "code": null, "e": 88160, "s": 88062, "text": "In this chapter, we will study about background images, background colors and background opacity." }, { "code": null, "e": 88205, "s": 88160, "text": "Step (1) − Click on Appearance → Background." }, { "code": null, "e": 88288, "s": 88205, "text": "Step (2) − The following page appears where the Background Image section shows up." }, { "code": null, "e": 88419, "s": 88288, "text": "Step (3) − There’s no image selected for background. If you want to do so, then click on Select Image. You get the following page." }, { "code": null, "e": 88465, "s": 88419, "text": "Here you can upload images using two options." }, { "code": null, "e": 88478, "s": 88465, "text": "Upload Files" }, { "code": null, "e": 88492, "s": 88478, "text": "Media Library" }, { "code": null, "e": 88675, "s": 88492, "text": "Step (4) − Upload Files − When you click on Upload files the following screen is displayed. Select files from your desktop and then click on Choose Image if satisfied with the image." }, { "code": null, "e": 88899, "s": 88675, "text": "Step (5) − Media Library − When you click on Media Library the following page appears. Select files from the WordPress media library, which means, if you already have images updated then you can select any of them directly." }, { "code": null, "e": 88972, "s": 88899, "text": "After selecting an image, on the right side you will get a few options −" }, { "code": null, "e": 89227, "s": 88972, "text": "Edit Image − When you click on this you are taken to another page where you can edit the scale image, dimensions, crop image, and thumbnail settings, etc. As shown in the following image, make the required changes, click on Save and then click on Update." }, { "code": null, "e": 89482, "s": 89227, "text": "Edit Image − When you click on this you are taken to another page where you can edit the scale image, dimensions, crop image, and thumbnail settings, etc. As shown in the following image, make the required changes, click on Save and then click on Update." }, { "code": null, "e": 89569, "s": 89482, "text": "Delete Permanently − If you want your image off the library then click on this button." }, { "code": null, "e": 89656, "s": 89569, "text": "Delete Permanently − If you want your image off the library then click on this button." }, { "code": null, "e": 89698, "s": 89656, "text": "URL − Enter your image URL into this box." }, { "code": null, "e": 89740, "s": 89698, "text": "URL − Enter your image URL into this box." }, { "code": null, "e": 89832, "s": 89740, "text": "Title − If you want to make any changes in the title of the image you can do it right here." }, { "code": null, "e": 89924, "s": 89832, "text": "Title − If you want to make any changes in the title of the image you can do it right here." }, { "code": null, "e": 89992, "s": 89924, "text": "Caption − You can explain briefly about your image in this section." }, { "code": null, "e": 90060, "s": 89992, "text": "Caption − You can explain briefly about your image in this section." }, { "code": null, "e": 90170, "s": 90060, "text": "Alt text − Give an alternative text to your image so that it is easily available for the users during search." }, { "code": null, "e": 90280, "s": 90170, "text": "Alt text − Give an alternative text to your image so that it is easily available for the users during search." }, { "code": null, "e": 90333, "s": 90280, "text": "Description − A little description about your image." }, { "code": null, "e": 90386, "s": 90333, "text": "Description − A little description about your image." }, { "code": null, "e": 90627, "s": 90386, "text": "Step (6) − Click on Colors → Background Color on the same page. Change your background color accordingly. Background Opacity is not used for all themes. Theme customization is not same for every theme we use. It changes from theme to theme." }, { "code": null, "e": 90711, "s": 90627, "text": "In this chapter, we will study how to transfer WordPress to a new hosting platform." }, { "code": null, "e": 90800, "s": 90711, "text": "Here, we have used Hostinger web hosting to transfer the WordPress site to another host." }, { "code": null, "e": 90890, "s": 90800, "text": "Just follow the simple steps given below to transfer your WordPress site to another host." }, { "code": null, "e": 91040, "s": 90890, "text": "Step (1) − Keep the backup of WordPress files and export the database. We will study about this in detail in the chapter WordPress - Backup & Restore" }, { "code": null, "e": 91135, "s": 91040, "text": "Step (2) − Login to your cPanel and click on MySQL Databases as shown in the following screen." }, { "code": null, "e": 91253, "s": 91135, "text": "Step (3) − Create a new database and MySQL user as shown in the following screen. The page has the following fields −" }, { "code": null, "e": 91301, "s": 91253, "text": "MySQL Database Name − Enter your database name." }, { "code": null, "e": 91349, "s": 91301, "text": "MySQL Database Name − Enter your database name." }, { "code": null, "e": 91387, "s": 91349, "text": "MySQL Username − Enter your username." }, { "code": null, "e": 91425, "s": 91387, "text": "MySQL Username − Enter your username." }, { "code": null, "e": 91468, "s": 91425, "text": "Password − Set password for your database." }, { "code": null, "e": 91511, "s": 91468, "text": "Password − Set password for your database." }, { "code": null, "e": 91593, "s": 91511, "text": "Password again − Once again set the same password as previous for authentication." }, { "code": null, "e": 91675, "s": 91593, "text": "Password again − Once again set the same password as previous for authentication." }, { "code": null, "e": 91729, "s": 91675, "text": "After filling all the fields, Click on Create button." }, { "code": null, "e": 91830, "s": 91729, "text": "Step (4) − You can view your created MySQL database, User and Host as shown in the following screen." }, { "code": null, "e": 91860, "s": 91830, "text": "Step (5) − Click on + symbol." }, { "code": null, "e": 91892, "s": 91860, "text": "Step (6) − Click on phpMyAdmin." }, { "code": null, "e": 91947, "s": 91892, "text": "Step (7) − Click on Import tab on the phpMyAdmin page." }, { "code": null, "e": 92053, "s": 91947, "text": "Step (8) − Click on Choose File button to select the backup file from your system and click on Go button." }, { "code": null, "e": 92143, "s": 92053, "text": "Step (9) − You can view the tables of database uploaded as shown in the following screen." }, { "code": null, "e": 92317, "s": 92143, "text": "Step (10) − Upload your WordPress files by using file transfer protocol(FileZilla) as shown in the chapter WordPress - Backup & Restore in Restoring WordPress Files section." }, { "code": null, "e": 92448, "s": 92317, "text": "Step (11) − Edit wp-config.php file as mentioned in the Restoring WordPress Files section in chapter Wordpress - Backup & Restore." }, { "code": null, "e": 92526, "s": 92448, "text": "Step (12) − Inside the Website section of hostinger, Click on Auto Installer." }, { "code": null, "e": 92643, "s": 92526, "text": "Step (13) − You can view the uploaded file of the WordPress. Click on the URL link as shown in the following screen." }, { "code": null, "e": 92697, "s": 92643, "text": "Step (14) − You can view the login page of WordPress." }, { "code": null, "e": 92843, "s": 92697, "text": "In this chapter, we will study how to update version in WordPress. Here, we will upgrade WordPress to the latest version through the admin panel." }, { "code": null, "e": 92912, "s": 92843, "text": "Following are a few simple steps to update the version in WordPress." }, { "code": null, "e": 92984, "s": 92912, "text": "Step (1) − Click on Please Update Now as shown in the following screen." }, { "code": null, "e": 93148, "s": 92984, "text": "You will get notifications in WordPress admin panel when there is a newer version available for WordPress. Before updating, it is advised to keep WordPress backup." }, { "code": null, "e": 93257, "s": 93148, "text": "Step (2) − After clicking on the update link, the following page gets displayed. Click on Update Now button." }, { "code": null, "e": 93342, "s": 93257, "text": "Step (3) − The following message gets displayed during the upgradation of WordPress." }, { "code": null, "e": 93400, "s": 93342, "text": "Note − While updating the version, if you get an error as" }, { "code": null, "e": 93446, "s": 93400, "text": "then you need to take the following actions −" }, { "code": null, "e": 93494, "s": 93446, "text": "Open your WordPress folder → wp-includes folder" }, { "code": null, "e": 93542, "s": 93494, "text": "Open your WordPress folder → wp-includes folder" }, { "code": null, "e": 93632, "s": 93542, "text": "Open class-http.php file and add the following line at the beginning: set_time_limit (0);" }, { "code": null, "e": 93722, "s": 93632, "text": "Open class-http.php file and add the following line at the beginning: set_time_limit (0);" }, { "code": null, "e": 93737, "s": 93722, "text": "Save the file." }, { "code": null, "e": 93752, "s": 93737, "text": "Save the file." }, { "code": null, "e": 93797, "s": 93752, "text": "Now your WordPress is successfully upgraded." }, { "code": null, "e": 94028, "s": 93797, "text": "In this chapter, we will learn how to protect your WordPress blog or website from spam. Make sure that your WordPress script is updated to the latest stable version. WordPress comes with a preinstalled antispam solution - Akismet." }, { "code": null, "e": 94196, "s": 94028, "text": "You can activate Akismet, for which you should have a WordPress API key. You have to register at the official WordPress website. The key will be sent to your mail box." }, { "code": null, "e": 94297, "s": 94196, "text": "Following are the steps to follow to enable Akismet Spam Protection plugin for your website or blog." }, { "code": null, "e": 94403, "s": 94297, "text": "Step (1) − Go to your WordPress admin area → Plugins → Installed. The following screen will be displayed." }, { "code": null, "e": 94473, "s": 94403, "text": "Step (2) − Click on Activate button as shown in the following screen." }, { "code": null, "e": 94610, "s": 94473, "text": "Step (3) − The Akismet plugin will be activated and then Click on Activate your Akismet account button as shown in the following screen." }, { "code": null, "e": 94744, "s": 94610, "text": "Step (4) − Click on Get your API key as seen in the following screen to get a new key or enter manually, if you already have API key." }, { "code": null, "e": 94840, "s": 94744, "text": "Step (5) − If you don't have API key then, click on GET AN AKISMET API KEY tab to move further." }, { "code": null, "e": 94941, "s": 94840, "text": "Step (6) − Fill up the required fields and click on Sign up button as shown in the following screen." }, { "code": null, "e": 95134, "s": 94941, "text": "Step (7) − Once you complete with signup process. You will get an API key in your registered e-mail id. Enter API key manually and click on Use this key button as seen in the following screen." }, { "code": null, "e": 95282, "s": 95134, "text": "Step (8) − If you have entered a correct API key, it will be verified and you will get a confirmation message as reflected in the following screen." }, { "code": null, "e": 95488, "s": 95282, "text": "Step (9) − Now your blog will be protected from spam by Akismet. You will be able to check the comments in your blog for spam, as well as manually mark comments as spam from the blog admin area → Comments." }, { "code": null, "e": 95695, "s": 95488, "text": "You can keep a track of how many spam posts have been stopped by Akismet and you can secure your posts, blogs, comments, etc. Furthermore, you can prevent your website from spammers, who can harm your site." }, { "code": null, "e": 95840, "s": 95695, "text": "In this chapter, we will study how to Backup & Restore files and database in WordPress. In WordPress there are two parts of backing up such as −" }, { "code": null, "e": 95863, "s": 95840, "text": "WordPress Files Backup" }, { "code": null, "e": 95889, "s": 95863, "text": "WordPress Database Backup" }, { "code": null, "e": 95913, "s": 95889, "text": "WordPress Files Restore" }, { "code": null, "e": 95940, "s": 95913, "text": "WordPress Database Restore" }, { "code": null, "e": 96031, "s": 95940, "text": "To get the backup files of WordPress, you need to install FileZilla Client on your system." }, { "code": null, "e": 96109, "s": 96031, "text": "Following are the simple steps used for files backup operation in WordPress −" }, { "code": null, "e": 96184, "s": 96109, "text": "Step (1) − Open the FileZilla Client as shown in the following screenshot." }, { "code": null, "e": 96284, "s": 96184, "text": "Step (2) − Enter the Host, Username, Password and Port like you have used to log-in to your cPanel." }, { "code": null, "e": 96344, "s": 96284, "text": "After filling all the fields, click on Quickconnect button." }, { "code": null, "e": 96464, "s": 96344, "text": "Step (3) − You will get all files and folders of your WordPress site on the right side as seen in the following screen." }, { "code": null, "e": 96560, "s": 96464, "text": "Step (4) − Select all the files and folders and right click on the mouse and click on Download." }, { "code": null, "e": 96644, "s": 96560, "text": "After downloading the WordPress files from cPanel, it will be saved on your system." }, { "code": null, "e": 96710, "s": 96644, "text": "Following are the simple steps for database backup in WordPress −" }, { "code": null, "e": 96815, "s": 96710, "text": "Step (1) − Type the path http://localhost/phpmyadmin in your browser. You will get the following screen." }, { "code": null, "e": 96903, "s": 96815, "text": "Step (2) − Click on the database name ‘wordpress’ which you have created for WordPress." }, { "code": null, "e": 97007, "s": 96903, "text": "Step (3) − After clicking on database wordpress, it will open the following page. Click on Export tab." }, { "code": null, "e": 97143, "s": 97007, "text": "Step (4) − You will get two methods to export the database i.e. Quick and Custom. Select any one of the methods and click on Go button." }, { "code": null, "e": 97212, "s": 97143, "text": "After exporting the database file, it will get saved on your system." }, { "code": null, "e": 97294, "s": 97212, "text": "Following are the simple steps used to restore the files in WordPress using ftp −" }, { "code": null, "e": 97398, "s": 97294, "text": "Step (1) − Open the FileZilla Client and login to your site using ftp as shown in the following screen." }, { "code": null, "e": 97522, "s": 97398, "text": "Step (2) − Open the local directory in ftp and upload all WordPress files to your website as shown in the following screen." }, { "code": null, "e": 97696, "s": 97522, "text": "Step (3) − Then, go to your wordpress folder → wp-config.php file. Copy and rename wp-config.php file before editing, in case of some mistake you can restore this file back." }, { "code": null, "e": 97755, "s": 97696, "text": "Open the wp-config.php file and locate the following code." }, { "code": null, "e": 97785, "s": 97755, "text": "define('DB_NAME', 'db_name');" }, { "code": null, "e": 97853, "s": 97785, "text": "Replace the db_name with your database name which you have created." }, { "code": null, "e": 97883, "s": 97853, "text": "define('DB_USER', 'db_user');" }, { "code": null, "e": 97932, "s": 97883, "text": "Replace the db_user with your username of MySql." }, { "code": null, "e": 97970, "s": 97932, "text": "define('DB_PASSWORD', 'db_password');" }, { "code": null, "e": 98023, "s": 97970, "text": "Replace the db_password with your password of MySql." }, { "code": null, "e": 98112, "s": 98023, "text": "Save your wp-config file after editing and upload it to your WordPress site through ftp." }, { "code": null, "e": 98180, "s": 98112, "text": "Following are the steps used to restore the database in WordPress −" }, { "code": null, "e": 98283, "s": 98180, "text": "Step (1) − Type the path http://localhost/phpmyadmin in the browser. The following screen will pop up." }, { "code": null, "e": 98361, "s": 98283, "text": "You can create a new database or import your backup in the existing database." }, { "code": null, "e": 98448, "s": 98361, "text": "Here we'll create a new database name, i.e., new_wordpress and click on Create button." }, { "code": null, "e": 98570, "s": 98448, "text": "Step (2) − You can view your created database as shown in the following screen. Click on the database name new_wordpress." }, { "code": null, "e": 98598, "s": 98570, "text": "Step (3) − Click on Import." }, { "code": null, "e": 98766, "s": 98598, "text": "Step (4) − Click on Choose File button to select the backup file from your system. After uploading the sql file, select format as SQL as shown in the following screen." }, { "code": null, "e": 98786, "s": 98766, "text": "Click on Go button." }, { "code": null, "e": 98887, "s": 98786, "text": "Step (5) − Once you click on Go, you will get a message after the sql file is uploaded successfully." }, { "code": null, "e": 98950, "s": 98887, "text": "In this chapter, we will study how to Optimize WordPress site." }, { "code": null, "e": 99010, "s": 98950, "text": "Here are a few simple tips to optimize your WordPress site." }, { "code": null, "e": 99054, "s": 99010, "text": "Ensure high quality and meaningful content." }, { "code": null, "e": 99087, "s": 99054, "text": "Have the right names for images." }, { "code": null, "e": 99131, "s": 99087, "text": "Use short permalinks that contain keywords." }, { "code": null, "e": 99154, "s": 99131, "text": "Have optimized themes." }, { "code": null, "e": 99187, "s": 99154, "text": "Sitemap should be in XML format." }, { "code": null, "e": 99221, "s": 99187, "text": "Connect posts to social networks." }, { "code": null, "e": 99253, "s": 99221, "text": "Beware of black hat techniques." }, { "code": null, "e": 99276, "s": 99253, "text": "Delete your trash box." }, { "code": null, "e": 99311, "s": 99276, "text": "Keep Checking Your Site Statistics" }, { "code": null, "e": 99339, "s": 99311, "text": "Keep checking your plugins." }, { "code": null, "e": 99375, "s": 99339, "text": "Use CSS and JavaScript effectively." }, { "code": null, "e": 99625, "s": 99375, "text": "Any page you create, the most important thing that matters is the content. You must have good content with keywords that can be helpful for users, not for the search engines. Content should be understandable and not complicated or difficult to read." }, { "code": null, "e": 99889, "s": 99625, "text": "The names you choose for your images must be unique; consider choosing images keeping the user in mind. Use keywords that might be helpful for the users. Have some specific names for your images and don’t forget to add your alt tags and title tags to your images." }, { "code": null, "e": 100106, "s": 99889, "text": "For example − If your image is about Chocolate sundae Ice-cream then do not mention the name as DSC12346, instead put it as ‘Chocolate-sundae-High-street-restaurant-new-york.jpg’. This would be much easier to search." }, { "code": null, "e": 100273, "s": 100106, "text": "The permalinks you use must be understandable. For example − http://www.mywebsite.com/tutorialspoint/telangana/ instead of http://www.mywebsite.com/page-id?5631456325" }, { "code": null, "e": 100399, "s": 100273, "text": "Use those themes that are fast and are optimized for WordPress so that when applied to a website, it must not have low speed." }, { "code": null, "e": 100536, "s": 100399, "text": "Google has many tools that can be useful. Tools like Website Optimizer, Webmaster Central, and Google XML sitemaps are very easy to use." }, { "code": null, "e": 100751, "s": 100536, "text": "Social media is a very important aspect today. So have them connected to your blog posts, pages, etc., to have good ranks and popularity. Help promote others posts and pages too and they will do the same in return." }, { "code": null, "e": 100932, "s": 100751, "text": "Don’t trick Google as it finds you in no time. Don’t put yourself in trouble and create problems for your site by using black hat techniques. Be sure to use genuine SEO techniques." }, { "code": null, "e": 101026, "s": 100932, "text": "Always consider clearing your trash for more speed and to have a good flow with your website." }, { "code": null, "e": 101236, "s": 101026, "text": "Size of page matters a lot. The more images, flash, videos or media related posts on your page, the more it would be slower to load. Yslowi> module plugin is recommended to help you get a faster page browsing." }, { "code": null, "e": 101429, "s": 101236, "text": "Having many plugins in WordPress may also be the reason for your page to slow load. So keep a check on your plugins which you’re working on. Consider checking your plugins before you add them." }, { "code": null, "e": 101660, "s": 101429, "text": "Always keep your CSS at the upper side of the page and JavaScript at the bottom. Let CSS load first and then JavaScript. Here is a plugin that will help you get your JavaScript’s at the bottom of the page. It is Footer javaScript." }, { "code": null, "e": 101791, "s": 101660, "text": "In this chapter, we will learn how to reset your passwords in WordPress. We have two methods of resetting passwords in WordPress −" }, { "code": null, "e": 101796, "s": 101791, "text": "User" }, { "code": null, "e": 101801, "s": 101796, "text": "User" }, { "code": null, "e": 101820, "s": 101801, "text": "Lost your password" }, { "code": null, "e": 101839, "s": 101820, "text": "Lost your password" }, { "code": null, "e": 101896, "s": 101839, "text": "Let's look how to set password through the User section." }, { "code": null, "e": 101994, "s": 101896, "text": "Step (1) − Login to your wordPress admin panel and click on Users → All Users from the dashboard." }, { "code": null, "e": 102144, "s": 101994, "text": "Step (2) − When you click on All Users you get a page with a list of users. From this select the one you want to reset password of and click on edit." }, { "code": null, "e": 102203, "s": 102144, "text": "When you click on edit, the following page gets displayed." }, { "code": null, "e": 102281, "s": 102203, "text": "Now let's look into resetting your password using Lost your password section." }, { "code": null, "e": 102445, "s": 102281, "text": "Step (3) − In this page you can type in your new password that must contain 7 characters. Once you are done with setting your new password click on Update Profile." }, { "code": null, "e": 102602, "s": 102445, "text": "Step (3.1) − When you try logging into your WordPress admin panel, you forget your password and need to reset it, you get the following message on the page." }, { "code": null, "e": 102717, "s": 102602, "text": "Step (3.2) − Click on Lost your password? The following page appears. Update your e-mail and say Get New Password." }, { "code": null, "e": 102829, "s": 102717, "text": "Step (3.3) − After you click, you get a message saying a Link has been sent to the e-mail address you provided." }, { "code": null, "e": 102950, "s": 102829, "text": "Step (3.4) − Go to your e-mail and open the (Wordpress Site) Password Reset mail and click on the link that is provided." }, { "code": null, "e": 103047, "s": 102950, "text": "Step (3.5) − Type your new password, confirm again if required and then click on Reset Password." }, { "code": null, "e": 103080, "s": 103047, "text": "\n 57 Lectures \n 2 hours \n" }, { "code": null, "e": 103092, "s": 103080, "text": " Amit Diwan" }, { "code": null, "e": 103127, "s": 103092, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 103141, "s": 103127, "text": " Sasha Miller" }, { "code": null, "e": 103176, "s": 103141, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 103189, "s": 103176, "text": " Zach Miller" }, { "code": null, "e": 103222, "s": 103189, "text": "\n 45 Lectures \n 2 hours \n" }, { "code": null, "e": 103235, "s": 103222, "text": " Zach Miller" }, { "code": null, "e": 103268, "s": 103235, "text": "\n 19 Lectures \n 4 hours \n" }, { "code": null, "e": 103296, "s": 103268, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 103333, "s": 103296, "text": "\n 145 Lectures \n 12.5 hours \n" }, { "code": null, "e": 103348, "s": 103333, "text": " Theo McArthur" }, { "code": null, "e": 103355, "s": 103348, "text": " Print" }, { "code": null, "e": 103366, "s": 103355, "text": " Add Notes" } ]
How to add space between two widgets placed in a grid in tkinter?
Let us assume that we are creating a tkinter application where two or more widgets are placed using a grid property. We have to add some space between the widgets in order to style their appearance. To provide space in the widgets, we can use padding property, as padding adds space to the outermost part of the widget. In order to add padding, assign the values to padx and pady. #Import the required library from tkinter import * #create an instance of tkinter frame win= Tk() win.geometry("750x250") #Create some Button widgets Label(win, text= "New Line Text", font= ('Helvetica 20 bold')).grid(row=0, column=5, padx= 25, pady= 25) Button(win, text= "Button 1").grid(row=0, column=1, padx= 50, pady= 80) Button(win, text= "Button 2").grid(row=0, column=2, padx= 25, pady =36) win.mainloop()
[ { "code": null, "e": 1443, "s": 1062, "text": "Let us assume that we are creating a tkinter application where two or more widgets are placed using a grid property. We have to add some space between the widgets in order to style their appearance. To provide space in the widgets, we can use padding property, as padding adds space to the outermost part of the widget. In order to add padding, assign the values to padx and pady." }, { "code": null, "e": 1857, "s": 1443, "text": "#Import the required library\nfrom tkinter import *\n#create an instance of tkinter frame\nwin= Tk()\nwin.geometry(\"750x250\")\n#Create some Button widgets\nLabel(win, text= \"New Line Text\", font= ('Helvetica 20 bold')).grid(row=0, column=5, padx= 25, pady= 25)\nButton(win, text= \"Button 1\").grid(row=0, column=1, padx= 50, pady= 80)\nButton(win, text= \"Button 2\").grid(row=0, column=2, padx= 25, pady =36)\nwin.mainloop()" } ]
JavaScript Arrays
An array is a special variable, which can hold more than one value: If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is an array! An array can hold many values under a single name, and you can access the values by referring to an index number. Using an array literal is the easiest way to create a JavaScript Array. Syntax: It is a common practice to declare arrays with the const keyword. Learn more about const with arrays in the chapter: JS Array Const. Spaces and line breaks are not important. A declaration can span multiple lines: You can also create an array, and then provide the elements: The following example also creates an Array, and assigns values to it: The two examples above do exactly the same. There is no need to use new Array(). For simplicity, readability and execution speed, use the array literal method. You access an array element by referring to the index number: Note: Array indexes start with 0. [0] is the first element. [1] is the second element. This statement changes the value of the first element in cars: With JavaScript, the full array can be accessed by referring to the array name: Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements". In this example, person[0] returns John: Objects use names to access its "members". In this example, person.firstName returns John: JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array. You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array: The real strength of JavaScript arrays are the built-in array properties and methods: Array methods are covered in the next chapters. The length property of an array returns the length of an array (the number of array elements). The length property is always one more than the highest array index. One way to loop through an array, is using a for loop: You can also use the Array.forEach() function: The easiest way to add a new element to an array is using the push() method: New element can also be added to an array using the length property: WARNING ! Adding elements with high indexes can create undefined "holes" in an array: Many programming languages support arrays with named indexes. Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays with named indexes. In JavaScript, arrays always use numbered indexes. WARNING !! If you use named indexes, JavaScript will redefine the array to an object. After that, some array methods and properties will produce incorrect results. In JavaScript, arrays use numbered indexes. In JavaScript, objects use named indexes. Arrays are a special kind of objects, with numbered indexes. JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers. JavaScript has a built in array constructor new Array(). But you can safely use [] instead. These two different statements both create a new empty array named points: These two different statements both create a new array containing 6 numbers: The new keyword can produce some unexpected results: is not the same as: A common question is: How do I know if a variable is an array? The problem is that the JavaScript operator typeof returns "object": The typeof operator returns object because a JavaScript array is an object. To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method Array.isArray(): The instanceof operator returns true if an object is created by a given constructor: For a complete Array reference, go to our: Complete JavaScript Array Reference. The reference contains descriptions and examples of all Array properties and methods. Get the value "Volvo" from the cars array. const cars = ["Saab", "Volvo", "BMW"]; let x = ; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 68, "s": 0, "text": "An array is a special variable, which can hold more than one value:" }, { "code": null, "e": 192, "s": 68, "text": "If you have a list of items (a list of car names, for example), storing the \ncars in single variables could look like this:" }, { "code": null, "e": 310, "s": 192, "text": "However, what if you want to loop through the cars and find a specific one? \nAnd what if you had not 3 cars, but 300?" }, { "code": null, "e": 336, "s": 310, "text": "The solution is an array!" }, { "code": null, "e": 451, "s": 336, "text": "An array can hold many values under a single name, and you can \naccess the values by referring to an index number." }, { "code": null, "e": 523, "s": 451, "text": "Using an array literal is the easiest way to create a JavaScript Array." }, { "code": null, "e": 532, "s": 523, "text": "Syntax: " }, { "code": null, "e": 598, "s": 532, "text": "It is a common practice to declare arrays with the const keyword." }, { "code": null, "e": 665, "s": 598, "text": "Learn more about const with arrays in the chapter: JS Array Const." }, { "code": null, "e": 746, "s": 665, "text": "Spaces and line breaks are not important. A declaration can span multiple lines:" }, { "code": null, "e": 807, "s": 746, "text": "You can also create an array, and then provide the elements:" }, { "code": null, "e": 878, "s": 807, "text": "The following example also creates an Array, and assigns values to it:" }, { "code": null, "e": 922, "s": 878, "text": "The two examples above do exactly the same." }, { "code": null, "e": 959, "s": 922, "text": "There is no need to use new Array()." }, { "code": null, "e": 1038, "s": 959, "text": "For simplicity, readability and execution speed, use the array literal method." }, { "code": null, "e": 1100, "s": 1038, "text": "You access an array element by referring to the index number:" }, { "code": null, "e": 1134, "s": 1100, "text": "Note: Array indexes start with 0." }, { "code": null, "e": 1187, "s": 1134, "text": "[0] is the first element.\n[1] is the second element." }, { "code": null, "e": 1250, "s": 1187, "text": "This statement changes the value of the first element in cars:" }, { "code": null, "e": 1331, "s": 1250, "text": "With JavaScript, the full array can be accessed by referring to the array \nname:" }, { "code": null, "e": 1433, "s": 1331, "text": "Arrays are a special type of objects. The typeof operator in JavaScript returns \"object\" for \narrays." }, { "code": null, "e": 1486, "s": 1433, "text": "But, JavaScript arrays are best described as arrays." }, { "code": null, "e": 1574, "s": 1486, "text": "Arrays use numbers to access its \"elements\". In this \nexample, person[0] \nreturns John:" }, { "code": null, "e": 1667, "s": 1574, "text": "Objects use names to access its \"members\". In this example, \nperson.firstName \nreturns John:" }, { "code": null, "e": 1741, "s": 1667, "text": "JavaScript variables can be objects. Arrays are special kinds of objects." }, { "code": null, "e": 1820, "s": 1741, "text": "Because of this, you can have variables of different types in the \nsame Array." }, { "code": null, "e": 1924, "s": 1820, "text": "You can have objects in an Array. You can have functions in an Array. You can \nhave arrays in an Array:" }, { "code": null, "e": 2011, "s": 1924, "text": "The real strength of JavaScript arrays are the built-in array properties and \nmethods:" }, { "code": null, "e": 2059, "s": 2011, "text": "Array methods are covered in the next chapters." }, { "code": null, "e": 2155, "s": 2059, "text": "The length property of an array returns the length of an array (the number of array \nelements)." }, { "code": null, "e": 2224, "s": 2155, "text": "The length property is always one more than the highest array index." }, { "code": null, "e": 2279, "s": 2224, "text": "One way to loop through an array, is using a for loop:" }, { "code": null, "e": 2326, "s": 2279, "text": "You can also use the Array.forEach() function:" }, { "code": null, "e": 2403, "s": 2326, "text": "The easiest way to add a new element to an array is using the push() method:" }, { "code": null, "e": 2472, "s": 2403, "text": "New element can also be added to an array using the length property:" }, { "code": null, "e": 2483, "s": 2472, "text": "WARNING !\n" }, { "code": null, "e": 2559, "s": 2483, "text": "Adding elements with high indexes can create undefined \"holes\" in an array:" }, { "code": null, "e": 2621, "s": 2559, "text": "Many programming languages support arrays with named indexes." }, { "code": null, "e": 2691, "s": 2621, "text": "Arrays with named indexes are called associative \narrays (or hashes)." }, { "code": null, "e": 2746, "s": 2691, "text": "JavaScript does not support arrays with named indexes." }, { "code": null, "e": 2800, "s": 2746, "text": "In JavaScript, arrays always use numbered indexes. " }, { "code": null, "e": 2886, "s": 2800, "text": "WARNING !!\nIf you use named indexes, JavaScript will redefine the array to an object." }, { "code": null, "e": 2965, "s": 2886, "text": "After that, some array methods and properties will produce incorrect \nresults." }, { "code": null, "e": 3012, "s": 2965, "text": "In JavaScript, arrays use numbered indexes. " }, { "code": null, "e": 3054, "s": 3012, "text": "In JavaScript, objects use named indexes." }, { "code": null, "e": 3115, "s": 3054, "text": "Arrays are a special kind of objects, with numbered indexes." }, { "code": null, "e": 3163, "s": 3115, "text": "JavaScript does not support associative arrays." }, { "code": null, "e": 3241, "s": 3163, "text": "You should use objects when you want the element names to be \nstrings (text)." }, { "code": null, "e": 3310, "s": 3241, "text": "You should use arrays when you want the element names to be\nnumbers." }, { "code": null, "e": 3367, "s": 3310, "text": "JavaScript has a built in array constructor new Array()." }, { "code": null, "e": 3402, "s": 3367, "text": "But you can safely use [] instead." }, { "code": null, "e": 3477, "s": 3402, "text": "These two different statements both create a new empty array named points:" }, { "code": null, "e": 3554, "s": 3477, "text": "These two different statements both create a new array containing 6 numbers:" }, { "code": null, "e": 3607, "s": 3554, "text": "The new keyword can produce some unexpected results:" }, { "code": null, "e": 3627, "s": 3607, "text": "is not the same as:" }, { "code": null, "e": 3690, "s": 3627, "text": "A common question is: How do I know if a variable is an array?" }, { "code": null, "e": 3760, "s": 3690, "text": "The problem is that the JavaScript operator typeof returns \n\"object\":" }, { "code": null, "e": 3838, "s": 3760, "text": "The typeof operator returns object because a JavaScript array is an \nobject. " }, { "code": null, "e": 3929, "s": 3838, "text": "To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method Array.isArray():" }, { "code": null, "e": 4015, "s": 3929, "text": "The instanceof operator returns true if an object is created \nby a given constructor:" }, { "code": null, "e": 4058, "s": 4015, "text": "For a complete Array reference, go to our:" }, { "code": null, "e": 4095, "s": 4058, "text": "Complete JavaScript Array Reference." }, { "code": null, "e": 4182, "s": 4095, "text": "The reference contains descriptions and examples of all Array \nproperties and methods." }, { "code": null, "e": 4225, "s": 4182, "text": "Get the value \"Volvo\" from the cars array." }, { "code": null, "e": 4275, "s": 4225, "text": "const cars = [\"Saab\", \"Volvo\", \"BMW\"];\nlet x = ;\n" }, { "code": null, "e": 4294, "s": 4275, "text": "Start the Exercise" }, { "code": null, "e": 4327, "s": 4294, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 4369, "s": 4327, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 4476, "s": 4369, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 4495, "s": 4476, "text": "help@w3schools.com" } ]
Add column names to dataframe in Pandas - GeeksforGeeks
01 Aug, 2020 Let us how to add names to DataFrame columns in Pandas. Creating the DataFrame : # importing the pandas libraryimport pandas as pd # creating listsl1 =["Amar", "Barsha", "Carlos", "Tanmay", "Misbah"]l2 =["Alpha", "Bravo", "Charlie", "Tango", "Mike"]l3 =[23, 25, 22, 27, 29]l4 =[69, 54, 73, 70, 74] # creating the DataFrameteam = pd.DataFrame(list(zip(l1, l2, l3, l4))) # displaying the DataFrameprint(team) Output : Here we can see that the columns in the DataFrame are unnamed. Adding column name to the DataFrame : We can add columns to an existing DataFrame using its columns attribute. # adding column name to the respective columnsteam.columns =['Name', 'Code', 'Age', 'Weight'] # displaying the DataFrameprint(team) Output : Now the DataFrame has column names. Renaming column name of a DataFrame : We can rename the columns of a DataFrame by using the rename() function. # reanming the DataFrame columnsteam.rename(columns = {'Code':'Code-Name', 'Weight':'Weight in kgs'}, inplace = True) # displaying the DataFrameprint(team) Output : We can see the names of the columns have been changed. 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 Create a Pandas DataFrame from Lists Box Plot in Python using Matplotlib Python | Get dictionary keys as a list Enumerate() in Python Python Dictionary Bar Plot in Matplotlib Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method loops in python Python - Call function from another file
[ { "code": null, "e": 24511, "s": 24483, "text": "\n01 Aug, 2020" }, { "code": null, "e": 24567, "s": 24511, "text": "Let us how to add names to DataFrame columns in Pandas." }, { "code": null, "e": 24592, "s": 24567, "text": "Creating the DataFrame :" }, { "code": "# importing the pandas libraryimport pandas as pd # creating listsl1 =[\"Amar\", \"Barsha\", \"Carlos\", \"Tanmay\", \"Misbah\"]l2 =[\"Alpha\", \"Bravo\", \"Charlie\", \"Tango\", \"Mike\"]l3 =[23, 25, 22, 27, 29]l4 =[69, 54, 73, 70, 74] # creating the DataFrameteam = pd.DataFrame(list(zip(l1, l2, l3, l4))) # displaying the DataFrameprint(team)", "e": 24922, "s": 24592, "text": null }, { "code": null, "e": 24931, "s": 24922, "text": "Output :" }, { "code": null, "e": 24994, "s": 24931, "text": "Here we can see that the columns in the DataFrame are unnamed." }, { "code": null, "e": 25105, "s": 24994, "text": "Adding column name to the DataFrame : We can add columns to an existing DataFrame using its columns attribute." }, { "code": "# adding column name to the respective columnsteam.columns =['Name', 'Code', 'Age', 'Weight'] # displaying the DataFrameprint(team)", "e": 25238, "s": 25105, "text": null }, { "code": null, "e": 25248, "s": 25238, "text": " Output :" }, { "code": null, "e": 25284, "s": 25248, "text": "Now the DataFrame has column names." }, { "code": null, "e": 25395, "s": 25284, "text": "Renaming column name of a DataFrame : We can rename the columns of a DataFrame by using the rename() function." }, { "code": "# reanming the DataFrame columnsteam.rename(columns = {'Code':'Code-Name', 'Weight':'Weight in kgs'}, inplace = True) # displaying the DataFrameprint(team)", "e": 25587, "s": 25395, "text": null }, { "code": null, "e": 25596, "s": 25587, "text": "Output :" }, { "code": null, "e": 25651, "s": 25596, "text": "We can see the names of the columns have been changed." }, { "code": null, "e": 25675, "s": 25651, "text": "Python pandas-dataFrame" }, { "code": null, "e": 25689, "s": 25675, "text": "Python-pandas" }, { "code": null, "e": 25696, "s": 25689, "text": "Python" }, { "code": null, "e": 25794, "s": 25696, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25803, "s": 25794, "text": "Comments" }, { "code": null, "e": 25816, "s": 25803, "text": "Old Comments" }, { "code": null, "e": 25853, "s": 25816, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25889, "s": 25853, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25928, "s": 25889, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25950, "s": 25928, "text": "Enumerate() in Python" }, { "code": null, "e": 25968, "s": 25950, "text": "Python Dictionary" }, { "code": null, "e": 25991, "s": 25968, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26042, "s": 25991, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 26074, "s": 26042, "text": "Python Dictionary keys() method" }, { "code": null, "e": 26090, "s": 26074, "text": "loops in python" } ]
Longest Arithmetic Sequence in C++
Suppose we have an array A of integers, we have to return the length of the longest arithmetic subsequence in A. As you know that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic when B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1). So if the input is like [9,4,7,2,10], then the output will be 3. As the longest subsequence is [4,7,10]. To solve this, we will follow these steps − Make a map dp, n := size of A, set ret := 2 Make a map dp, n := size of A, set ret := 2 for i in range 0 to n – 1for j in range 0 to i – 1diff := A[j] – A[i]dp[i, diff] := 1 + dp[j, diff]ret := max of 1 + dp[i, diff] and ret for i in range 0 to n – 1 for j in range 0 to i – 1diff := A[j] – A[i]dp[i, diff] := 1 + dp[j, diff]ret := max of 1 + dp[i, diff] and ret for j in range 0 to i – 1 diff := A[j] – A[i] diff := A[j] – A[i] dp[i, diff] := 1 + dp[j, diff] dp[i, diff] := 1 + dp[j, diff] ret := max of 1 + dp[i, diff] and ret ret := max of 1 + dp[i, diff] and ret return ret return ret Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int longestArithSeqLength(vector<int>& A) { unordered_map <int, unordered_map <int, int> > dp; int n = A.size(); int ret = 2; for(int i = 0; i < n; i++){ for(int j = 0; j < i; j++){ int diff = A[j] - A[i]; dp[i][diff] = 1 + dp[j][diff]; ret = max(1 + dp[i][diff], ret); } } return ret; } }; main(){ vector<int> v1 = {9,4,7,2,10}; Solution ob; cout << (ob.longestArithSeqLength(v1)); } [9,4,7,2,10] 3
[ { "code": null, "e": 1510, "s": 1062, "text": "Suppose we have an array A of integers, we have to return the length of the longest arithmetic subsequence in A. As you know that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic when B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1). So if the input is like [9,4,7,2,10], then the output will be 3. As the longest subsequence is [4,7,10]." }, { "code": null, "e": 1554, "s": 1510, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1598, "s": 1554, "text": "Make a map dp, n := size of A, set ret := 2" }, { "code": null, "e": 1642, "s": 1598, "text": "Make a map dp, n := size of A, set ret := 2" }, { "code": null, "e": 1779, "s": 1642, "text": "for i in range 0 to n – 1for j in range 0 to i – 1diff := A[j] – A[i]dp[i, diff] := 1 + dp[j, diff]ret := max of 1 + dp[i, diff] and ret" }, { "code": null, "e": 1805, "s": 1779, "text": "for i in range 0 to n – 1" }, { "code": null, "e": 1917, "s": 1805, "text": "for j in range 0 to i – 1diff := A[j] – A[i]dp[i, diff] := 1 + dp[j, diff]ret := max of 1 + dp[i, diff] and ret" }, { "code": null, "e": 1943, "s": 1917, "text": "for j in range 0 to i – 1" }, { "code": null, "e": 1963, "s": 1943, "text": "diff := A[j] – A[i]" }, { "code": null, "e": 1983, "s": 1963, "text": "diff := A[j] – A[i]" }, { "code": null, "e": 2014, "s": 1983, "text": "dp[i, diff] := 1 + dp[j, diff]" }, { "code": null, "e": 2045, "s": 2014, "text": "dp[i, diff] := 1 + dp[j, diff]" }, { "code": null, "e": 2083, "s": 2045, "text": "ret := max of 1 + dp[i, diff] and ret" }, { "code": null, "e": 2121, "s": 2083, "text": "ret := max of 1 + dp[i, diff] and ret" }, { "code": null, "e": 2132, "s": 2121, "text": "return ret" }, { "code": null, "e": 2143, "s": 2132, "text": "return ret" }, { "code": null, "e": 2213, "s": 2143, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2224, "s": 2213, "text": " Live Demo" }, { "code": null, "e": 2788, "s": 2224, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int longestArithSeqLength(vector<int>& A) {\n unordered_map <int, unordered_map <int, int> > dp;\n int n = A.size();\n int ret = 2;\n for(int i = 0; i < n; i++){\n for(int j = 0; j < i; j++){\n int diff = A[j] - A[i];\n dp[i][diff] = 1 + dp[j][diff];\n ret = max(1 + dp[i][diff], ret);\n }\n }\n return ret;\n }\n};\nmain(){\n vector<int> v1 = {9,4,7,2,10};\n Solution ob;\n cout << (ob.longestArithSeqLength(v1));\n}" }, { "code": null, "e": 2801, "s": 2788, "text": "[9,4,7,2,10]" }, { "code": null, "e": 2803, "s": 2801, "text": "3" } ]
How to append list to second list (concatenate lists) in Python?
This can be done in different ways − l1=[1,2,3] l2=[2,3,4] l3=l1+l2 print ('new list', l3) This will print new list [1, 2, 3, 2, 3, 4] l1=[1,2,3] l1=[3,4,5] l1.append(l2) print ('appended list', l1) Here’s the result appended list [3, 4, 5, [2, 3, 4]] l1=[1,2,3] l1=[3,4,5] l1.extend(l2) print ('extended list', l1) The output is as follows − extended list [1, 2, 3, 3, 4, 5] First concatenate list, then use set() function to eliminate duplicates and then use list() function to convert set to list l1=[1,2,3] l2=[3,4,5] l=list(set(l1+l2)) print ('list without duplicates',l) Resulting list object will be list without duplicates [1, 2, 3, 4, 5]
[ { "code": null, "e": 1099, "s": 1062, "text": "This can be done in different ways −" }, { "code": null, "e": 1153, "s": 1099, "text": "l1=[1,2,3]\nl2=[2,3,4]\nl3=l1+l2\nprint ('new list', l3)" }, { "code": null, "e": 1169, "s": 1153, "text": "This will print" }, { "code": null, "e": 1197, "s": 1169, "text": "new list [1, 2, 3, 2, 3, 4]" }, { "code": null, "e": 1261, "s": 1197, "text": "l1=[1,2,3]\nl1=[3,4,5]\nl1.append(l2)\nprint ('appended list', l1)" }, { "code": null, "e": 1279, "s": 1261, "text": "Here’s the result" }, { "code": null, "e": 1314, "s": 1279, "text": "appended list [3, 4, 5, [2, 3, 4]]" }, { "code": null, "e": 1378, "s": 1314, "text": "l1=[1,2,3]\nl1=[3,4,5]\nl1.extend(l2)\nprint ('extended list', l1)" }, { "code": null, "e": 1405, "s": 1378, "text": "The output is as follows −" }, { "code": null, "e": 1438, "s": 1405, "text": "extended list [1, 2, 3, 3, 4, 5]" }, { "code": null, "e": 1562, "s": 1438, "text": "First concatenate list, then use set() function to eliminate duplicates and then use list() function to convert set to list" }, { "code": null, "e": 1639, "s": 1562, "text": "l1=[1,2,3]\nl2=[3,4,5]\nl=list(set(l1+l2))\nprint ('list without duplicates',l)" }, { "code": null, "e": 1669, "s": 1639, "text": "Resulting list object will be" }, { "code": null, "e": 1709, "s": 1669, "text": "list without duplicates [1, 2, 3, 4, 5]" } ]
Converting digits to word format using switch case in C language
Is it possible to convert the given one or two-digit numbers into English words by using the C Programming language? We can easily convert the given two-digit number into English word format with the help of a switch case. Not only two digits, but any number can also convert into English like a statement in C. In this program, we will convert one or two-digit numbers into English word format. Live Demo #include<stdio.h> int main(){ int no; printf("enter any 1 or 2 digit number:"); scanf("%d",&no); if(no<0 || no>=99) //finding out whether enter no is 2 digit or not printf("Invalid number"); else{ printf("entered number:"); switch(no){ case 0:printf("zero"); break; case 10: printf("ten"); break; case 11: printf("eleven"); break; case 12: printf("twelve"); break; case 13: printf("thirteen"); break; case 14: printf("fourteen"); break; case 15: printf("fifteen"); break; case 16: printf("sixteen"); break; case 17: printf("seventeen"); break; case 18: printf("eighteen"); break; case 19: printf("nineteen"); break; default: switch(no/10) //first digit word{ case 2: printf("twenty"); break; case 3: printf("thirty"); break; case 4: printf("forty"); break; case 5: printf("fifty"); break; case 6: printf("sixty"); break; case 7: printf("seventy"); break; case 8: printf("eighty"); break; case 9: printf("ninty"); break; } switch(no%10) //second digit word{ case 1: printf("one"); break; case 2: printf("tw0"); break; case 3: printf("three"); break; case 4: printf("four"); break; case 5: printf("five"); break; case 6: printf("six"); break; case 7: printf("seven"); break; case 8: printf("eight"); break; case 9: printf("nine"); break; } } } } enter any 1 or 2 digit number:83 entered number:eightythree enter any 1 or 2 digit number:6 entered number:six enter any 1 or 2 digit number:548 Invalid number
[ { "code": null, "e": 1179, "s": 1062, "text": "Is it possible to convert the given one or two-digit numbers into English words by using the C Programming language?" }, { "code": null, "e": 1374, "s": 1179, "text": "We can easily convert the given two-digit number into English word format with the help of a switch case. Not only two digits, but any number can also convert into English like a statement in C." }, { "code": null, "e": 1458, "s": 1374, "text": "In this program, we will convert one or two-digit numbers into English word format." }, { "code": null, "e": 1469, "s": 1458, "text": " Live Demo" }, { "code": null, "e": 3481, "s": 1469, "text": "#include<stdio.h>\nint main(){\n int no;\n printf(\"enter any 1 or 2 digit number:\");\n scanf(\"%d\",&no);\n if(no<0 || no>=99) //finding out whether enter no is 2 digit or not\n printf(\"Invalid number\");\n else{\n printf(\"entered number:\");\n switch(no){\n case 0:printf(\"zero\");\n break;\n case 10: printf(\"ten\");\n break;\n case 11: printf(\"eleven\");\n break;\n case 12: printf(\"twelve\");\n break;\n case 13: printf(\"thirteen\");\n break;\n case 14: printf(\"fourteen\");\n break;\n case 15: printf(\"fifteen\");\n break;\n case 16: printf(\"sixteen\");\n break;\n case 17: printf(\"seventeen\");\n break;\n case 18: printf(\"eighteen\");\n break;\n case 19: printf(\"nineteen\");\n break;\n default: switch(no/10) //first digit word{\n case 2: printf(\"twenty\");\n break;\n case 3: printf(\"thirty\");\n break;\n case 4: printf(\"forty\");\n break;\n case 5: printf(\"fifty\");\n break;\n case 6: printf(\"sixty\");\n break;\n case 7: printf(\"seventy\");\n break;\n case 8: printf(\"eighty\");\n break;\n case 9: printf(\"ninty\");\n break;\n }\n switch(no%10) //second digit word{\n case 1: printf(\"one\");\n break;\n case 2: printf(\"tw0\");\n break;\n case 3: printf(\"three\");\n break;\n case 4: printf(\"four\");\n break;\n case 5: printf(\"five\");\n break;\n case 6: printf(\"six\");\n break;\n case 7: printf(\"seven\");\n break;\n case 8: printf(\"eight\");\n break;\n case 9: printf(\"nine\");\n break;\n }\n }\n }\n}" }, { "code": null, "e": 3643, "s": 3481, "text": "enter any 1 or 2 digit number:83\nentered number:eightythree\n\nenter any 1 or 2 digit number:6\nentered number:six\n\nenter any 1 or 2 digit number:548\nInvalid number" } ]
Logistic Regression. A gentle introduction to Logistic... | by Sangeet Aggarwal | Towards Data Science
Logistic Regression is one of the fundamental models used in Machine Learning. It is a classification technique and is best suited for predicting the categorical response variable. While linear regression works well with a continuous or quantitative output variable, the Logistic Regression is used to predict a categorical or qualitative output variable. For example, target values like price, sales, temperature, etc are quantitative in nature and thus can be analyzed and predicted using any linear model such as linear regression. But what if we have to predict, whether a mail is a spam or not spam, whether a credit card customer will default or not, whether a given cancer is stage 1, 2, or 3? We cannot use a trivial regression model for such cases, and we need something that can accommodate a qualitative response. Consider the figure below. The plot shows the credit card default status (0 or 1) against the customer’s account balance. Default status 0 means that no default is shown by the customer, and default value 1 means that the customer defaulted. As can be seen in the figure above, the linear regression fit (left) exceeds the possible limits of 0 and 1. This happens because linear regression does not take into account the fact that the values of the response variable are categorical and discrete. It may plot even higher values for a customer having high account balance and vice versa, which does not make any sense. This is why we cannot use linear regression for such problems. Such a problem can be solved by Logistic Regression (right) as it only takes values between 0 and 1. The Logistic Regression is mostly used and best suited for problems having 2 response classes, for example, → 0 or 1, true or false, spam or not spam, type A or type B, etc. Although it can be extended to predict response with more than 2 classes, there are several other ways that are better than Logistic Regression to deal with those problems. Hence, for this post, we will only focus on problems that have two response classes. To understand Logistic Regression, we must understand how it generates results of classification. Does it simply predict the response class? No, it does not. Logistic Regression calculates the probability, by which a sample belongs to a class, given the features in the sample. This probability is calculated for each response class. The class with the highest probability is generally taken to be the predicted class. For a problem with 2 response classes, the probabilities of both classes add to 1 and can be represented as below (taking the class values as 0 and 1). Pr(Class = 1 | Feature(s)) = 1 — Pr(Class = 0 | Feature(s)) Here, Pr(Class=1|Feauture(s)) is read as → the probability of a sample belonging to class 1 with the given feature(s). Since it’s a probability, its value is always between 0 and 1, both inclusive. Recall the equation of Simple Linear Regression. For Logistic Regression, this equation takes such a form, that it only returns values between 0 and 1. This is the Logistic Function, whose values range from 0 to 1 for any value of X. Hence the plot of Logistic Function takes an S-shape with its tails ending towards 0 and 1, with values in between. With few manipulations, the above equation can be rewritten as: The ratio expression on the left-hand side is called the odds and can take values from 0 to infinity. The value of odds close to 0 indicates a very low probability of class 1 (high probability for class 0). A large value of odds indicates a high probability of class 1. Taking log on both sides: The expression on the left is called Logit function or the log-odds function. This logit function is linear in X and can be used to interpret the coefficients of X terms, as we will see later. We will first see how Logistic Regression works when there is a single input variable. We will then learn how the model can be extended to accommodate more input variables. Let’s catch a glimpse of the data we are going to use. This data represents customers of a credit card issuer, with few details like whether or not they are students, their income, balance, and if they were defaulters. The company wants to build a logistic model that can predict whether a customer will default or not. So the default column is our target variable. To build our first logistic model, let’s just consider the balance of a customer as our only predictor. So our model equations will look like these: Let’s build our model using SciKit Learn in Python. from sklearn.linear_model import LogisticRegressionX = data.balance.values.reshape(-1,1)y = data.defaultlogistic = LogisticRegression()logistic.fit(X,y) Plotting the results of the above model, we will get something like this. Let’s check the intercept and coefficient terms. print("Intercept: ",logi.intercept_)print("Coefficient: ",logi.coef_) Output: Intercept: [-5.75236929]Coefficient: [[0.00448445]] These can be interpreted as → For every unit change in balance, the log-odds of default gets multiplied by e0-00445. The intercept term -5.75 can be read as the value of log-odds when the account balance is zero. Let’s now move on to the case where we consider the effect of multiple input variables to predict the default status. The equation for multiple logistic regression can be written as: And the corresponding log-odds function will become: For our model to work, we need to change all categorical inputs into numeric labels. In this case, the student variable has values “Yes ” and “No”. Thus, I have converted these values to 1 and 0, respectively. Let’s have another look at the data before moving on. Let’s fit the model. X_all = data.drop('default',axis=1)y = data.defaultmlr = LogisticRegression()mlr.fit(X_all, y) Check the coefficients. print("Coefficients for stuedent, income and balance are:")for i in range(3): print(round(mlr.coef_[0][i],5))print("Intercept: ", mlr.intercept_[0]) Output: Coefficients for stuedent, income and balance are:-1.63465-5e-050.0047Intercept: -3.8386588181706274 Here, the coefficient value of income is quite low, which indicates that the income of a customer does not really add to the odds of default. We can do further analysis by checking for correlation and other insights to improve the understanding of our data and model. But to maintain the scope of the topic, I’m not adding that part of the analysis here. I hope this post helped you understand the working of Logistic Regression. You can also check the links below for knowing about Linear Regression. For more such posts, please stay tuned. towardsdatascience.com towardsdatascience.com If you are new to Data Science and Machine Learning and wondering where to begin your journey from, do check the link below, where I have mentioned step by step method to learn Data Science, with lots of sources for you to choose from. towardsdatascience.com Can’t wait? If you want to dive right into a course, check out the career tracks in Data Science that suits you, from the link below.
[ { "code": null, "e": 353, "s": 172, "text": "Logistic Regression is one of the fundamental models used in Machine Learning. It is a classification technique and is best suited for predicting the categorical response variable." }, { "code": null, "e": 528, "s": 353, "text": "While linear regression works well with a continuous or quantitative output variable, the Logistic Regression is used to predict a categorical or qualitative output variable." }, { "code": null, "e": 707, "s": 528, "text": "For example, target values like price, sales, temperature, etc are quantitative in nature and thus can be analyzed and predicted using any linear model such as linear regression." }, { "code": null, "e": 997, "s": 707, "text": "But what if we have to predict, whether a mail is a spam or not spam, whether a credit card customer will default or not, whether a given cancer is stage 1, 2, or 3? We cannot use a trivial regression model for such cases, and we need something that can accommodate a qualitative response." }, { "code": null, "e": 1239, "s": 997, "text": "Consider the figure below. The plot shows the credit card default status (0 or 1) against the customer’s account balance. Default status 0 means that no default is shown by the customer, and default value 1 means that the customer defaulted." }, { "code": null, "e": 1678, "s": 1239, "text": "As can be seen in the figure above, the linear regression fit (left) exceeds the possible limits of 0 and 1. This happens because linear regression does not take into account the fact that the values of the response variable are categorical and discrete. It may plot even higher values for a customer having high account balance and vice versa, which does not make any sense. This is why we cannot use linear regression for such problems." }, { "code": null, "e": 1779, "s": 1678, "text": "Such a problem can be solved by Logistic Regression (right) as it only takes values between 0 and 1." }, { "code": null, "e": 1953, "s": 1779, "text": "The Logistic Regression is mostly used and best suited for problems having 2 response classes, for example, → 0 or 1, true or false, spam or not spam, type A or type B, etc." }, { "code": null, "e": 2211, "s": 1953, "text": "Although it can be extended to predict response with more than 2 classes, there are several other ways that are better than Logistic Regression to deal with those problems. Hence, for this post, we will only focus on problems that have two response classes." }, { "code": null, "e": 2369, "s": 2211, "text": "To understand Logistic Regression, we must understand how it generates results of classification. Does it simply predict the response class? No, it does not." }, { "code": null, "e": 2630, "s": 2369, "text": "Logistic Regression calculates the probability, by which a sample belongs to a class, given the features in the sample. This probability is calculated for each response class. The class with the highest probability is generally taken to be the predicted class." }, { "code": null, "e": 2782, "s": 2630, "text": "For a problem with 2 response classes, the probabilities of both classes add to 1 and can be represented as below (taking the class values as 0 and 1)." }, { "code": null, "e": 2842, "s": 2782, "text": "Pr(Class = 1 | Feature(s)) = 1 — Pr(Class = 0 | Feature(s))" }, { "code": null, "e": 3040, "s": 2842, "text": "Here, Pr(Class=1|Feauture(s)) is read as → the probability of a sample belonging to class 1 with the given feature(s). Since it’s a probability, its value is always between 0 and 1, both inclusive." }, { "code": null, "e": 3089, "s": 3040, "text": "Recall the equation of Simple Linear Regression." }, { "code": null, "e": 3192, "s": 3089, "text": "For Logistic Regression, this equation takes such a form, that it only returns values between 0 and 1." }, { "code": null, "e": 3390, "s": 3192, "text": "This is the Logistic Function, whose values range from 0 to 1 for any value of X. Hence the plot of Logistic Function takes an S-shape with its tails ending towards 0 and 1, with values in between." }, { "code": null, "e": 3454, "s": 3390, "text": "With few manipulations, the above equation can be rewritten as:" }, { "code": null, "e": 3724, "s": 3454, "text": "The ratio expression on the left-hand side is called the odds and can take values from 0 to infinity. The value of odds close to 0 indicates a very low probability of class 1 (high probability for class 0). A large value of odds indicates a high probability of class 1." }, { "code": null, "e": 3750, "s": 3724, "text": "Taking log on both sides:" }, { "code": null, "e": 3943, "s": 3750, "text": "The expression on the left is called Logit function or the log-odds function. This logit function is linear in X and can be used to interpret the coefficients of X terms, as we will see later." }, { "code": null, "e": 4116, "s": 3943, "text": "We will first see how Logistic Regression works when there is a single input variable. We will then learn how the model can be extended to accommodate more input variables." }, { "code": null, "e": 4335, "s": 4116, "text": "Let’s catch a glimpse of the data we are going to use. This data represents customers of a credit card issuer, with few details like whether or not they are students, their income, balance, and if they were defaulters." }, { "code": null, "e": 4586, "s": 4335, "text": "The company wants to build a logistic model that can predict whether a customer will default or not. So the default column is our target variable. To build our first logistic model, let’s just consider the balance of a customer as our only predictor." }, { "code": null, "e": 4631, "s": 4586, "text": "So our model equations will look like these:" }, { "code": null, "e": 4683, "s": 4631, "text": "Let’s build our model using SciKit Learn in Python." }, { "code": null, "e": 4836, "s": 4683, "text": "from sklearn.linear_model import LogisticRegressionX = data.balance.values.reshape(-1,1)y = data.defaultlogistic = LogisticRegression()logistic.fit(X,y)" }, { "code": null, "e": 4910, "s": 4836, "text": "Plotting the results of the above model, we will get something like this." }, { "code": null, "e": 4959, "s": 4910, "text": "Let’s check the intercept and coefficient terms." }, { "code": null, "e": 5029, "s": 4959, "text": "print(\"Intercept: \",logi.intercept_)print(\"Coefficient: \",logi.coef_)" }, { "code": null, "e": 5037, "s": 5029, "text": "Output:" }, { "code": null, "e": 5089, "s": 5037, "text": "Intercept: [-5.75236929]Coefficient: [[0.00448445]]" }, { "code": null, "e": 5119, "s": 5089, "text": "These can be interpreted as →" }, { "code": null, "e": 5206, "s": 5119, "text": "For every unit change in balance, the log-odds of default gets multiplied by e0-00445." }, { "code": null, "e": 5302, "s": 5206, "text": "The intercept term -5.75 can be read as the value of log-odds when the account balance is zero." }, { "code": null, "e": 5420, "s": 5302, "text": "Let’s now move on to the case where we consider the effect of multiple input variables to predict the default status." }, { "code": null, "e": 5485, "s": 5420, "text": "The equation for multiple logistic regression can be written as:" }, { "code": null, "e": 5538, "s": 5485, "text": "And the corresponding log-odds function will become:" }, { "code": null, "e": 5802, "s": 5538, "text": "For our model to work, we need to change all categorical inputs into numeric labels. In this case, the student variable has values “Yes ” and “No”. Thus, I have converted these values to 1 and 0, respectively. Let’s have another look at the data before moving on." }, { "code": null, "e": 5823, "s": 5802, "text": "Let’s fit the model." }, { "code": null, "e": 5918, "s": 5823, "text": "X_all = data.drop('default',axis=1)y = data.defaultmlr = LogisticRegression()mlr.fit(X_all, y)" }, { "code": null, "e": 5942, "s": 5918, "text": "Check the coefficients." }, { "code": null, "e": 6094, "s": 5942, "text": "print(\"Coefficients for stuedent, income and balance are:\")for i in range(3): print(round(mlr.coef_[0][i],5))print(\"Intercept: \", mlr.intercept_[0])" }, { "code": null, "e": 6102, "s": 6094, "text": "Output:" }, { "code": null, "e": 6203, "s": 6102, "text": "Coefficients for stuedent, income and balance are:-1.63465-5e-050.0047Intercept: -3.8386588181706274" }, { "code": null, "e": 6558, "s": 6203, "text": "Here, the coefficient value of income is quite low, which indicates that the income of a customer does not really add to the odds of default. We can do further analysis by checking for correlation and other insights to improve the understanding of our data and model. But to maintain the scope of the topic, I’m not adding that part of the analysis here." }, { "code": null, "e": 6745, "s": 6558, "text": "I hope this post helped you understand the working of Logistic Regression. You can also check the links below for knowing about Linear Regression. For more such posts, please stay tuned." }, { "code": null, "e": 6768, "s": 6745, "text": "towardsdatascience.com" }, { "code": null, "e": 6791, "s": 6768, "text": "towardsdatascience.com" }, { "code": null, "e": 7027, "s": 6791, "text": "If you are new to Data Science and Machine Learning and wondering where to begin your journey from, do check the link below, where I have mentioned step by step method to learn Data Science, with lots of sources for you to choose from." }, { "code": null, "e": 7050, "s": 7027, "text": "towardsdatascience.com" } ]
Converting string to date in MongoDB?
To convert the string to date in MongoDB, use the following syntax: db.yourCollectionName.aggregate( [ { $project: { anyVariableName: { $dateFromString: { dateString: '$yourFieldName’ } } } } ] ); To understand the above syntax, let us create a collection with some documents. The query to create a collection with documents are as follows: > db.ConvertStringToDateDemo.insertOne({"ArrivalDate":"20-10-2019"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef3596fd07954a489069f") } > db.ConvertStringToDateDemo.insertOne({"ArrivalDate":"21-02-2019"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef3616fd07954a48906a0") } > db.ConvertStringToDateDemo.insertOne({"ArrivalDate":"10-12-2018"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef36d6fd07954a48906a1") } > db.ConvertStringToDateDemo.insertOne({"ArrivalDate":"31-01-2017"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ef37b6fd07954a48906a2") } Display all documents from a collection with the help of find() method. The query is as follows: > db.ConvertStringToDateDemo.find().pretty(); The following is the output: { "_id" : ObjectId("5c6ef3596fd07954a489069f"), "ArrivalDate" : "20-10-2019" } { "_id" : ObjectId("5c6ef3616fd07954a48906a0"), "ArrivalDate" : "21-02-2019" } { "_id" : ObjectId("5c6ef36d6fd07954a48906a1"), "ArrivalDate" : "10-12-2018" } { "_id" : ObjectId("5c6ef37b6fd07954a48906a2"), "ArrivalDate" : "31-01-2017" } Here is the query to convert string to date: > db.ConvertStringToDateDemo.aggregate( [ { ... $project: { ... StringToDate: { ... $dateFromString: { ... dateString: '$ArrivalDate' ... } ... } ... } ... } ] ).pretty(); The following is the output: { "_id" : ObjectId("5c6ef3596fd07954a489069f"), "StringToDate" : ISODate("2019-10-20T00:00:00Z") } { "_id" : ObjectId("5c6ef3616fd07954a48906a0"), "StringToDate" : ISODate("2019-02-21T00:00:00Z") } { "_id" : ObjectId("5c6ef36d6fd07954a48906a1"), "StringToDate" : ISODate("2018-12-10T00:00:00Z") } { "_id" : ObjectId("5c6ef37b6fd07954a48906a2"), "StringToDate" : ISODate("2017-01-31T00:00:00Z") }
[ { "code": null, "e": 1130, "s": 1062, "text": "To convert the string to date in MongoDB, use the following syntax:" }, { "code": null, "e": 1403, "s": 1130, "text": "db.yourCollectionName.aggregate(\n [\n {\n $project:\n {\n anyVariableName:\n {\n $dateFromString:\n {\n dateString: '$yourFieldName’\n }\n }\n }\n }\n ]\n);" }, { "code": null, "e": 1547, "s": 1403, "text": "To understand the above syntax, let us create a collection with some documents. The query to create a collection with documents are as follows:" }, { "code": null, "e": 2167, "s": 1547, "text": "> db.ConvertStringToDateDemo.insertOne({\"ArrivalDate\":\"20-10-2019\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ef3596fd07954a489069f\")\n}\n> db.ConvertStringToDateDemo.insertOne({\"ArrivalDate\":\"21-02-2019\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ef3616fd07954a48906a0\")\n}\n> db.ConvertStringToDateDemo.insertOne({\"ArrivalDate\":\"10-12-2018\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ef36d6fd07954a48906a1\")\n}\n> db.ConvertStringToDateDemo.insertOne({\"ArrivalDate\":\"31-01-2017\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c6ef37b6fd07954a48906a2\")\n}" }, { "code": null, "e": 2264, "s": 2167, "text": "Display all documents from a collection with the help of find() method. The query is as follows:" }, { "code": null, "e": 2310, "s": 2264, "text": "> db.ConvertStringToDateDemo.find().pretty();" }, { "code": null, "e": 2339, "s": 2310, "text": "The following is the output:" }, { "code": null, "e": 2679, "s": 2339, "text": "{\n \"_id\" : ObjectId(\"5c6ef3596fd07954a489069f\"),\n \"ArrivalDate\" : \"20-10-2019\"\n}\n{\n \"_id\" : ObjectId(\"5c6ef3616fd07954a48906a0\"),\n \"ArrivalDate\" : \"21-02-2019\"\n}\n{\n \"_id\" : ObjectId(\"5c6ef36d6fd07954a48906a1\"),\n \"ArrivalDate\" : \"10-12-2018\"\n}\n{\n \"_id\" : ObjectId(\"5c6ef37b6fd07954a48906a2\"),\n \"ArrivalDate\" : \"31-01-2017\"\n}" }, { "code": null, "e": 2724, "s": 2679, "text": "Here is the query to convert string to date:" }, { "code": null, "e": 2944, "s": 2724, "text": "> db.ConvertStringToDateDemo.aggregate( [ {\n... $project: {\n... StringToDate: {\n... $dateFromString: {\n... dateString: '$ArrivalDate'\n... }\n... }\n... }\n... } ] ).pretty();" }, { "code": null, "e": 2973, "s": 2944, "text": "The following is the output:" }, { "code": null, "e": 3393, "s": 2973, "text": "{\n \"_id\" : ObjectId(\"5c6ef3596fd07954a489069f\"),\n \"StringToDate\" : ISODate(\"2019-10-20T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5c6ef3616fd07954a48906a0\"),\n \"StringToDate\" : ISODate(\"2019-02-21T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5c6ef36d6fd07954a48906a1\"),\n \"StringToDate\" : ISODate(\"2018-12-10T00:00:00Z\")\n}\n{\n \"_id\" : ObjectId(\"5c6ef37b6fd07954a48906a2\"),\n \"StringToDate\" : ISODate(\"2017-01-31T00:00:00Z\")\n}" } ]
Inverse t-distribution in R - GeeksforGeeks
06 Jun, 2021 In probability and statistics, Student’s t-distribution (or simply the t-distribution) is any member of a family of continuous probability distributions. It comes to the picture when estimating the mean of a normally distributed population, where the sample size is small and the standard deviation (S.D) is undefined and unknown. The t distribution with df = n degrees of freedom has density If a random variable X has a T-distribution with ν degrees of freedom, then Pr (X ≤ x) = P. Suppose that Z and Y are independent random variables. Let Z be a standard normal random variable (mean of 0, the variance of 1). And Y a chi-square variable with m degrees of freedom. Now, we have, The variable T has the t distribution with m degrees of freedom. Method 1: Using tinv() method PEIP is a package in R which is used to apply many MATLAB translations and computations in R. It is useful for data statistics and mathematical operations. This method is more precise in comparison to the qt() method. The package can be installed into the working space using the following command : install.packages("PEIP") tinv() method of this package is based on the betaincinv function. It is used to compute inverse t-distribution. It returns the quintile for T-distribution. A p-value is a probability that the results from your sample data occurred by chance. Syntax: tinv(p, nu) Arguments : p : P-value nu : degrees of freedom The following code snippet illustrates the calculation of inverse t-distribution considering the random probability of a number 0.4 (p -value) with 2 degrees of freedom : R # loading the required librarylibrary("PEIP") # defining p-valuep <- 0.4nu <- 2print ("Inverse t-distribution")tinv(p, nu) Output: [1] "Inverse t-distribution" [1] -0.2887 Method 2: Using qt() method qt() method in base R is used to return the inverse probability cumulative density of the Student t-distribution, also known as the T-distribution. It is basically a quantile function. Syntax: qt(p, nu ) Arguments : p : vector of probabilities. nu : degrees of freedom The following code snippet illustrates the calculation of inverse t-distribution considering the random probability of an tiny exponential number 1e-20 (p -value) with 2 degrees of freedom. The negative sign illustrates that it is declining in nature much towards the -ve NaN : R # defining p-valuep <- 1e-20nu <- 2 print ("Inverse t-distribution")qt(p, nu) Output: [1] "Inverse t-distribution" [1] -7071067812 A vector of x values is taken in the form of a sequence, considering the number of degrees of freedom to be 15. The corresponding y values can be computed by using qt() method in R. The following code snippet illustrates the usage of this method over a vector of values : R # creating a vecx <- seq(.1, .9, by = .1) # Calling qt() Functiony <- qt(x, 15)print ("inverse t-distribution")print (y) # plotting dataplot (x, y, type = "o") Output: [1] “inverse t-distribution” [1] -1.3406056 -0.8662450 -0.5357291 -0.2578853 0.0000000 0.2578853 0.5357291 0.8662450 1.3406056 Picked R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Control Statements in R Programming Change Color of Bars in Barchart using ggplot2 in R Data Visualization in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? Logistic Regression in R Programming Linear Discriminant Analysis in R Programming How to filter R DataFrame by values in a column? How to change Colors in ggplot2 Line Plot in R ? How to import an Excel File into R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n06 Jun, 2021" }, { "code": null, "e": 25244, "s": 24851, "text": "In probability and statistics, Student’s t-distribution (or simply the t-distribution) is any member of a family of continuous probability distributions. It comes to the picture when estimating the mean of a normally distributed population, where the sample size is small and the standard deviation (S.D) is undefined and unknown. The t distribution with df = n degrees of freedom has density" }, { "code": null, "e": 25536, "s": 25244, "text": "If a random variable X has a T-distribution with ν degrees of freedom, then Pr (X ≤ x) = P. Suppose that Z and Y are independent random variables. Let Z be a standard normal random variable (mean of 0, the variance of 1). And Y a chi-square variable with m degrees of freedom. Now, we have, " }, { "code": null, "e": 25601, "s": 25536, "text": "The variable T has the t distribution with m degrees of freedom." }, { "code": null, "e": 25631, "s": 25601, "text": "Method 1: Using tinv() method" }, { "code": null, "e": 25932, "s": 25631, "text": "PEIP is a package in R which is used to apply many MATLAB translations and computations in R. It is useful for data statistics and mathematical operations. This method is more precise in comparison to the qt() method. The package can be installed into the working space using the following command : " }, { "code": null, "e": 25957, "s": 25932, "text": "install.packages(\"PEIP\")" }, { "code": null, "e": 26200, "s": 25957, "text": "tinv() method of this package is based on the betaincinv function. It is used to compute inverse t-distribution. It returns the quintile for T-distribution. A p-value is a probability that the results from your sample data occurred by chance." }, { "code": null, "e": 26220, "s": 26200, "text": "Syntax: tinv(p, nu)" }, { "code": null, "e": 26233, "s": 26220, "text": "Arguments : " }, { "code": null, "e": 26245, "s": 26233, "text": "p : P-value" }, { "code": null, "e": 26269, "s": 26245, "text": "nu : degrees of freedom" }, { "code": null, "e": 26441, "s": 26269, "text": "The following code snippet illustrates the calculation of inverse t-distribution considering the random probability of a number 0.4 (p -value) with 2 degrees of freedom : " }, { "code": null, "e": 26443, "s": 26441, "text": "R" }, { "code": "# loading the required librarylibrary(\"PEIP\") # defining p-valuep <- 0.4nu <- 2print (\"Inverse t-distribution\")tinv(p, nu)", "e": 26567, "s": 26443, "text": null }, { "code": null, "e": 26575, "s": 26567, "text": "Output:" }, { "code": null, "e": 26617, "s": 26575, "text": "[1] \"Inverse t-distribution\" \n[1] -0.2887" }, { "code": null, "e": 26645, "s": 26617, "text": "Method 2: Using qt() method" }, { "code": null, "e": 26831, "s": 26645, "text": "qt() method in base R is used to return the inverse probability cumulative density of the Student t-distribution, also known as the T-distribution. It is basically a quantile function. " }, { "code": null, "e": 26850, "s": 26831, "text": "Syntax: qt(p, nu )" }, { "code": null, "e": 26862, "s": 26850, "text": "Arguments :" }, { "code": null, "e": 26891, "s": 26862, "text": "p : vector of probabilities." }, { "code": null, "e": 26915, "s": 26891, "text": "nu : degrees of freedom" }, { "code": null, "e": 27194, "s": 26915, "text": "The following code snippet illustrates the calculation of inverse t-distribution considering the random probability of an tiny exponential number 1e-20 (p -value) with 2 degrees of freedom. The negative sign illustrates that it is declining in nature much towards the -ve NaN : " }, { "code": null, "e": 27196, "s": 27194, "text": "R" }, { "code": "# defining p-valuep <- 1e-20nu <- 2 print (\"Inverse t-distribution\")qt(p, nu)", "e": 27275, "s": 27196, "text": null }, { "code": null, "e": 27283, "s": 27275, "text": "Output:" }, { "code": null, "e": 27329, "s": 27283, "text": "[1] \"Inverse t-distribution\" \n[1] -7071067812" }, { "code": null, "e": 27602, "s": 27329, "text": "A vector of x values is taken in the form of a sequence, considering the number of degrees of freedom to be 15. The corresponding y values can be computed by using qt() method in R. The following code snippet illustrates the usage of this method over a vector of values : " }, { "code": null, "e": 27604, "s": 27602, "text": "R" }, { "code": "# creating a vecx <- seq(.1, .9, by = .1) # Calling qt() Functiony <- qt(x, 15)print (\"inverse t-distribution\")print (y) # plotting dataplot (x, y, type = \"o\")", "e": 27766, "s": 27604, "text": null }, { "code": null, "e": 27774, "s": 27766, "text": "Output:" }, { "code": null, "e": 27804, "s": 27774, "text": "[1] “inverse t-distribution” " }, { "code": null, "e": 27907, "s": 27804, "text": "[1] -1.3406056 -0.8662450 -0.5357291 -0.2578853 0.0000000 0.2578853 0.5357291 0.8662450 1.3406056" }, { "code": null, "e": 27914, "s": 27907, "text": "Picked" }, { "code": null, "e": 27927, "s": 27914, "text": "R-Statistics" }, { "code": null, "e": 27938, "s": 27927, "text": "R Language" }, { "code": null, "e": 28036, "s": 27938, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28045, "s": 28036, "text": "Comments" }, { "code": null, "e": 28058, "s": 28045, "text": "Old Comments" }, { "code": null, "e": 28094, "s": 28058, "text": "Control Statements in R Programming" }, { "code": null, "e": 28146, "s": 28094, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28170, "s": 28146, "text": "Data Visualization in R" }, { "code": null, "e": 28205, "s": 28170, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28243, "s": 28205, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28280, "s": 28243, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 28326, "s": 28280, "text": "Linear Discriminant Analysis in R Programming" }, { "code": null, "e": 28375, "s": 28326, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28424, "s": 28375, "text": "How to change Colors in ggplot2 Line Plot in R ?" } ]
SQL Tryit Editor v1.6
SELECT * FROM Customers WHERE City LIKE '[bsp]%'; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 24, "s": 0, "text": "SELECT * FROM Customers" }, { "code": null, "e": 50, "s": 24, "text": "WHERE City LIKE '[bsp]%';" }, { "code": null, "e": 52, "s": 50, "text": "​" }, { "code": null, "e": 115, "s": 52, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 175, "s": 115, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 243, "s": 175, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 281, "s": 243, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 366, "s": 281, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 540, "s": 366, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 591, "s": 540, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 659, "s": 591, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 830, "s": 659, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 930, "s": 830, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 990, "s": 930, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
Check if value exists for a field in a MongoDB document?
To check if value exists for a field in a MongoDB document, you can use find() along with $exists operator. Let us first create a collection with documents − > db.checkIfValueDemo.insertOne({"PlayerName":"John Smith","PlayerScores":[5000,98595858,554343]}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6f507af8e7a4ca6b2ad98") } > db.checkIfValueDemo.insertOne({"PlayerName":"John Doe","PlayerScores":[]}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6f512af8e7a4ca6b2ad99") } > db.checkIfValueDemo.insertOne({"PlayerName":"Carol Taylor","PlayerScores":[7848474,8746345353]}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6f521af8e7a4ca6b2ad9a") } > db.checkIfValueDemo.insertOne({"PlayerName":"David Miller","PlayerScores":[]}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6f531af8e7a4ca6b2ad9b") } Following is the query to display all documents from a collection with the help of find() method − > db.checkIfValueDemo.find().pretty(); This will produce the following output − { "_id" : ObjectId("5cc6f507af8e7a4ca6b2ad98"), "PlayerName" : "John Smith", "PlayerScores" : [ 5000, 98595858, 554343 ] } { "_id" : ObjectId("5cc6f512af8e7a4ca6b2ad99"), "PlayerName" : "John Doe", "PlayerScores" : [ ] } { "_id" : ObjectId("5cc6f521af8e7a4ca6b2ad9a"), "PlayerName" : "Carol Taylor", "PlayerScores" : [ 7848474, 8746345353 ] } { "_id" : ObjectId("5cc6f531af8e7a4ca6b2ad9b"), "PlayerName" : "David Miller", "PlayerScores" : [ ] } Following is the query to check if value exists for a field in a document. Here, we are checking for field 'PlayerScores with value [ ] − > db.checkIfValueDemo.find({'PlayerScores.0' : {$exists: true}}).count(); This will produce the following output 2
[ { "code": null, "e": 1220, "s": 1062, "text": "To check if value exists for a field in a MongoDB document, you can use find() along with $exists operator. Let us first create a collection with documents −" }, { "code": null, "e": 1920, "s": 1220, "text": "> db.checkIfValueDemo.insertOne({\"PlayerName\":\"John Smith\",\"PlayerScores\":[5000,98595858,554343]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cc6f507af8e7a4ca6b2ad98\")\n}\n> db.checkIfValueDemo.insertOne({\"PlayerName\":\"John Doe\",\"PlayerScores\":[]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cc6f512af8e7a4ca6b2ad99\")\n}\n> db.checkIfValueDemo.insertOne({\"PlayerName\":\"Carol Taylor\",\"PlayerScores\":[7848474,8746345353]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cc6f521af8e7a4ca6b2ad9a\")\n}\n> db.checkIfValueDemo.insertOne({\"PlayerName\":\"David Miller\",\"PlayerScores\":[]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cc6f531af8e7a4ca6b2ad9b\")\n}" }, { "code": null, "e": 2019, "s": 1920, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2058, "s": 2019, "text": "> db.checkIfValueDemo.find().pretty();" }, { "code": null, "e": 2099, "s": 2058, "text": "This will produce the following output −" }, { "code": null, "e": 2616, "s": 2099, "text": "{\n \"_id\" : ObjectId(\"5cc6f507af8e7a4ca6b2ad98\"),\n \"PlayerName\" : \"John Smith\",\n \"PlayerScores\" : [\n 5000,\n 98595858,\n 554343\n ]\n}\n{\n \"_id\" : ObjectId(\"5cc6f512af8e7a4ca6b2ad99\"),\n \"PlayerName\" : \"John Doe\",\n \"PlayerScores\" : [ ]\n}\n{\n \"_id\" : ObjectId(\"5cc6f521af8e7a4ca6b2ad9a\"),\n \"PlayerName\" : \"Carol Taylor\",\n \"PlayerScores\" : [\n 7848474,\n 8746345353\n ]\n}\n{\n \"_id\" : ObjectId(\"5cc6f531af8e7a4ca6b2ad9b\"),\n \"PlayerName\" : \"David Miller\",\n \"PlayerScores\" : [ ]\n}" }, { "code": null, "e": 2754, "s": 2616, "text": "Following is the query to check if value exists for a field in a document. Here, we are checking for field 'PlayerScores with value [ ] −" }, { "code": null, "e": 2828, "s": 2754, "text": "> db.checkIfValueDemo.find({'PlayerScores.0' : {$exists: true}}).count();" }, { "code": null, "e": 2867, "s": 2828, "text": "This will produce the following output" }, { "code": null, "e": 2869, "s": 2867, "text": "2" } ]
How to Integrate Salesforce with Python | by hotglue | Towards Data Science
If you’re a B2B developer building a product, one of the earliest product development phases is creating a data integration pipeline to import customer data. In this article, I’ll show you how to leverage Singer’s tap-salesforce to extract data from Salesforce. From there I’ll walk you through how to parse the JSON output data from Singer using target-csv and standardize it using a simple Python script. The code for these examples is available publicly on GitHub here, along with descriptions that mirror the information I’ll walk you through. These samples rely on a few open source Python packages: tap-salesforce: a Singer tap to extract data from Salesforce. More info on GitHub. target-csv: a Singer target which converts input JSON data to CSV files. More info on GitHub. We’ll use the hotglue fork which uses updated dependencies. singer-discover: an open source utility to select streams from a Singer catalog. More info on GitHub. pandas: a widely used open source data analysis and manipulation tool. More info on their site and PyPi. gluestick: a small open source Python package containing util functions for ETL maintained by the hotglue team. More info on PyPi and GitHub. Without further ado, let’s dive in! Singer taps tend to have a lot of dependency conflicts with each other — to avoid dependency hell, I highly recommend running through this example in a virtual environment. # Install JupyterLab if you don't have it already$ pip3 install jupyterlab# Create the virtual env$ python3 -m venv ~/env/tap-salesforce# Activate the virtual env$ source ~/env/tap-salesforce/bin/activate# Install the dependencies$ pip install tap-salesforce git+https://github.com/hotgluexyz/target-csv.git gluestick pandas ipykernel singer-python==5.3.1 https://github.com/chrisgoddard/singer-discover/archive/master.zip# Make our venv available to JupyterLab$ python -m ipykernel install --user --name=tap-salesforce# Create a workspace for this$ mkdir salesforce-integration# Enter the directory$ cd salesforce-integration These commands may vary depending on your OS and Python version. For more info on venvs with Jupyter, check out this TowardsDataScience article. First off, you’re going to need Salesforce OAuth credentials. This process is already well-documented by Salesforce, so I’ll assume you can follow that guide. Now we have to create a Singer config. This will specify our OAuth credentials and some Singer specific settings. Their example config is of the following format: { "client_id": "secret_client_id", "client_secret": "secret_client_secret", "refresh_token": "abc123", "start_date": "2017-11-02T00:00:00Z", "api_type": "BULK", "select_fields_by_default": true} Fill in your credentials, and save this to a file called config.json in the local directory. The first step of getting data from Salesforce is to figure out what data is actually available. Singer taps offer a discover command which prints a JSON object describing all of this. Let’s run it now: # Do the Singer discover and save to catalog.json$ tap-salesforce --config config.json --discover > catalog.json If this worked successfully, your catalog.json should resemble this: # Check discover output$ less catalog.json{ "streams": [ { "stream": "UserProvisioningRequestShare", "tap_stream_id": "UserProvisioningRequestShare", "schema": { "type": "object", "additionalProperties": false, "properties": { "Id": { "type": "string" },... From here, we want to select what objects we actually want to sync. We’ll use the singer-discover utility we downloaded earlier for this. # Switch singer-python version to meet singer-discover dep$ pip install singer-python==5.4.1# Build our selected catalog$ singer-discover --input catalog.json --output properties.json This will launch an interactive utility to select what streams (objects) you want from Salesforce. I am going to select Lead (space) and press enter. This will prompt you the option to select specific fields. I’ll accept the default and press enter. This should give you the following output ? Select fields from stream: `Lead` done (55 selections)INFO Catalog configuration saved. We can now finally get the data from Salesforce using the files we’ve generated, using the following command: # Get Lead data from Salesforce and save as a CSV$ tap-salesforce --config config.json --properties properties.json | target-csv > state.json This will output two files: the CSV containing the data from Salesforce (something like Lead-20210128T125258.csv) a JSON file state.jsontelling tap-salesforcewhat it last synced. This can be fed back to the tap-salesforce in the future to avoid syncing the same data again. Finally! We’ve pulled our data from Salesforce! Not too bad, right? If you wanted to use this in production, you’d have to automate the process of creating the properties.json and likely stick all of this into a Docker container (very similar to how hotglue and Airbyte work). You can follow along with this part directly in the Jupyter Notebook (feel free to clone and try your own transformations). github.com Let’s take a peek at what tap-salesforce gave us. Not too bad, right? Let’s load the data into a Jupyter Notebook and clean the data up a bit. For this article, I’ll keep it very simple but if you’d like to learn about other ETL operations check out my TowardsDataScience article. Let’s launch Jupyter # You may have some issues in Jupyter if you don't do this$ pip install prompt-toolkit==3.0.14# Deactivate the virtualenv$ deactivate# Start Jupyter Lab$ jupyter lab This should start Jupyter in the current directory and open the browser. If all the setup commands worked, you should see tap-salesforce available under the Notebook sections. Let’s create a new Notebook with the tap-salesforce kernel. I am going to name mine salesforce.ipynb Let’s use the gluestick and pandas libraries to load the data and take a look. Our goal here is to be able to easily manipulate the output from tap-salesforce. Now that we have the data in a Panda’s dataframe, you can transform it however you like. Of course, you’re not limited to use Pandas — you could use Spark, or any other Python based data transformation tool you like. This is really just a starting point for a data integration pipeline. If you’re looking to take this further (orchestrating this on the cloud, connecting it to your product) it’s worth taking a look at tools like hotglue and Meltano, both of which aim to make data integration easier for developers. I recently published an article on TowardsDataScience about the pros and cons of building off Singer. I would recommend checking out Airbyte before resolving to build your pipeline off Singer. Feel free to check out the open source hotglue recipes for more samples in the future. Thanks for reading! I’d love to answer any comments or questions below.
[ { "code": null, "e": 330, "s": 172, "text": "If you’re a B2B developer building a product, one of the earliest product development phases is creating a data integration pipeline to import customer data." }, { "code": null, "e": 579, "s": 330, "text": "In this article, I’ll show you how to leverage Singer’s tap-salesforce to extract data from Salesforce. From there I’ll walk you through how to parse the JSON output data from Singer using target-csv and standardize it using a simple Python script." }, { "code": null, "e": 720, "s": 579, "text": "The code for these examples is available publicly on GitHub here, along with descriptions that mirror the information I’ll walk you through." }, { "code": null, "e": 777, "s": 720, "text": "These samples rely on a few open source Python packages:" }, { "code": null, "e": 860, "s": 777, "text": "tap-salesforce: a Singer tap to extract data from Salesforce. More info on GitHub." }, { "code": null, "e": 1014, "s": 860, "text": "target-csv: a Singer target which converts input JSON data to CSV files. More info on GitHub. We’ll use the hotglue fork which uses updated dependencies." }, { "code": null, "e": 1116, "s": 1014, "text": "singer-discover: an open source utility to select streams from a Singer catalog. More info on GitHub." }, { "code": null, "e": 1221, "s": 1116, "text": "pandas: a widely used open source data analysis and manipulation tool. More info on their site and PyPi." }, { "code": null, "e": 1363, "s": 1221, "text": "gluestick: a small open source Python package containing util functions for ETL maintained by the hotglue team. More info on PyPi and GitHub." }, { "code": null, "e": 1399, "s": 1363, "text": "Without further ado, let’s dive in!" }, { "code": null, "e": 1572, "s": 1399, "text": "Singer taps tend to have a lot of dependency conflicts with each other — to avoid dependency hell, I highly recommend running through this example in a virtual environment." }, { "code": null, "e": 2199, "s": 1572, "text": "# Install JupyterLab if you don't have it already$ pip3 install jupyterlab# Create the virtual env$ python3 -m venv ~/env/tap-salesforce# Activate the virtual env$ source ~/env/tap-salesforce/bin/activate# Install the dependencies$ pip install tap-salesforce git+https://github.com/hotgluexyz/target-csv.git gluestick pandas ipykernel singer-python==5.3.1 https://github.com/chrisgoddard/singer-discover/archive/master.zip# Make our venv available to JupyterLab$ python -m ipykernel install --user --name=tap-salesforce# Create a workspace for this$ mkdir salesforce-integration# Enter the directory$ cd salesforce-integration" }, { "code": null, "e": 2344, "s": 2199, "text": "These commands may vary depending on your OS and Python version. For more info on venvs with Jupyter, check out this TowardsDataScience article." }, { "code": null, "e": 2503, "s": 2344, "text": "First off, you’re going to need Salesforce OAuth credentials. This process is already well-documented by Salesforce, so I’ll assume you can follow that guide." }, { "code": null, "e": 2666, "s": 2503, "text": "Now we have to create a Singer config. This will specify our OAuth credentials and some Singer specific settings. Their example config is of the following format:" }, { "code": null, "e": 2867, "s": 2666, "text": "{ \"client_id\": \"secret_client_id\", \"client_secret\": \"secret_client_secret\", \"refresh_token\": \"abc123\", \"start_date\": \"2017-11-02T00:00:00Z\", \"api_type\": \"BULK\", \"select_fields_by_default\": true}" }, { "code": null, "e": 2960, "s": 2867, "text": "Fill in your credentials, and save this to a file called config.json in the local directory." }, { "code": null, "e": 3163, "s": 2960, "text": "The first step of getting data from Salesforce is to figure out what data is actually available. Singer taps offer a discover command which prints a JSON object describing all of this. Let’s run it now:" }, { "code": null, "e": 3276, "s": 3163, "text": "# Do the Singer discover and save to catalog.json$ tap-salesforce --config config.json --discover > catalog.json" }, { "code": null, "e": 3345, "s": 3276, "text": "If this worked successfully, your catalog.json should resemble this:" }, { "code": null, "e": 3752, "s": 3345, "text": "# Check discover output$ less catalog.json{ \"streams\": [ { \"stream\": \"UserProvisioningRequestShare\", \"tap_stream_id\": \"UserProvisioningRequestShare\", \"schema\": { \"type\": \"object\", \"additionalProperties\": false, \"properties\": { \"Id\": { \"type\": \"string\" },..." }, { "code": null, "e": 3890, "s": 3752, "text": "From here, we want to select what objects we actually want to sync. We’ll use the singer-discover utility we downloaded earlier for this." }, { "code": null, "e": 4074, "s": 3890, "text": "# Switch singer-python version to meet singer-discover dep$ pip install singer-python==5.4.1# Build our selected catalog$ singer-discover --input catalog.json --output properties.json" }, { "code": null, "e": 4324, "s": 4074, "text": "This will launch an interactive utility to select what streams (objects) you want from Salesforce. I am going to select Lead (space) and press enter. This will prompt you the option to select specific fields. I’ll accept the default and press enter." }, { "code": null, "e": 4366, "s": 4324, "text": "This should give you the following output" }, { "code": null, "e": 4457, "s": 4366, "text": "? Select fields from stream: `Lead` done (55 selections)INFO Catalog configuration saved." }, { "code": null, "e": 4567, "s": 4457, "text": "We can now finally get the data from Salesforce using the files we’ve generated, using the following command:" }, { "code": null, "e": 4710, "s": 4567, "text": "# Get Lead data from Salesforce and save as a CSV$ tap-salesforce --config config.json --properties properties.json | target-csv > state.json" }, { "code": null, "e": 4738, "s": 4710, "text": "This will output two files:" }, { "code": null, "e": 4824, "s": 4738, "text": "the CSV containing the data from Salesforce (something like Lead-20210128T125258.csv)" }, { "code": null, "e": 4984, "s": 4824, "text": "a JSON file state.jsontelling tap-salesforcewhat it last synced. This can be fed back to the tap-salesforce in the future to avoid syncing the same data again." }, { "code": null, "e": 5261, "s": 4984, "text": "Finally! We’ve pulled our data from Salesforce! Not too bad, right? If you wanted to use this in production, you’d have to automate the process of creating the properties.json and likely stick all of this into a Docker container (very similar to how hotglue and Airbyte work)." }, { "code": null, "e": 5385, "s": 5261, "text": "You can follow along with this part directly in the Jupyter Notebook (feel free to clone and try your own transformations)." }, { "code": null, "e": 5396, "s": 5385, "text": "github.com" }, { "code": null, "e": 5446, "s": 5396, "text": "Let’s take a peek at what tap-salesforce gave us." }, { "code": null, "e": 5677, "s": 5446, "text": "Not too bad, right? Let’s load the data into a Jupyter Notebook and clean the data up a bit. For this article, I’ll keep it very simple but if you’d like to learn about other ETL operations check out my TowardsDataScience article." }, { "code": null, "e": 5698, "s": 5677, "text": "Let’s launch Jupyter" }, { "code": null, "e": 5864, "s": 5698, "text": "# You may have some issues in Jupyter if you don't do this$ pip install prompt-toolkit==3.0.14# Deactivate the virtualenv$ deactivate# Start Jupyter Lab$ jupyter lab" }, { "code": null, "e": 5937, "s": 5864, "text": "This should start Jupyter in the current directory and open the browser." }, { "code": null, "e": 6141, "s": 5937, "text": "If all the setup commands worked, you should see tap-salesforce available under the Notebook sections. Let’s create a new Notebook with the tap-salesforce kernel. I am going to name mine salesforce.ipynb" }, { "code": null, "e": 6301, "s": 6141, "text": "Let’s use the gluestick and pandas libraries to load the data and take a look. Our goal here is to be able to easily manipulate the output from tap-salesforce." }, { "code": null, "e": 6518, "s": 6301, "text": "Now that we have the data in a Panda’s dataframe, you can transform it however you like. Of course, you’re not limited to use Pandas — you could use Spark, or any other Python based data transformation tool you like." }, { "code": null, "e": 6818, "s": 6518, "text": "This is really just a starting point for a data integration pipeline. If you’re looking to take this further (orchestrating this on the cloud, connecting it to your product) it’s worth taking a look at tools like hotglue and Meltano, both of which aim to make data integration easier for developers." }, { "code": null, "e": 7011, "s": 6818, "text": "I recently published an article on TowardsDataScience about the pros and cons of building off Singer. I would recommend checking out Airbyte before resolving to build your pipeline off Singer." } ]
Simple Transformers — Named Entity Recognition with Transformer Models | by Thilina Rajapakse | Towards Data Science
The Simple Transformers library was conceived to make Transformer models easy to use. Transformers are incredibly powerful (not to mention huge) deep learning models which have been hugely successful at tackling a wide variety of Natural Language Processing tasks. Simple Transformers enabled the application of Transformer models to Sequence Classification tasks (binary classification initially, but with multiclass classification added soon after) with only three lines of code. I am delighted to announce that Simple Transformers now supports Named Entity Recognition, another common NLP task, alongside Sequence Classification. Links to other capabilities: Binary Sequence Classification with Simple Transformers Multiclass Sequence Classification with Simple Transformers The Simple Transformers library is built on top of the excellent Transformers library by Hugging Face. The Hugging Face Transformers library is the library for researchers and other people who need extensive control over how things are done. It is also the best choice when you need to stray off the beaten path, do things differently, or do new things altogether. Simple Transformers is, well, a lot simpler. You want to try out that brilliant idea, you want to roll up your sleeves and get to work but the thousands of lines of code full of cryptic (but cool) looking stuff can be intimidating even to a veteran NLP researcher. The core idea behind Simple Transformers is that using Transformers doesn’t need to be difficult (or frustrating). Simple Transformers abstracts away all the complicated setup code while retaining flexibility and room for configuration as far as possible. A Transformer model can be used in just three lines of code, one line for initializing, one for training, and one for evaluation. This post demonstrates how to perform NER using Simple Transformers. All source code is available on the Github Repo. If you have any issues or questions, that’s the place to resolve them. Please do check it out! Install Anaconda or Miniconda Package Manager from hereCreate a new virtual environment and install the required packages.conda create -n transformers python pandas tqdmconda activate transformersIf using cuda:conda install pytorch cudatoolkit=10.0 -c pytorchelse:conda install pytorch cpuonly -c pytorchconda install -c anaconda scipyconda install -c anaconda scikit-learnpip install transformerspip install tensorboardx pip install seqevalInstall simpletransformers.pip install simpletransformers Install Anaconda or Miniconda Package Manager from here Create a new virtual environment and install the required packages.conda create -n transformers python pandas tqdmconda activate transformersIf using cuda:conda install pytorch cudatoolkit=10.0 -c pytorchelse:conda install pytorch cpuonly -c pytorchconda install -c anaconda scipyconda install -c anaconda scikit-learnpip install transformerspip install tensorboardx pip install seqeval Install simpletransformers.pip install simpletransformers To demonstrate Named Entity Recognition, we’ll be using the CoNLL Dataset. Getting hold of this dataset can be a little tricky, but I found a version of it on Kaggle that works for our purpose. Download the dataset from Kaggle.Extract the text files to the data/ directory. (It should contain 3 text files train.txt, valid.txt, test.txt. We’ll be using the train and test files. You can use the valid file to perform hyperparameter tuning to improve model performance. Download the dataset from Kaggle. Extract the text files to the data/ directory. (It should contain 3 text files train.txt, valid.txt, test.txt. We’ll be using the train and test files. You can use the valid file to perform hyperparameter tuning to improve model performance. Simple Transformers’ NER model can be used with either .txt files or with pandas DataFrames. For a usage example with DataFrames, please refer to the minimal start example for NER in the repo docs. When using your own datasets, the input text files should follow the CoNLL format. Each line in the file should contain one word and its related tags separated by a single space each. Simple Transformers assumes the first “word” in a line is the actual word, and that the last “word” in a line is its assigned label. To denote a new sentence, an empty line is added between the last word of the previous sentence and the first word of the next sentence. However, it may be easier to use the DataFrame approach when using custom datasets. We create a NERModel that can be used for training, evaluation, and prediction in NER tasks. The full parameter list for a NERModel object is given below. model_type: The type of model (bert, roberta) model_name: Default Transformer model name or path to a directory containing Transformer model file (pytorch_nodel.bin). labels (optional): A list of all Named Entity labels. If not given, [“O”, “B-MISC”, “I-MISC”, “B-PER”, “I-PER”, “B-ORG”, “I-ORG”, “B-LOC”, “I-LOC”] will be used. args (optional): Default args will be used if this parameter is not provided. If provided, it should be a dict containing the args that should be changed in the default args. use_cuda (optional): Use GPU if available. Setting to False will force model to use CPU only. To load a model a previously saved model instead of a default model, you can change the model_name to the path to a directory which contains a saved model. model = NERModel(‘bert’, ‘path_to_model/’) A NERModel contains a python dict args with many attributes that provide control over hyperparameters. A detailed description of each is provided in the repo docs. The default values are shown below. Any of these attributes can be modified when creating a NERModel or when calling its train_model method by simply passing in a dict containing the key-value pairs to be updated. An example is given below. As promised, training can be done in a single line of code. The train_model method will create a checkpoint (save) of the model at every nth step where n is self.args['save_steps']. Upon completion of training, the final model will be saved to self.args['output_dir']. Loading a saved model is shown below. Again, evaluation is just a single line of code. Here, the three return values are: result: Dictionary containing evaluation results. (eval_loss, precision, recall, f1_score) model_outputs: List of raw model outputs preds_list: List of predicted tags The evaluation results I obtained are given here for reference. {'eval_loss': 0.10684790916955669, 'precision': 0.9023580786026201, 'recall': 0.9153082919914954, 'f1_score': 0.9087870525112148} Not too shabby for a single run with default hyperparameter values! In real-world applications, we often have no idea what the true labels should be. To perform predictions on arbitrary examples, you can use the predict method. This method is fairly similar to the eval_model method except that this takes in a list of text and returns a list of predictions and a list of model outputs. predictions, raw_outputs = model.predict(["Some arbitary sentence"]) Simple Transformers provides a quick and easy way to perform Named Entity Recognition (and other token level classification tasks). To steal a line from the man behind BERT himself, Simple Transformers is “conceptually simple and empirically powerful”.
[ { "code": null, "e": 654, "s": 172, "text": "The Simple Transformers library was conceived to make Transformer models easy to use. Transformers are incredibly powerful (not to mention huge) deep learning models which have been hugely successful at tackling a wide variety of Natural Language Processing tasks. Simple Transformers enabled the application of Transformer models to Sequence Classification tasks (binary classification initially, but with multiclass classification added soon after) with only three lines of code." }, { "code": null, "e": 805, "s": 654, "text": "I am delighted to announce that Simple Transformers now supports Named Entity Recognition, another common NLP task, alongside Sequence Classification." }, { "code": null, "e": 834, "s": 805, "text": "Links to other capabilities:" }, { "code": null, "e": 890, "s": 834, "text": "Binary Sequence Classification with Simple Transformers" }, { "code": null, "e": 950, "s": 890, "text": "Multiclass Sequence Classification with Simple Transformers" }, { "code": null, "e": 1360, "s": 950, "text": "The Simple Transformers library is built on top of the excellent Transformers library by Hugging Face. The Hugging Face Transformers library is the library for researchers and other people who need extensive control over how things are done. It is also the best choice when you need to stray off the beaten path, do things differently, or do new things altogether. Simple Transformers is, well, a lot simpler." }, { "code": null, "e": 1695, "s": 1360, "text": "You want to try out that brilliant idea, you want to roll up your sleeves and get to work but the thousands of lines of code full of cryptic (but cool) looking stuff can be intimidating even to a veteran NLP researcher. The core idea behind Simple Transformers is that using Transformers doesn’t need to be difficult (or frustrating)." }, { "code": null, "e": 1966, "s": 1695, "text": "Simple Transformers abstracts away all the complicated setup code while retaining flexibility and room for configuration as far as possible. A Transformer model can be used in just three lines of code, one line for initializing, one for training, and one for evaluation." }, { "code": null, "e": 2035, "s": 1966, "text": "This post demonstrates how to perform NER using Simple Transformers." }, { "code": null, "e": 2179, "s": 2035, "text": "All source code is available on the Github Repo. If you have any issues or questions, that’s the place to resolve them. Please do check it out!" }, { "code": null, "e": 2678, "s": 2179, "text": "Install Anaconda or Miniconda Package Manager from hereCreate a new virtual environment and install the required packages.conda create -n transformers python pandas tqdmconda activate transformersIf using cuda:conda install pytorch cudatoolkit=10.0 -c pytorchelse:conda install pytorch cpuonly -c pytorchconda install -c anaconda scipyconda install -c anaconda scikit-learnpip install transformerspip install tensorboardx pip install seqevalInstall simpletransformers.pip install simpletransformers" }, { "code": null, "e": 2734, "s": 2678, "text": "Install Anaconda or Miniconda Package Manager from here" }, { "code": null, "e": 3121, "s": 2734, "text": "Create a new virtual environment and install the required packages.conda create -n transformers python pandas tqdmconda activate transformersIf using cuda:conda install pytorch cudatoolkit=10.0 -c pytorchelse:conda install pytorch cpuonly -c pytorchconda install -c anaconda scipyconda install -c anaconda scikit-learnpip install transformerspip install tensorboardx pip install seqeval" }, { "code": null, "e": 3179, "s": 3121, "text": "Install simpletransformers.pip install simpletransformers" }, { "code": null, "e": 3373, "s": 3179, "text": "To demonstrate Named Entity Recognition, we’ll be using the CoNLL Dataset. Getting hold of this dataset can be a little tricky, but I found a version of it on Kaggle that works for our purpose." }, { "code": null, "e": 3648, "s": 3373, "text": "Download the dataset from Kaggle.Extract the text files to the data/ directory. (It should contain 3 text files train.txt, valid.txt, test.txt. We’ll be using the train and test files. You can use the valid file to perform hyperparameter tuning to improve model performance." }, { "code": null, "e": 3682, "s": 3648, "text": "Download the dataset from Kaggle." }, { "code": null, "e": 3924, "s": 3682, "text": "Extract the text files to the data/ directory. (It should contain 3 text files train.txt, valid.txt, test.txt. We’ll be using the train and test files. You can use the valid file to perform hyperparameter tuning to improve model performance." }, { "code": null, "e": 4122, "s": 3924, "text": "Simple Transformers’ NER model can be used with either .txt files or with pandas DataFrames. For a usage example with DataFrames, please refer to the minimal start example for NER in the repo docs." }, { "code": null, "e": 4660, "s": 4122, "text": "When using your own datasets, the input text files should follow the CoNLL format. Each line in the file should contain one word and its related tags separated by a single space each. Simple Transformers assumes the first “word” in a line is the actual word, and that the last “word” in a line is its assigned label. To denote a new sentence, an empty line is added between the last word of the previous sentence and the first word of the next sentence. However, it may be easier to use the DataFrame approach when using custom datasets." }, { "code": null, "e": 4815, "s": 4660, "text": "We create a NERModel that can be used for training, evaluation, and prediction in NER tasks. The full parameter list for a NERModel object is given below." }, { "code": null, "e": 4861, "s": 4815, "text": "model_type: The type of model (bert, roberta)" }, { "code": null, "e": 4982, "s": 4861, "text": "model_name: Default Transformer model name or path to a directory containing Transformer model file (pytorch_nodel.bin)." }, { "code": null, "e": 5144, "s": 4982, "text": "labels (optional): A list of all Named Entity labels. If not given, [“O”, “B-MISC”, “I-MISC”, “B-PER”, “I-PER”, “B-ORG”, “I-ORG”, “B-LOC”, “I-LOC”] will be used." }, { "code": null, "e": 5319, "s": 5144, "text": "args (optional): Default args will be used if this parameter is not provided. If provided, it should be a dict containing the args that should be changed in the default args." }, { "code": null, "e": 5413, "s": 5319, "text": "use_cuda (optional): Use GPU if available. Setting to False will force model to use CPU only." }, { "code": null, "e": 5569, "s": 5413, "text": "To load a model a previously saved model instead of a default model, you can change the model_name to the path to a directory which contains a saved model." }, { "code": null, "e": 5612, "s": 5569, "text": "model = NERModel(‘bert’, ‘path_to_model/’)" }, { "code": null, "e": 5812, "s": 5612, "text": "A NERModel contains a python dict args with many attributes that provide control over hyperparameters. A detailed description of each is provided in the repo docs. The default values are shown below." }, { "code": null, "e": 6017, "s": 5812, "text": "Any of these attributes can be modified when creating a NERModel or when calling its train_model method by simply passing in a dict containing the key-value pairs to be updated. An example is given below." }, { "code": null, "e": 6077, "s": 6017, "text": "As promised, training can be done in a single line of code." }, { "code": null, "e": 6286, "s": 6077, "text": "The train_model method will create a checkpoint (save) of the model at every nth step where n is self.args['save_steps']. Upon completion of training, the final model will be saved to self.args['output_dir']." }, { "code": null, "e": 6324, "s": 6286, "text": "Loading a saved model is shown below." }, { "code": null, "e": 6373, "s": 6324, "text": "Again, evaluation is just a single line of code." }, { "code": null, "e": 6408, "s": 6373, "text": "Here, the three return values are:" }, { "code": null, "e": 6499, "s": 6408, "text": "result: Dictionary containing evaluation results. (eval_loss, precision, recall, f1_score)" }, { "code": null, "e": 6540, "s": 6499, "text": "model_outputs: List of raw model outputs" }, { "code": null, "e": 6575, "s": 6540, "text": "preds_list: List of predicted tags" }, { "code": null, "e": 6639, "s": 6575, "text": "The evaluation results I obtained are given here for reference." }, { "code": null, "e": 6769, "s": 6639, "text": "{'eval_loss': 0.10684790916955669, 'precision': 0.9023580786026201, 'recall': 0.9153082919914954, 'f1_score': 0.9087870525112148}" }, { "code": null, "e": 6837, "s": 6769, "text": "Not too shabby for a single run with default hyperparameter values!" }, { "code": null, "e": 7156, "s": 6837, "text": "In real-world applications, we often have no idea what the true labels should be. To perform predictions on arbitrary examples, you can use the predict method. This method is fairly similar to the eval_model method except that this takes in a list of text and returns a list of predictions and a list of model outputs." }, { "code": null, "e": 7225, "s": 7156, "text": "predictions, raw_outputs = model.predict([\"Some arbitary sentence\"])" } ]
Touch Control and Events in Android - GeeksforGeeks
20 Dec, 2021 Almost all Android phones today are touch-controlled. There are very few phones that do not have a touchscreen. In this article, we will discuss how to handle touch events in Android. Understanding how to work around touch controls and touch events when we tap on our screen is an example of this. We’ll go over how Android’s touch events work internally for any view. So, how exactly do input events work, and what happens when we touch our screen when we have a ViewGroup with multiple views inside it? In this case, we’ll look at a LinearLayout with a button on it, such as: Image #1: The linear layout and the button. What we will be discussing in this geeks for geeks article is, What happens when we press our fingers against the screen?How do we stop touch events?How is touch handled?What are the main touch events that we use in Android to handle touch control?What happens when we press our fingers against the screen? What happens when we press our fingers against the screen? How do we stop touch events? How is touch handled? What are the main touch events that we use in Android to handle touch control? What happens when we press our fingers against the screen? So, when we touch the screen, the activity’s view, also known as DecorView in Android, receives the touch event notification first. Now, we don’t usually work with the DecorView touch. As a result, the touch is transferred to the ViewGroup and then to its children in the XML file. Using dispatchTouchEvent, the ViewGroup in Android transfers the touch event from top to bottom in the ViewGroup hierarchy to its children (). Image #2: The dispatch event module To begin, when we perform a touch action, The touch event is then received by the ViewGroup, and it is intercepted within the ViewGroup using onInterceptTouchEvent (). Geek Tip: If we return true after intercepting, the touch event is not passed to its children; if we return false, the Android eco-system is notified that the ViewGroup wants to dispatch the event to its children, which in our case is a button. In general, if we return true, it means we handled the event within the ViewGroup itself, and there is no need to dispatch to its children. The view we have now is the last view in our view tree, as indicated by the button. As a result, it will no longer be able to pass on the touch event to its children because it no longer has any. So, in button, our last onInterceptTouchEvent would be called. We need to check the hierarchy, of all the views that we take into account and then perform our work. Handling the event is all about the priority assigned to everything, the first, and then it moves towards the ViewGroups. Touch events function similarly to event dispatching, but in reverse order from child to parent. Let’s say we dispatch the event from ViewGroup and intercept it there; the return value (true/false) determines whether the view’s touch is handled on the ViewGroup or the children. Image #3: The dispatchTouchEvent and onTouch So, in this article, the feedback received from the button returns all true, it means that it has been handled and will not be sent to the LinearLayout. When we receive a touch event, it is handled by onTouchEvent, which also has a MotionEvent parameter. Kotlin fun onTouchEvent(event: MotionEvent) The event parameter contains a reference to every task performed in relation to the touch. On the screen of the point on the touch, we can have coordinates such as X and Y points. It even has actions in it, for example, if we tap on the screen, MotionEvent.ACTION DOWN is called, and if we lift our finger, MotionEvent.ACTION UP is called. The action is MotionEvent even if you drag your finger across the screen using MorionEvent.ACTION MOVE. So, when we want to tap the button, the flow on the view occurs. onTouchEvent -> Activity -> dispatchTouchEvent (LinearLayout) -> dispatchTouchEvent (Button) -> onTouchEvent (Button). When we don’t want to tap the button but still want to handle the click on LinearLayout, the flow is as follows: Activity -> dispatchTouchEvent (LinearLayout) -> dispatchTouchEvent(Button) -> onTouchEvent(Button) (will return false) -> onTouchEvent(Button) -> onTouchEvent(Button) (will return false) -> onTouchEvent(Button) (LinearLayout). When working with touch events, we begin by clicking a view and then removing the gesture (in our case, our finger/stylus), after which MotionEvent.ACTION DOWN and MotionEvent.ACTION UP is called.When the initial touch occurs on the ViewGroup and the child is intercepted.MotionEvent.ACTION CANCEL is called on the ViewGroup and the touch event is dispatched to the children.Everything now depends on the return value of onInterceptTouchEvent().The dispatchTouchEvent is dependent on its return value; if it returns true, the dispatcher is canceled; if it returns false, the dispatching of the touch event continues until it is used.And if onTouchEvent() returns true, it means the touch was handled; if it returns false, it means the touch was not handled When working with touch events, we begin by clicking a view and then removing the gesture (in our case, our finger/stylus), after which MotionEvent.ACTION DOWN and MotionEvent.ACTION UP is called. When the initial touch occurs on the ViewGroup and the child is intercepted. MotionEvent.ACTION CANCEL is called on the ViewGroup and the touch event is dispatched to the children. Everything now depends on the return value of onInterceptTouchEvent(). The dispatchTouchEvent is dependent on its return value; if it returns true, the dispatcher is canceled; if it returns false, the dispatching of the touch event continues until it is used. And if onTouchEvent() returns true, it means the touch was handled; if it returns false, it means the touch was not handled Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Flexbox-Layout in Android How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example Fragment Lifecycle in Android How to Change the Background Color After Clicking the Button in Android? How to Get Current Location in Android?
[ { "code": null, "e": 26491, "s": 26463, "text": "\n20 Dec, 2021" }, { "code": null, "e": 27069, "s": 26491, "text": "Almost all Android phones today are touch-controlled. There are very few phones that do not have a touchscreen. In this article, we will discuss how to handle touch events in Android. Understanding how to work around touch controls and touch events when we tap on our screen is an example of this. We’ll go over how Android’s touch events work internally for any view. So, how exactly do input events work, and what happens when we touch our screen when we have a ViewGroup with multiple views inside it? In this case, we’ll look at a LinearLayout with a button on it, such as:" }, { "code": null, "e": 27113, "s": 27069, "text": "Image #1: The linear layout and the button." }, { "code": null, "e": 27176, "s": 27113, "text": "What we will be discussing in this geeks for geeks article is," }, { "code": null, "e": 27420, "s": 27176, "text": "What happens when we press our fingers against the screen?How do we stop touch events?How is touch handled?What are the main touch events that we use in Android to handle touch control?What happens when we press our fingers against the screen?" }, { "code": null, "e": 27479, "s": 27420, "text": "What happens when we press our fingers against the screen?" }, { "code": null, "e": 27508, "s": 27479, "text": "How do we stop touch events?" }, { "code": null, "e": 27530, "s": 27508, "text": "How is touch handled?" }, { "code": null, "e": 27609, "s": 27530, "text": "What are the main touch events that we use in Android to handle touch control?" }, { "code": null, "e": 27668, "s": 27609, "text": "What happens when we press our fingers against the screen?" }, { "code": null, "e": 27950, "s": 27668, "text": "So, when we touch the screen, the activity’s view, also known as DecorView in Android, receives the touch event notification first. Now, we don’t usually work with the DecorView touch. As a result, the touch is transferred to the ViewGroup and then to its children in the XML file." }, { "code": null, "e": 28093, "s": 27950, "text": "Using dispatchTouchEvent, the ViewGroup in Android transfers the touch event from top to bottom in the ViewGroup hierarchy to its children ()." }, { "code": null, "e": 28129, "s": 28093, "text": "Image #2: The dispatch event module" }, { "code": null, "e": 28297, "s": 28129, "text": "To begin, when we perform a touch action, The touch event is then received by the ViewGroup, and it is intercepted within the ViewGroup using onInterceptTouchEvent ()." }, { "code": null, "e": 28542, "s": 28297, "text": "Geek Tip: If we return true after intercepting, the touch event is not passed to its children; if we return false, the Android eco-system is notified that the ViewGroup wants to dispatch the event to its children, which in our case is a button." }, { "code": null, "e": 28941, "s": 28542, "text": "In general, if we return true, it means we handled the event within the ViewGroup itself, and there is no need to dispatch to its children. The view we have now is the last view in our view tree, as indicated by the button. As a result, it will no longer be able to pass on the touch event to its children because it no longer has any. So, in button, our last onInterceptTouchEvent would be called." }, { "code": null, "e": 29444, "s": 28941, "text": "We need to check the hierarchy, of all the views that we take into account and then perform our work. Handling the event is all about the priority assigned to everything, the first, and then it moves towards the ViewGroups. Touch events function similarly to event dispatching, but in reverse order from child to parent. Let’s say we dispatch the event from ViewGroup and intercept it there; the return value (true/false) determines whether the view’s touch is handled on the ViewGroup or the children." }, { "code": null, "e": 29489, "s": 29444, "text": "Image #3: The dispatchTouchEvent and onTouch" }, { "code": null, "e": 29642, "s": 29489, "text": "So, in this article, the feedback received from the button returns all true, it means that it has been handled and will not be sent to the LinearLayout." }, { "code": null, "e": 29744, "s": 29642, "text": "When we receive a touch event, it is handled by onTouchEvent, which also has a MotionEvent parameter." }, { "code": null, "e": 29751, "s": 29744, "text": "Kotlin" }, { "code": "fun onTouchEvent(event: MotionEvent)", "e": 29788, "s": 29751, "text": null }, { "code": null, "e": 30297, "s": 29788, "text": "The event parameter contains a reference to every task performed in relation to the touch. On the screen of the point on the touch, we can have coordinates such as X and Y points. It even has actions in it, for example, if we tap on the screen, MotionEvent.ACTION DOWN is called, and if we lift our finger, MotionEvent.ACTION UP is called. The action is MotionEvent even if you drag your finger across the screen using MorionEvent.ACTION MOVE. So, when we want to tap the button, the flow on the view occurs." }, { "code": null, "e": 30416, "s": 30297, "text": "onTouchEvent -> Activity -> dispatchTouchEvent (LinearLayout) -> dispatchTouchEvent (Button) -> onTouchEvent (Button)." }, { "code": null, "e": 30529, "s": 30416, "text": "When we don’t want to tap the button but still want to handle the click on LinearLayout, the flow is as follows:" }, { "code": null, "e": 30757, "s": 30529, "text": "Activity -> dispatchTouchEvent (LinearLayout) -> dispatchTouchEvent(Button) -> onTouchEvent(Button) (will return false) -> onTouchEvent(Button) -> onTouchEvent(Button) (will return false) -> onTouchEvent(Button) (LinearLayout)." }, { "code": null, "e": 31514, "s": 30757, "text": "When working with touch events, we begin by clicking a view and then removing the gesture (in our case, our finger/stylus), after which MotionEvent.ACTION DOWN and MotionEvent.ACTION UP is called.When the initial touch occurs on the ViewGroup and the child is intercepted.MotionEvent.ACTION CANCEL is called on the ViewGroup and the touch event is dispatched to the children.Everything now depends on the return value of onInterceptTouchEvent().The dispatchTouchEvent is dependent on its return value; if it returns true, the dispatcher is canceled; if it returns false, the dispatching of the touch event continues until it is used.And if onTouchEvent() returns true, it means the touch was handled; if it returns false, it means the touch was not handled" }, { "code": null, "e": 31711, "s": 31514, "text": "When working with touch events, we begin by clicking a view and then removing the gesture (in our case, our finger/stylus), after which MotionEvent.ACTION DOWN and MotionEvent.ACTION UP is called." }, { "code": null, "e": 31788, "s": 31711, "text": "When the initial touch occurs on the ViewGroup and the child is intercepted." }, { "code": null, "e": 31892, "s": 31788, "text": "MotionEvent.ACTION CANCEL is called on the ViewGroup and the touch event is dispatched to the children." }, { "code": null, "e": 31963, "s": 31892, "text": "Everything now depends on the return value of onInterceptTouchEvent()." }, { "code": null, "e": 32152, "s": 31963, "text": "The dispatchTouchEvent is dependent on its return value; if it returns true, the dispatcher is canceled; if it returns false, the dispatching of the touch event continues until it is used." }, { "code": null, "e": 32276, "s": 32152, "text": "And if onTouchEvent() returns true, it means the touch was handled; if it returns false, it means the touch was not handled" }, { "code": null, "e": 32283, "s": 32276, "text": "Picked" }, { "code": null, "e": 32291, "s": 32283, "text": "Android" }, { "code": null, "e": 32299, "s": 32291, "text": "Android" }, { "code": null, "e": 32397, "s": 32299, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32435, "s": 32397, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 32474, "s": 32435, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32524, "s": 32474, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 32550, "s": 32524, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 32601, "s": 32550, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 32643, "s": 32601, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32681, "s": 32643, "text": "Android Listview in Java with Example" }, { "code": null, "e": 32711, "s": 32681, "text": "Fragment Lifecycle in Android" }, { "code": null, "e": 32784, "s": 32711, "text": "How to Change the Background Color After Clicking the Button in Android?" } ]
Class cast() method in Java with Examples - GeeksforGeeks
27 Dec, 2019 The cast() method of java.lang.Class class is used to cast the specified object to the object of this class. The method returns the object after casting in the form of an object. Syntax: public T[] cast(Object obj) Parameter: This method accepts a parameter obj which is the object to be cast upon Return Value: This method returns the specified object after casting in the form of an object. Exception: This method throws: ClassCastException: if the object is not null and is not assignable to the type T. Below programs demonstrate the cast() method. Example 1: // Java program to demonstrate// cast() method import java.util.*; public class Test { public static Object obj; public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Cast the object obj to object of myClass // using cast() method System.out.println("Object " + obj + " after cast " + "upon to class Test: " + myClass.cast(obj)); }} Class represented by myClass: class Test Object null after cast upon to class Test: null Example 2: // Java program to demonstrate// cast() method import java.util.*; class Main { private static int obj = 10; public static void main(String[] args) throws ClassNotFoundException { try { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); // Cast the object obj to object of myClass // using cast() method System.out.println("Object " + obj + " after cast " + "upon to class Test: " + myClass.cast(obj)); } catch (Exception e) { System.out.println(e); } }} Class represented by myClass: class Main java.lang.ClassCastException: Cannot cast java.lang.Integer to Main Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#cast-java.lang.Object- Java-Functions Java-lang package Java.lang.Class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Overriding in Java Stack Class in Java Set in Java LinkedList in Java Singleton Class in Java
[ { "code": null, "e": 24214, "s": 24186, "text": "\n27 Dec, 2019" }, { "code": null, "e": 24393, "s": 24214, "text": "The cast() method of java.lang.Class class is used to cast the specified object to the object of this class. The method returns the object after casting in the form of an object." }, { "code": null, "e": 24401, "s": 24393, "text": "Syntax:" }, { "code": null, "e": 24430, "s": 24401, "text": "public T[] cast(Object obj)\n" }, { "code": null, "e": 24513, "s": 24430, "text": "Parameter: This method accepts a parameter obj which is the object to be cast upon" }, { "code": null, "e": 24608, "s": 24513, "text": "Return Value: This method returns the specified object after casting in the form of an object." }, { "code": null, "e": 24639, "s": 24608, "text": "Exception: This method throws:" }, { "code": null, "e": 24722, "s": 24639, "text": "ClassCastException: if the object is not null and is not assignable to the type T." }, { "code": null, "e": 24768, "s": 24722, "text": "Below programs demonstrate the cast() method." }, { "code": null, "e": 24779, "s": 24768, "text": "Example 1:" }, { "code": "// Java program to demonstrate// cast() method import java.util.*; public class Test { public static Object obj; public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Cast the object obj to object of myClass // using cast() method System.out.println(\"Object \" + obj + \" after cast \" + \"upon to class Test: \" + myClass.cast(obj)); }}", "e": 25440, "s": 24779, "text": null }, { "code": null, "e": 25530, "s": 25440, "text": "Class represented by myClass: class Test\nObject null after cast upon to class Test: null\n" }, { "code": null, "e": 25541, "s": 25530, "text": "Example 2:" }, { "code": "// Java program to demonstrate// cast() method import java.util.*; class Main { private static int obj = 10; public static void main(String[] args) throws ClassNotFoundException { try { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Cast the object obj to object of myClass // using cast() method System.out.println(\"Object \" + obj + \" after cast \" + \"upon to class Test: \" + myClass.cast(obj)); } catch (Exception e) { System.out.println(e); } }}", "e": 26328, "s": 25541, "text": null }, { "code": null, "e": 26438, "s": 26328, "text": "Class represented by myClass: class Main\njava.lang.ClassCastException: Cannot cast java.lang.Integer to Main\n" }, { "code": null, "e": 26535, "s": 26438, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#cast-java.lang.Object-" }, { "code": null, "e": 26550, "s": 26535, "text": "Java-Functions" }, { "code": null, "e": 26568, "s": 26550, "text": "Java-lang package" }, { "code": null, "e": 26584, "s": 26568, "text": "Java.lang.Class" }, { "code": null, "e": 26589, "s": 26584, "text": "Java" }, { "code": null, "e": 26594, "s": 26589, "text": "Java" }, { "code": null, "e": 26692, "s": 26594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26701, "s": 26692, "text": "Comments" }, { "code": null, "e": 26714, "s": 26701, "text": "Old Comments" }, { "code": null, "e": 26746, "s": 26714, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26776, "s": 26746, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26795, "s": 26776, "text": "Interfaces in Java" }, { "code": null, "e": 26813, "s": 26795, "text": "ArrayList in Java" }, { "code": null, "e": 26845, "s": 26813, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26864, "s": 26845, "text": "Overriding in Java" }, { "code": null, "e": 26884, "s": 26864, "text": "Stack Class in Java" }, { "code": null, "e": 26896, "s": 26884, "text": "Set in Java" }, { "code": null, "e": 26915, "s": 26896, "text": "LinkedList in Java" } ]
Sorted insert for circular linked list | Practice | GeeksforGeeks
Given a sorted circular linked list, the task is to insert a new node in this circular list so that it remains a sorted circular linked list. Example 1: Input: LinkedList = 1->2->4 (the first and last node is connected, i.e. 4 --> 1) data = 2 Output: 1 2 2 4 Example 2: Input: LinkedList = 1->4->7->9 (the first and last node is connected, i.e. 9 --> 1) data = 5 Output: 1 4 5 7 9 Your Task: The task is to complete the function sortedInsert() which should insert the new node into the given circular linked list and return the head of the linkedlist. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 0 <= N <= 105 0 shakshamkaushik12 weeks ago public static Node sortedInsert(Node head,int data) { Node temp = head; Node p = null; while (temp.next.data<data){ temp = temp.next; if(temp.next == head){ break; } } p = new Node(data); if(data>temp.data && data<=temp.next.data){ p.next = temp.next; temp.next = p; }else{ while(temp.next!=head) temp = temp.next; //= p.next; p.next = temp.next; temp.next = p; head = p; } return head; } 0 alokkumar90194 weeks ago Node *sortedInsert(Node* head, int data) { //Your code here Node *temp=new Node(data); if(head==NULL){ temp->next=temp; return temp; } if(head->data>data){ temp->next=head->next; head->next=temp; int t=head->data; head->data=temp->data; temp->data=t; return head; } Node *curr=head; while(curr->next!=head && curr->next->data<data){ curr=curr->next; } temp->next=curr->next; curr->next=temp; return head; } 0 sparhibsp20181 month ago // my code work for all cases but on submit it says segment fault , and i test this cases which say error in run time , and it perfectly works on compile but it shows error in submit . //Your code here Node* first=head; Node* sec; if(first->data<=data) { first=first->next; while(first!=head) { if(first->data<=data) { sec=first; first=first->next; } else { break; } } Node *newnode= new Node(data); newnode->next=first; sec->next=newnode; return head; } else{ Node *newnode=new Node(data); while(first->next!=head){ first=first->next; } first->next=newnode; newnode->next=head; return newnode; } 0 aryansinha18182 months ago A solution with explained test cases Node *sortedInsert(Node* head, int data) { //Your code here Node* temp = new Node(data); // Case 1. When there is no node and the inserted node is the new node if(head == NULL){ head = temp; temp -> next = head; return head; } //Case 2. When insertion is done before first node in circular LL Node* curr = head; if(data<curr -> data){ temp -> next = head; while(curr->next != head){ curr = curr -> next; } curr -> next = temp; head = temp; return head; } else{ //Case 3. When insertion is done anywhere between the circular LL while(curr -> data < data && curr -> next -> data < data){ curr = curr->next; } Node* nxt = curr -> next; curr -> next = temp; temp -> next = nxt; return head; } } +1 anuraggulati2412 months ago Simple C++ solution public: Node *sortedInsert(Node* head, int data) { //Your code here //code here Node* temp = new Node(data); // edege case // zero node if(head == NULL) { head = temp; temp -> next = temp; return head; } Node* curr = head; if(data < curr -> data ) { temp -> next = head; while(curr -> next != head) { curr = curr -> next; } curr -> next = temp; return temp; } // one node... else { while(curr -> data < data && curr -> next -> data < data) { curr = curr -> next; } Node* nxt = curr -> next; curr -> next = temp; temp -> next = nxt; return head; } } 0 rafi19982 months ago class Solution { public static Node sortedInsert(Node head,int data) { Node temp=head, t=null; while(temp.next.data<data){ temp=temp.next; if(temp.next==head){ break; } } t=new Node(data); if(data>temp.data && data<=temp.next.data){ t.next=temp.next; temp.next=t; } else{ while(temp.next!=head) temp=temp.next; t.next=temp.next; temp.next=t; head=t; } return head; } } +1 mashhadihossain2 months ago SIMPLE JAVA SOLUTION (1.4/2.6 SEC) class Solution{public static Node sortedInsert(Node head,int data) { Node temp=head; HashSet<Node> set=new HashSet<Node>(); boolean flag=false; while(!set.contains(temp)) { set.add(temp); if(data>temp.data) { flag=true; } else { flag=false; } temp=temp.next; } if(!flag) { Node temp2=head; HashSet<Node> set1=new HashSet<Node>(); if(set.size()==1) { if(data<temp2.data) { Node val=new Node(data); val.next=temp2; temp2.next=val; return val; } else { Node val=new Node(data); temp2.next=val; val.next=temp2; return temp2; } } if(head.data>data && set.size()>1) { int x=head.data; temp.data=data; data=x; } while(!set1.contains(temp2)) { set1.add(temp2); if(temp2.next.data<data) { temp2=temp2.next; } else if(temp2.next.data>=data) { Node curr=temp2.next; Node extra=new Node(data); temp2.next=extra; extra.next=curr; return head; } } } else { Node temp3=head; HashSet<Node> set2=new HashSet<Node>(); while(!set2.contains(temp3.next)) { set2.add(temp3); temp3=temp3.next; } Node curr=temp3.next; Node extra=new Node(data); temp3.next=extra; extra.next=curr; } return head; }} +2 badgujarsachin832 months ago Node *sortedInsert(Node* head, int data) { //Your code here Node* newnode=new Node(data); Node* temp=head,*temp2=head; if(!head){ newnode->next=newnode; return newnode; }else if(data<=head->data){ newnode->next=head; while(temp->next!=head){ temp=temp->next; } temp->next=newnode; return newnode; }else{ while(temp->next!=head && data>temp->next->data){ temp=temp->next; } newnode->next=temp->next; temp->next=newnode; return head; } } -3 mayank20212 months ago C++Node *sortedInsert(Node* head, int data) { Node *newnode=new Node(data); Node *temp=head, *temp1=head; if(!head) { newnode->next=newnode; return newnode; } else if (data <= head->data) { newnode->next=head; while(temp->next !=head) temp=temp->next; temp->next=newnode; //head=newnode; return newnode; } else { while(temp->next !=head && data > temp->next->data) { temp=temp->next; } newnode->next=temp->next; temp->next=newnode; return head; } } -1 gdhikshith13 months ago Node *sortedInsert(Node* head, int data) { struct Node* p=head; if(head==NULL) { struct Node* p=new Node(data); p->next=p; return p; } p=head; if(data<=head->data) { p=new Node(data); p->next=head; struct Node* q=head; while(q->next!=head) { q=q->next; } q->next=p; head=p; return head; } struct Node* r=NULL; p=head; while(p->next!=head) { if(data<=p->data) { struct Node* temp=new Node(data); r->next=temp; temp->next=p; return head; } else { r=p; p=p->next; } } struct Node* w=new Node(data); p->next=w; w->next=head; return head; } 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": 380, "s": 238, "text": "Given a sorted circular linked list, the task is to insert a new node in this circular list so that it remains a sorted circular linked list." }, { "code": null, "e": 391, "s": 380, "text": "Example 1:" }, { "code": null, "e": 498, "s": 391, "text": "Input:\nLinkedList = 1->2->4\n(the first and last node is connected,\ni.e. 4 --> 1)\ndata = 2\nOutput: 1 2 2 4\n" }, { "code": null, "e": 509, "s": 498, "text": "Example 2:" }, { "code": null, "e": 621, "s": 509, "text": "Input:\nLinkedList = 1->4->7->9\n(the first and last node is connected,\ni.e. 9 --> 1)\ndata = 5\nOutput: 1 4 5 7 9\n" }, { "code": null, "e": 792, "s": 621, "text": "Your Task:\nThe task is to complete the function sortedInsert() which should insert the new node into the given circular linked list and return the head of the linkedlist." }, { "code": null, "e": 854, "s": 792, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 881, "s": 854, "text": "Constraints:\n0 <= N <= 105" }, { "code": null, "e": 883, "s": 881, "text": "0" }, { "code": null, "e": 911, "s": 883, "text": "shakshamkaushik12 weeks ago" }, { "code": null, "e": 965, "s": 913, "text": "public static Node sortedInsert(Node head,int data)" }, { "code": null, "e": 975, "s": 965, "text": " {" }, { "code": null, "e": 1005, "s": 975, "text": " Node temp = head;" }, { "code": null, "e": 1032, "s": 1005, "text": " Node p = null;" }, { "code": null, "e": 1073, "s": 1032, "text": " while (temp.next.data<data){" }, { "code": null, "e": 1107, "s": 1073, "text": " temp = temp.next;" }, { "code": null, "e": 1146, "s": 1107, "text": " if(temp.next == head){" }, { "code": null, "e": 1173, "s": 1146, "text": " break;" }, { "code": null, "e": 1191, "s": 1173, "text": " }" }, { "code": null, "e": 1205, "s": 1191, "text": " }" }, { "code": null, "e": 1237, "s": 1205, "text": " p = new Node(data);" }, { "code": null, "e": 1293, "s": 1237, "text": " if(data>temp.data && data<=temp.next.data){" }, { "code": null, "e": 1329, "s": 1293, "text": " p.next = temp.next;" }, { "code": null, "e": 1360, "s": 1329, "text": " temp.next = p;" }, { "code": null, "e": 1379, "s": 1360, "text": " }else{" }, { "code": null, "e": 1418, "s": 1379, "text": " while(temp.next!=head)" }, { "code": null, "e": 1456, "s": 1418, "text": " temp = temp.next;" }, { "code": null, "e": 1468, "s": 1456, "text": "//= p.next;" }, { "code": null, "e": 1508, "s": 1468, "text": " p.next = temp.next;" }, { "code": null, "e": 1543, "s": 1508, "text": " temp.next = p;" }, { "code": null, "e": 1573, "s": 1543, "text": " head = p;" }, { "code": null, "e": 1617, "s": 1607, "text": " }" }, { "code": null, "e": 1638, "s": 1617, "text": " return head;" }, { "code": null, "e": 1648, "s": 1638, "text": " }" }, { "code": null, "e": 1650, "s": 1648, "text": "0" }, { "code": null, "e": 1675, "s": 1650, "text": "alokkumar90194 weeks ago" }, { "code": null, "e": 2255, "s": 1675, "text": "Node *sortedInsert(Node* head, int data)\n {\n //Your code here\n Node *temp=new Node(data);\n \n if(head==NULL){\n temp->next=temp;\n return temp;\n }\n if(head->data>data){\n temp->next=head->next;\n head->next=temp;\n int t=head->data;\n head->data=temp->data;\n temp->data=t;\n return head;\n }\n Node *curr=head;\n while(curr->next!=head && curr->next->data<data){\n curr=curr->next;\n }\n temp->next=curr->next;\n curr->next=temp;\n return head;\n }" }, { "code": null, "e": 2257, "s": 2255, "text": "0" }, { "code": null, "e": 2282, "s": 2257, "text": "sparhibsp20181 month ago" }, { "code": null, "e": 2469, "s": 2282, "text": "// my code work for all cases but on submit it says segment fault , and i test this cases which say error in run time , and it perfectly works on compile but it shows error in submit . " }, { "code": null, "e": 3221, "s": 2469, "text": "//Your code here Node* first=head; Node* sec; if(first->data<=data) { first=first->next; while(first!=head) { if(first->data<=data) { sec=first; first=first->next; } else { break; } } Node *newnode= new Node(data); newnode->next=first; sec->next=newnode; return head; } else{ Node *newnode=new Node(data); while(first->next!=head){ first=first->next; } first->next=newnode; newnode->next=head; return newnode; }" }, { "code": null, "e": 3223, "s": 3221, "text": "0" }, { "code": null, "e": 3250, "s": 3223, "text": "aryansinha18182 months ago" }, { "code": null, "e": 3287, "s": 3250, "text": "A solution with explained test cases" }, { "code": null, "e": 4199, "s": 3289, "text": "Node *sortedInsert(Node* head, int data) { //Your code here Node* temp = new Node(data); // Case 1. When there is no node and the inserted node is the new node if(head == NULL){ head = temp; temp -> next = head; return head; } //Case 2. When insertion is done before first node in circular LL Node* curr = head; if(data<curr -> data){ temp -> next = head; while(curr->next != head){ curr = curr -> next; } curr -> next = temp; head = temp; return head; } else{ //Case 3. When insertion is done anywhere between the circular LL while(curr -> data < data && curr -> next -> data < data){ curr = curr->next; } Node* nxt = curr -> next; curr -> next = temp; temp -> next = nxt; return head; } }" }, { "code": null, "e": 4202, "s": 4199, "text": "+1" }, { "code": null, "e": 4230, "s": 4202, "text": "anuraggulati2412 months ago" }, { "code": null, "e": 4251, "s": 4230, "text": "Simple C++ solution " }, { "code": null, "e": 5019, "s": 4255, "text": " public:\n Node *sortedInsert(Node* head, int data)\n {\n //Your code here\n //code here\n Node* temp = new Node(data);\n \n // edege case \n // zero node\n if(head == NULL) {\n head = temp;\n temp -> next = temp;\n return head;\n }\n \n Node* curr = head;\n \n if(data < curr -> data ) {\n temp -> next = head;\n while(curr -> next != head) {\n curr = curr -> next;\n }\n curr -> next = temp;\n return temp;\n }\n // one node...\n else {\n while(curr -> data < data && curr -> next -> data < data) {\n curr = curr -> next;\n }\n Node* nxt = curr -> next;\n curr -> next = temp;\n temp -> next = nxt;\n return head;\n }\n }" }, { "code": null, "e": 5021, "s": 5019, "text": "0" }, { "code": null, "e": 5042, "s": 5021, "text": "rafi19982 months ago" }, { "code": null, "e": 5744, "s": 5042, "text": "class Solution\n{\n\tpublic static Node sortedInsert(Node head,int data)\n {\n Node temp=head, t=null;\n \n while(temp.next.data<data){\n temp=temp.next;\n if(temp.next==head){\n break;\n }\n }\n t=new Node(data);\n if(data>temp.data && data<=temp.next.data){\n t.next=temp.next;\n temp.next=t;\n }\n else{\n while(temp.next!=head)\n temp=temp.next;\n t.next=temp.next;\n temp.next=t;\n head=t;\n }\n \n return head;\n }\n}" }, { "code": null, "e": 5747, "s": 5744, "text": "+1" }, { "code": null, "e": 5775, "s": 5747, "text": "mashhadihossain2 months ago" }, { "code": null, "e": 5810, "s": 5775, "text": "SIMPLE JAVA SOLUTION (1.4/2.6 SEC)" }, { "code": null, "e": 8251, "s": 5810, "text": "class Solution{public static Node sortedInsert(Node head,int data) { Node temp=head; HashSet<Node> set=new HashSet<Node>(); boolean flag=false; while(!set.contains(temp)) { set.add(temp); if(data>temp.data) { flag=true; } else { flag=false; } temp=temp.next; } if(!flag) { Node temp2=head; HashSet<Node> set1=new HashSet<Node>(); if(set.size()==1) { if(data<temp2.data) { Node val=new Node(data); val.next=temp2; temp2.next=val; return val; } else { Node val=new Node(data); temp2.next=val; val.next=temp2; return temp2; } } if(head.data>data && set.size()>1) { int x=head.data; temp.data=data; data=x; } while(!set1.contains(temp2)) { set1.add(temp2); if(temp2.next.data<data) { temp2=temp2.next; } else if(temp2.next.data>=data) { Node curr=temp2.next; Node extra=new Node(data); temp2.next=extra; extra.next=curr; return head; } } } else { Node temp3=head; HashSet<Node> set2=new HashSet<Node>(); while(!set2.contains(temp3.next)) { set2.add(temp3); temp3=temp3.next; } Node curr=temp3.next; Node extra=new Node(data); temp3.next=extra; extra.next=curr; } return head; }}" }, { "code": null, "e": 8254, "s": 8251, "text": "+2" }, { "code": null, "e": 8283, "s": 8254, "text": "badgujarsachin832 months ago" }, { "code": null, "e": 8939, "s": 8283, "text": " Node *sortedInsert(Node* head, int data)\n {\n //Your code here\n Node* newnode=new Node(data);\n Node* temp=head,*temp2=head;\n if(!head){\n newnode->next=newnode;\n return newnode;\n }else if(data<=head->data){\n newnode->next=head;\n while(temp->next!=head){\n temp=temp->next;\n }\n temp->next=newnode;\n return newnode;\n }else{\n while(temp->next!=head && data>temp->next->data){\n temp=temp->next;\n }\n newnode->next=temp->next;\n temp->next=newnode;\n return head;\n }\n }" }, { "code": null, "e": 8942, "s": 8939, "text": "-3" }, { "code": null, "e": 8965, "s": 8942, "text": "mayank20212 months ago" }, { "code": null, "e": 9648, "s": 8965, "text": "C++Node *sortedInsert(Node* head, int data) { Node *newnode=new Node(data); Node *temp=head, *temp1=head; if(!head) { newnode->next=newnode; return newnode; } else if (data <= head->data) { newnode->next=head; while(temp->next !=head) temp=temp->next; temp->next=newnode; //head=newnode; return newnode; } else { while(temp->next !=head && data > temp->next->data) { temp=temp->next; } newnode->next=temp->next; temp->next=newnode; return head; } }" }, { "code": null, "e": 9651, "s": 9648, "text": "-1" }, { "code": null, "e": 9675, "s": 9651, "text": "gdhikshith13 months ago" }, { "code": null, "e": 10442, "s": 9675, "text": "Node *sortedInsert(Node* head, int data) { struct Node* p=head; if(head==NULL) { struct Node* p=new Node(data); p->next=p; return p; } p=head; if(data<=head->data) { p=new Node(data); p->next=head; struct Node* q=head; while(q->next!=head) { q=q->next; } q->next=p; head=p; return head; } struct Node* r=NULL; p=head; while(p->next!=head) { if(data<=p->data) { struct Node* temp=new Node(data); r->next=temp; temp->next=p; return head; } else { r=p; p=p->next; } } struct Node* w=new Node(data); p->next=w; w->next=head; return head; }" }, { "code": null, "e": 10588, "s": 10442, "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": 10624, "s": 10588, "text": " Login to access your submissions. " }, { "code": null, "e": 10634, "s": 10624, "text": "\nProblem\n" }, { "code": null, "e": 10644, "s": 10634, "text": "\nContest\n" }, { "code": null, "e": 10707, "s": 10644, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 10855, "s": 10707, "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": 11063, "s": 10855, "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": 11169, "s": 11063, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Find original numbers from gcd() every pair - GeeksforGeeks
06 Jun, 2021 Given an array arr[] containing GCD of every possible pair of elements of another array. The task is to find the original numbers which are used to calculate the GCD array. For example, if original numbers are {4, 6, 8} then the given array will be {4, 2, 4, 2, 6, 2, 4, 2, 8}. Examples: Input: arr[] = {5, 1, 1, 12} Output: 12 5 gcd(12, 12) = 12 gcd(12, 5) = 1 gcd(5, 12) = 1 gcd(5, 5) = 5 Input: arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2} Output: 12 10 7 5 1 Approach: Sort the array in decreasing order.Highest element will always be one of the original numbers. Keep that number and remove it from the array.Compute GCD of the element taken in the previous step with the current element starting from the greatest and discard the GCD value from the given array. Sort the array in decreasing order. Highest element will always be one of the original numbers. Keep that number and remove it from the array. Compute GCD of the element taken in the previous step with the current element starting from the greatest and discard the GCD value from the given array. 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; // Utility function to print// the contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Function to find the required numbersvoid findNumbers(int arr[], int n){ // Sort array in decreasing order sort(arr, arr + n, greater<int>()); int freq[arr[0] + 1] = { 0 }; // Count frequency of each element for (int i = 0; i < n; i++) freq[arr[i]]++; // Size of the resultant array int size = sqrt(n); int brr[size] = { 0 }, x, l = 0; for (int i = 0; i < n; i++) { if (freq[arr[i]] > 0) { // Store the highest element in // the resultant array brr[l] = arr[i]; // Decrement the frequency of that element freq[brr[l]]--; l++; for (int j = 0; j < l; j++) { if (i != j) { // Compute GCD x = __gcd(arr[i], brr[j]); // Decrement GCD value by 2 freq[x] -= 2; } } } } printArr(brr, size);} // Driver codeint main(){ int arr[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2 }; int n = sizeof(arr) / sizeof(arr[0]); findNumbers(arr, n); return 0;} // Java implementation of the approachimport java.util.Arrays; class GFG{ // Utility function to print // the contents of an array static void printArr(int arr[], int n) { for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } } // Function to find the required numbers static void findNumbers(int arr[], int n) { // Sort array in decreasing order Arrays.sort(arr); reverse(arr); int freq[] = new int[arr[0] + 1]; // Count frequency of each element for (int i = 0; i < n; i++) { freq[arr[i]]++; } // Size of the resultant array int size = (int) Math.sqrt(n); int brr[] = new int[size], x, l = 0; for (int i = 0; i < n; i++) { if (freq[arr[i]] > 0 && l < size) { // Store the highest element in // the resultant array brr[l] = arr[i]; // Decrement the frequency of that element freq[brr[l]]--; l++; for (int j = 0; j < l; j++) { if (i != j) { // Compute GCD x = __gcd(arr[i], brr[j]); // Decrement GCD value by 2 freq[x] -= 2; } } } } printArr(brr, size); } // reverse array public static void reverse(int[] input) { int last = input.length - 1; int middle = input.length / 2; for (int i = 0; i <= middle; i++) { int temp = input[i]; input[i] = input[last - i]; input[last - i] = temp; } } static int __gcd(int a, int b) { if (b == 0) { return a; } return __gcd(b, a % b); } // Driver code public static void main(String[] args) { int arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2}; int n = arr.length; findNumbers(arr, n); }} // This code has been contributed by 29AjayKumar # Python 3 implementation of the approachfrom math import sqrt, gcd # Utility function to print# the contents of an arraydef printArr(arr, n): for i in range(n): print(arr[i], end = " ") # Function to find the required numbersdef findNumbers(arr, n): # Sort array in decreasing order arr.sort(reverse = True) freq = [0 for i in range(arr[0] + 1)] # Count frequency of each element for i in range(n): freq[arr[i]] += 1 # Size of the resultant array size = int(sqrt(n)) brr = [0 for i in range(len(arr))] l = 0 for i in range(n): if (freq[arr[i]] > 0): # Store the highest element in # the resultant array brr[l] = arr[i] # Decrement the frequency of that element freq[brr[l]] -= 1 l += 1 for j in range(l): if (i != j): # Compute GCD x = gcd(arr[i], brr[j]) # Decrement GCD value by 2 freq[x] -= 2 printArr(brr, size) # Driver codeif __name__ == '__main__': arr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2] n = len(arr) findNumbers(arr, n) # This code is contributed by# Surendra_Gangwar // C# implementation for above approachusing System; class GFG{ // Utility function to print // the contents of an array static void printArr(int []arr, int n) { for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); } } // Function to find the required numbers static void findNumbers(int []arr, int n) { // Sort array in decreasing order Array.Sort(arr); reverse(arr); int []freq = new int[arr[0] + 1]; // Count frequency of each element for (int i = 0; i < n; i++) { freq[arr[i]]++; } // Size of the resultant array int size = (int) Math.Sqrt(n); int []brr = new int[size];int x, l = 0; for (int i = 0; i < n; i++) { if (freq[arr[i]] > 0 && l < size) { // Store the highest element in // the resultant array brr[l] = arr[i]; // Decrement the frequency of that element freq[brr[l]]--; l++; for (int j = 0; j < l; j++) { if (i != j) { // Compute GCD x = __gcd(arr[i], brr[j]); // Decrement GCD value by 2 freq[x] -= 2; } } } } printArr(brr, size); } // reverse array public static void reverse(int []input) { int last = input.Length - 1; int middle = input.Length / 2; for (int i = 0; i <= middle; i++) { int temp = input[i]; input[i] = input[last - i]; input[last - i] = temp; } } static int __gcd(int a, int b) { if (b == 0) { return a; } return __gcd(b, a % b); } // Driver code public static void Main(String[] args) { int []arr = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2}; int n = arr.Length; findNumbers(arr, n); }} /* This code contributed by PrinciRaj1992 */ <?php// PHP implementation of the approachfunction gcd($a, $b){ return ($a % $b) ? gcd($b, $a % $b) : $b;} // Utility function to print// the contents of an arrayfunction printArr($arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i], " ";} // Function to find the required numbersfunction findNumbers($arr, $n){ // Sort array in decreasing order rsort($arr); $freq = array_fill(0, $arr[0] + 1, 0); // Count frequency of each element for ($i = 0; $i < $n; $i++) $freq[$arr[$i]]++; // Size of the resultant array $size = floor(sqrt($n)); $brr = array_fill(0, $size, 0); $l = 0; for ($i = 0; $i < $n; $i++) { if ($freq[$arr[$i]] > 0) { // Store the highest element in // the resultant array $brr[$l] = $arr[$i]; // Decrement the frequency of that element $freq[$brr[$l]]--; $l++; for ($j = 0; $j < $l; $j++) { if ($i != $j) { // Compute GCD $x = gcd($arr[$i], $brr[$j]); // Decrement GCD value by 2 $freq[$x] -= 2; } } } } printArr($brr, $size);} // Driver code$arr = array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2 );$n = count($arr) ;findNumbers($arr, $n); // This code is contributed by Ryuga?> <script> // Javascript implementation for above approach // Utility function to print// the contents of an arrayfunction printArr(arr, n){ for(let i = 0; i < n; i++) { document.write(arr[i] + " "); }} // Function to find the required numbersfunction findNumbers(arr, n){ // Sort array in decreasing order arr.sort(function(a, b){return a - b}); reverse(arr); let freq = new Array(arr[0] + 1); freq.fill(0); // Count frequency of each element for(let i = 0; i < n; i++) { freq[arr[i]]++; } // Size of the resultant array let size = parseInt(Math.sqrt(n), 10); let brr = new Array(size); brr.fill(0); let x, l = 0; for(let i = 0; i < n; i++) { if (freq[arr[i]] > 0 && l < size) { // Store the highest element in // the resultant array brr[l] = arr[i]; // Decrement the frequency of that element freq[brr[l]]--; l++; for(let j = 0; j < l; j++) { if (i != j) { // Compute GCD x = __gcd(arr[i], brr[j]); // Decrement GCD value by 2 freq[x] -= 2; } } } } printArr(brr, size);} // Reverse arrayfunction reverse(input){ let last = input.length - 1; let middle = parseInt(input.length / 2, 10); for(let i = 0; i <= middle; i++) { let temp = input[i]; input[i] = input[last - i]; input[last - i] = temp; }} function __gcd(a, b){ if (b == 0) { return a; } return __gcd(b, a % b);} // Driver codelet arr = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2];let n = arr.length;findNumbers(arr, n); // This code is contributed by divyeshrabadiya07 </script> 12 10 7 5 1 SURENDRA_GANGWAR 29AjayKumar princiraj1992 ankthon nikhil3991 divyeshrabadiya07 Constructive Algorithms GCD-LCM Competitive Programming Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multistage Graph (Shortest Path) Breadth First Traversal ( BFS ) on a 2D array Difference between Backtracking and Branch-N-Bound technique 5 Best Languages for Competitive Programming Most important type of Algorithms
[ { "code": null, "e": 26357, "s": 26329, "text": "\n06 Jun, 2021" }, { "code": null, "e": 26636, "s": 26357, "text": "Given an array arr[] containing GCD of every possible pair of elements of another array. The task is to find the original numbers which are used to calculate the GCD array. For example, if original numbers are {4, 6, 8} then the given array will be {4, 2, 4, 2, 6, 2, 4, 2, 8}. " }, { "code": null, "e": 26647, "s": 26636, "text": "Examples: " }, { "code": null, "e": 26750, "s": 26647, "text": "Input: arr[] = {5, 1, 1, 12} Output: 12 5 gcd(12, 12) = 12 gcd(12, 5) = 1 gcd(5, 12) = 1 gcd(5, 5) = 5" }, { "code": null, "e": 26865, "s": 26750, "text": "Input: arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2} Output: 12 10 7 5 1 " }, { "code": null, "e": 26876, "s": 26865, "text": "Approach: " }, { "code": null, "e": 27171, "s": 26876, "text": "Sort the array in decreasing order.Highest element will always be one of the original numbers. Keep that number and remove it from the array.Compute GCD of the element taken in the previous step with the current element starting from the greatest and discard the GCD value from the given array." }, { "code": null, "e": 27207, "s": 27171, "text": "Sort the array in decreasing order." }, { "code": null, "e": 27314, "s": 27207, "text": "Highest element will always be one of the original numbers. Keep that number and remove it from the array." }, { "code": null, "e": 27468, "s": 27314, "text": "Compute GCD of the element taken in the previous step with the current element starting from the greatest and discard the GCD value from the given array." }, { "code": null, "e": 27520, "s": 27468, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27524, "s": 27520, "text": "C++" }, { "code": null, "e": 27529, "s": 27524, "text": "Java" }, { "code": null, "e": 27537, "s": 27529, "text": "Python3" }, { "code": null, "e": 27540, "s": 27537, "text": "C#" }, { "code": null, "e": 27544, "s": 27540, "text": "PHP" }, { "code": null, "e": 27555, "s": 27544, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print// the contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Function to find the required numbersvoid findNumbers(int arr[], int n){ // Sort array in decreasing order sort(arr, arr + n, greater<int>()); int freq[arr[0] + 1] = { 0 }; // Count frequency of each element for (int i = 0; i < n; i++) freq[arr[i]]++; // Size of the resultant array int size = sqrt(n); int brr[size] = { 0 }, x, l = 0; for (int i = 0; i < n; i++) { if (freq[arr[i]] > 0) { // Store the highest element in // the resultant array brr[l] = arr[i]; // Decrement the frequency of that element freq[brr[l]]--; l++; for (int j = 0; j < l; j++) { if (i != j) { // Compute GCD x = __gcd(arr[i], brr[j]); // Decrement GCD value by 2 freq[x] -= 2; } } } } printArr(brr, size);} // Driver codeint main(){ int arr[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2 }; int n = sizeof(arr) / sizeof(arr[0]); findNumbers(arr, n); return 0;}", "e": 28951, "s": 27555, "text": null }, { "code": "// Java implementation of the approachimport java.util.Arrays; class GFG{ // Utility function to print // the contents of an array static void printArr(int arr[], int n) { for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } } // Function to find the required numbers static void findNumbers(int arr[], int n) { // Sort array in decreasing order Arrays.sort(arr); reverse(arr); int freq[] = new int[arr[0] + 1]; // Count frequency of each element for (int i = 0; i < n; i++) { freq[arr[i]]++; } // Size of the resultant array int size = (int) Math.sqrt(n); int brr[] = new int[size], x, l = 0; for (int i = 0; i < n; i++) { if (freq[arr[i]] > 0 && l < size) { // Store the highest element in // the resultant array brr[l] = arr[i]; // Decrement the frequency of that element freq[brr[l]]--; l++; for (int j = 0; j < l; j++) { if (i != j) { // Compute GCD x = __gcd(arr[i], brr[j]); // Decrement GCD value by 2 freq[x] -= 2; } } } } printArr(brr, size); } // reverse array public static void reverse(int[] input) { int last = input.length - 1; int middle = input.length / 2; for (int i = 0; i <= middle; i++) { int temp = input[i]; input[i] = input[last - i]; input[last - i] = temp; } } static int __gcd(int a, int b) { if (b == 0) { return a; } return __gcd(b, a % b); } // Driver code public static void main(String[] args) { int arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2}; int n = arr.length; findNumbers(arr, n); }} // This code has been contributed by 29AjayKumar", "e": 31161, "s": 28951, "text": null }, { "code": "# Python 3 implementation of the approachfrom math import sqrt, gcd # Utility function to print# the contents of an arraydef printArr(arr, n): for i in range(n): print(arr[i], end = \" \") # Function to find the required numbersdef findNumbers(arr, n): # Sort array in decreasing order arr.sort(reverse = True) freq = [0 for i in range(arr[0] + 1)] # Count frequency of each element for i in range(n): freq[arr[i]] += 1 # Size of the resultant array size = int(sqrt(n)) brr = [0 for i in range(len(arr))] l = 0 for i in range(n): if (freq[arr[i]] > 0): # Store the highest element in # the resultant array brr[l] = arr[i] # Decrement the frequency of that element freq[brr[l]] -= 1 l += 1 for j in range(l): if (i != j): # Compute GCD x = gcd(arr[i], brr[j]) # Decrement GCD value by 2 freq[x] -= 2 printArr(brr, size) # Driver codeif __name__ == '__main__': arr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2] n = len(arr) findNumbers(arr, n) # This code is contributed by# Surendra_Gangwar", "e": 32487, "s": 31161, "text": null }, { "code": "// C# implementation for above approachusing System; class GFG{ // Utility function to print // the contents of an array static void printArr(int []arr, int n) { for (int i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); } } // Function to find the required numbers static void findNumbers(int []arr, int n) { // Sort array in decreasing order Array.Sort(arr); reverse(arr); int []freq = new int[arr[0] + 1]; // Count frequency of each element for (int i = 0; i < n; i++) { freq[arr[i]]++; } // Size of the resultant array int size = (int) Math.Sqrt(n); int []brr = new int[size];int x, l = 0; for (int i = 0; i < n; i++) { if (freq[arr[i]] > 0 && l < size) { // Store the highest element in // the resultant array brr[l] = arr[i]; // Decrement the frequency of that element freq[brr[l]]--; l++; for (int j = 0; j < l; j++) { if (i != j) { // Compute GCD x = __gcd(arr[i], brr[j]); // Decrement GCD value by 2 freq[x] -= 2; } } } } printArr(brr, size); } // reverse array public static void reverse(int []input) { int last = input.Length - 1; int middle = input.Length / 2; for (int i = 0; i <= middle; i++) { int temp = input[i]; input[i] = input[last - i]; input[last - i] = temp; } } static int __gcd(int a, int b) { if (b == 0) { return a; } return __gcd(b, a % b); } // Driver code public static void Main(String[] args) { int []arr = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2}; int n = arr.Length; findNumbers(arr, n); }} /* This code contributed by PrinciRaj1992 */", "e": 34686, "s": 32487, "text": null }, { "code": "<?php// PHP implementation of the approachfunction gcd($a, $b){ return ($a % $b) ? gcd($b, $a % $b) : $b;} // Utility function to print// the contents of an arrayfunction printArr($arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i], \" \";} // Function to find the required numbersfunction findNumbers($arr, $n){ // Sort array in decreasing order rsort($arr); $freq = array_fill(0, $arr[0] + 1, 0); // Count frequency of each element for ($i = 0; $i < $n; $i++) $freq[$arr[$i]]++; // Size of the resultant array $size = floor(sqrt($n)); $brr = array_fill(0, $size, 0); $l = 0; for ($i = 0; $i < $n; $i++) { if ($freq[$arr[$i]] > 0) { // Store the highest element in // the resultant array $brr[$l] = $arr[$i]; // Decrement the frequency of that element $freq[$brr[$l]]--; $l++; for ($j = 0; $j < $l; $j++) { if ($i != $j) { // Compute GCD $x = gcd($arr[$i], $brr[$j]); // Decrement GCD value by 2 $freq[$x] -= 2; } } } } printArr($brr, $size);} // Driver code$arr = array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2 );$n = count($arr) ;findNumbers($arr, $n); // This code is contributed by Ryuga?>", "e": 36164, "s": 34686, "text": null }, { "code": "<script> // Javascript implementation for above approach // Utility function to print// the contents of an arrayfunction printArr(arr, n){ for(let i = 0; i < n; i++) { document.write(arr[i] + \" \"); }} // Function to find the required numbersfunction findNumbers(arr, n){ // Sort array in decreasing order arr.sort(function(a, b){return a - b}); reverse(arr); let freq = new Array(arr[0] + 1); freq.fill(0); // Count frequency of each element for(let i = 0; i < n; i++) { freq[arr[i]]++; } // Size of the resultant array let size = parseInt(Math.sqrt(n), 10); let brr = new Array(size); brr.fill(0); let x, l = 0; for(let i = 0; i < n; i++) { if (freq[arr[i]] > 0 && l < size) { // Store the highest element in // the resultant array brr[l] = arr[i]; // Decrement the frequency of that element freq[brr[l]]--; l++; for(let j = 0; j < l; j++) { if (i != j) { // Compute GCD x = __gcd(arr[i], brr[j]); // Decrement GCD value by 2 freq[x] -= 2; } } } } printArr(brr, size);} // Reverse arrayfunction reverse(input){ let last = input.length - 1; let middle = parseInt(input.length / 2, 10); for(let i = 0; i <= middle; i++) { let temp = input[i]; input[i] = input[last - i]; input[last - i] = temp; }} function __gcd(a, b){ if (b == 0) { return a; } return __gcd(b, a % b);} // Driver codelet arr = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 7, 10, 12, 2, 2];let n = arr.length;findNumbers(arr, n); // This code is contributed by divyeshrabadiya07 </script>", "e": 38075, "s": 36164, "text": null }, { "code": null, "e": 38087, "s": 38075, "text": "12 10 7 5 1" }, { "code": null, "e": 38106, "s": 38089, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 38118, "s": 38106, "text": "29AjayKumar" }, { "code": null, "e": 38132, "s": 38118, "text": "princiraj1992" }, { "code": null, "e": 38140, "s": 38132, "text": "ankthon" }, { "code": null, "e": 38151, "s": 38140, "text": "nikhil3991" }, { "code": null, "e": 38169, "s": 38151, "text": "divyeshrabadiya07" }, { "code": null, "e": 38193, "s": 38169, "text": "Constructive Algorithms" }, { "code": null, "e": 38201, "s": 38193, "text": "GCD-LCM" }, { "code": null, "e": 38225, "s": 38201, "text": "Competitive Programming" }, { "code": null, "e": 38233, "s": 38225, "text": "Sorting" }, { "code": null, "e": 38241, "s": 38233, "text": "Sorting" }, { "code": null, "e": 38339, "s": 38241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38372, "s": 38339, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 38418, "s": 38372, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 38479, "s": 38418, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 38524, "s": 38479, "text": "5 Best Languages for Competitive Programming" } ]
How to make a div center align in HTML?
To center div element center ,you can use "div style="text-align:center" " and to center the div ,use "div style="margin: 0 auto" " In your code, the above css will be written as − <div style="text-align:center;width: 300px;margin: 0 auto;border-style: dotted;"> <p>hi</p> </div>
[ { "code": null, "e": 1194, "s": 1062, "text": "To center div element center ,you can use \"div style=\"text-align:center\" \" and to center the div ,use \"div style=\"margin: 0 auto\" \"" }, { "code": null, "e": 1243, "s": 1194, "text": "In your code, the above css will be written as −" }, { "code": null, "e": 1342, "s": 1243, "text": "<div style=\"text-align:center;width: 300px;margin: 0 auto;border-style: dotted;\">\n<p>hi</p>\n</div>" } ]
What is onmouseover event in JavaScript?
The onmouseover event triggers when the mouse pointer moves over an element. You can try to run the following code to learn how to work with onmouseover event in JavaScript − <html> <head> <script> <!-- function sayHello() { alert("Mouse Over") } //--> </script> </head> <body> <p onmouseover = "sayHello()">This is demo text for mouseover event.</p> </body> </html>
[ { "code": null, "e": 1139, "s": 1062, "text": "The onmouseover event triggers when the mouse pointer moves over an element." }, { "code": null, "e": 1237, "s": 1139, "text": "You can try to run the following code to learn how to work with onmouseover event in JavaScript −" }, { "code": null, "e": 1516, "s": 1237, "text": "<html>\n <head>\n <script>\n <!--\n function sayHello() {\n alert(\"Mouse Over\")\n }\n //-->\n </script>\n </head>\n <body>\n <p onmouseover = \"sayHello()\">This is demo text for mouseover event.</p>\n </body>\n</html>" } ]
How to derive summary statistics using PostgreSQL | by KSV Muralidhar | Towards Data Science
In this article, we’ll discuss how to derive summary statistics of numerical and categorical columns/fields using SQL. We’ll use the Netflix Movies and TV Shows dataset that’s downloaded from Tableau Public sample datasets (https://public.tableau.com/en-us/s/resources and go to Sample Data). This dataset consists of TV shows and movies available on Netflix as of 2019 and is sourced by Tableau from Kaggle and the updated version of the dataset can be found on Kaggle. However, for this article, we’ll use the older version available in Tableau sample datasets and import it into Postgres. This article assumes that the reader has basic knowledge of SQL queries and statistics. Below is a snapshot of the netflix_titles that we’ll be using throughout this article. Frequently used summary statistics for numerical variables are mean, median, minimum, maximum, range, standard deviation, variance, Q1, Q3, IQR and skewness. In PostgreSQL, the mean of a numerical field/column is computed using the AVG() function. We’ll compute the mean of duration_minutes field as shown below. SELECT AVG(duration_minutes) AS mean FROM netflix_titles; In PostgreSQL, there is no function to directly compute the median of a numerical field/column. However, since median is the 50th percentile, we can use it as a proxy to median. Percentile of a numerical variable is computed using the PERCENTILE_CONT() function. We’ll compute the median of duration_minutes field as shown below. SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY duration_minutes) AS median FROM netflix_titles; WITHIN GROUP clause creates an ordered subset of data that can be used to perform aggregations. PERCENTILE_CONT takes the percentile required as an argument, in this case it is 0.5 i.e. the 50th percentile. In PostgreSQL, the minimum value of a numerical field/column is found using the MIN() function. We’ll find the minimum value of duration_minutes field as shown below. SELECT MIN(duration_minutes) AS min FROM netflix_titles; In PostgreSQL, the maximum value of a numerical field/column is found using the MAX() function. We’ll find the maximum value of duration_minutes field as shown below. SELECT MAX(duration_minutes) AS max FROM netflix_titles; In PostgreSQL, there is no function to directly compute the range of a numerical field/column. However, since range is the difference between maximum and minimum values, we can use it as a proxy to range. SELECT MAX(duration_minutes) - MIN(duration_minutes) AS range FROM netflix_titles; In PostgreSQL, the standard deviation of a numerical field/column is computed using the STDDEV() function. We’ll compute the standard deviation of duration_minutes field as shown below. SELECT ROUND(STDDEV(duration_minutes), 2) AS standard_deviation FROM netflix_titles; OR We can also compute standard deviation as the square root of variance as shown below. SELECT ROUND(SQRT(VARIANCE(duration_minutes)), 2) AS stddev_using_variance FROM netflix_titles; In PostgreSQL, the variance of a numerical field/column is computed using the VARIANCE() function. We’ll compute the variance of duration_minutes field as shown below. SELECT ROUND(VARIANCE(duration_minutes), 2) AS variance FROM netflix_titles; OR We can also compute variance as the square of standard deviation as shown below. SELECT ROUND(POWER(STDDEV(duration_minutes), 2), 2) AS variance_using_stddev FROM netflix_titles; In PostgreSQL, there is no function to directly compute the first quartile (Q1) of a numerical field/column. However, since Q1 is the 25th percentile, we can use it as a proxy to Q1. We’ll compute the Q1 of duration_minutes field as shown below. SELECT PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY duration_minutes) AS q1 FROM netflix_titles; In PostgreSQL, there is no function to directly compute the third quartile (Q3) of a numerical field/column. However, since Q3 is the 75th percentile, we can use it as a proxy to Q3. We’ll compute the Q3 of duration_minutes field as shown below. SELECT PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY duration_minutes) AS q3 FROM netflix_titles; In PostgreSQL, there is no function to directly compute the interquartile range (IQR) of a numerical field/column. However, since IQR is the difference between Q3 and Q1, we can use it as a proxy to IQR. We’ll compute the IQR of duration_minutes field as shown below. SELECT PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY duration_minutes) - PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY duration_minutes) AS iqr FROM netflix_titles; In PostgreSQL, there is no function to directly compute the skewness of a numerical field/column. However, since skewness is 3 * (mean-median) / standard_deviation, we can use it as a proxy to skewness. We’ll compute the skewness of duration_minutes field as shown below. To keep the code more readable we’ll use CTE to compute the mean, median and standard deviation. WITH mean_median_sd AS( SELECT AVG(duration_minutes) AS mean, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY duration_minutes) AS median, STDDEV(duration_minutes) AS stddev FROM netflix_titles)SELECT ROUND(3 * (mean - median)::NUMERIC / stddev, 2) AS skewness FROM mean_median_sd; We’ll put all the functions discussed earlier together and return them in a single table. In the below query, we’ll create two CTEs namely summary_stats (which returns the previously discussed statistics one per each column) and row_summary_stats (which returns the statistics one per each row). WITH RECURSIVEsummary_stats AS( SELECT ROUND(AVG(duration_minutes), 2) AS mean, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY duration_minutes) AS median, MIN(duration_minutes) AS min, MAX(duration_minutes) AS max, MAX(duration_minutes) - MIN(duration_minutes) AS range, ROUND(STDDEV(duration_minutes), 2) AS standard_deviation, ROUND(VARIANCE(duration_minutes), 2) AS variance, PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY duration_minutes) AS q1, PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY duration_minutes) AS q3 FROM netflix_titles),row_summary_stats AS(SELECT 1 AS sno, 'mean' AS statistic, mean AS value FROM summary_statsUNIONSELECT 2, 'median', median FROM summary_statsUNIONSELECT 3, 'minimum', min FROM summary_statsUNIONSELECT 4, 'maximum', max FROM summary_statsUNIONSELECT 5, 'range', range FROM summary_statsUNIONSELECT 6, 'standard deviation', standard_deviation FROM summary_statsUNIONSELECT 7, 'variance', variance FROM summary_statsUNIONSELECT 9, 'Q1', q1 FROM summary_statsUNIONSELECT 10, 'Q3', q3 FROM summary_statsUNIONSELECT 11, 'IQR', (q3 - q1) FROM summary_statsUNIONSELECT 12, 'skewness', ROUND(3 * (mean - median)::NUMERIC / standard_deviation, 2) AS skewness FROM summary_stats)SELECT * FROM row_summary_stats ORDER BY sno; Frequently used summary statistics for categorical variables are mode, cardinality (number of unique categories), frequency and relative frequency. In PostgreSQL, mode of a categorical field/column is computed using the MODE() function. We’ll compute the mode of rating field as shown below. SELECT MODE() WITHIN GROUP (ORDER BY rating) AS mode FROM netflix_titles; In PostgreSQL, there is no function to directly compute the number of unique values of a categorical field/column. However, we can count the distinct values of a variable as shown below. SELECT COUNT(DISTINCT rating) AS cardinality FROM netflix_titles; In Postgres, we can compute the frequency of the categories in a categorical variable using GROUP BY and COUNT. For relative frequency, we’ll use a CTE to count the total number of values in rating field and use it to compute the relative frequency. Since, not all databases support window functions we’ll use CTE. We’ll also discuss how to calculate relative frequency using window functions. WITH total_count AS(SELECT COUNT(rating) AS total_cnt FROM netflix_titles)SELECT rating, COUNT(rating) AS frequency, ROUND(COUNT(rating)::NUMERIC / (SELECT total_cnt FROM total_count), 4) AS relative_frequency FROM netflix_titles GROUP BY rating ORDER BY frequency DESC; In the above example, we’ve created a CTE that captures the count of values in the rating field. We then used it to calculate the percentage/relative frequency of each category in the rating field. Since, Postgres supports window functions, we’ll see a simpler way of calculating relative frequency using window functions. We’ll use OVER() to compute the sum of the counts of rating across each group which in turn is the total number of values in the rating field. SELECT rating, COUNT(rating) AS frequency, ROUND(COUNT(rating)::NUMERIC / SUM(COUNT(rating)) OVER(), 4) AS relative_frequency FROM netflix_titles GROUP BY rating ORDER BY frequency DESC; This brings the article to an end. We’ve discussed various functions to compute the frequently used summary statistics of numerical fields like mean, median, min, max, Q1, Q2, IQR, etc. and of categorical fields like cardinality, frequency, etc. Summary statistics can be used to get an idea of the data distribution and also aid in identifying potential outliers.
[ { "code": null, "e": 938, "s": 171, "text": "In this article, we’ll discuss how to derive summary statistics of numerical and categorical columns/fields using SQL. We’ll use the Netflix Movies and TV Shows dataset that’s downloaded from Tableau Public sample datasets (https://public.tableau.com/en-us/s/resources and go to Sample Data). This dataset consists of TV shows and movies available on Netflix as of 2019 and is sourced by Tableau from Kaggle and the updated version of the dataset can be found on Kaggle. However, for this article, we’ll use the older version available in Tableau sample datasets and import it into Postgres. This article assumes that the reader has basic knowledge of SQL queries and statistics. Below is a snapshot of the netflix_titles that we’ll be using throughout this article." }, { "code": null, "e": 1096, "s": 938, "text": "Frequently used summary statistics for numerical variables are mean, median, minimum, maximum, range, standard deviation, variance, Q1, Q3, IQR and skewness." }, { "code": null, "e": 1251, "s": 1096, "text": "In PostgreSQL, the mean of a numerical field/column is computed using the AVG() function. We’ll compute the mean of duration_minutes field as shown below." }, { "code": null, "e": 1311, "s": 1251, "text": "SELECT AVG(duration_minutes) AS mean FROM netflix_titles;" }, { "code": null, "e": 1641, "s": 1311, "text": "In PostgreSQL, there is no function to directly compute the median of a numerical field/column. However, since median is the 50th percentile, we can use it as a proxy to median. Percentile of a numerical variable is computed using the PERCENTILE_CONT() function. We’ll compute the median of duration_minutes field as shown below." }, { "code": null, "e": 1743, "s": 1641, "text": "SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY duration_minutes) AS median FROM netflix_titles;" }, { "code": null, "e": 1950, "s": 1743, "text": "WITHIN GROUP clause creates an ordered subset of data that can be used to perform aggregations. PERCENTILE_CONT takes the percentile required as an argument, in this case it is 0.5 i.e. the 50th percentile." }, { "code": null, "e": 2117, "s": 1950, "text": "In PostgreSQL, the minimum value of a numerical field/column is found using the MIN() function. We’ll find the minimum value of duration_minutes field as shown below." }, { "code": null, "e": 2177, "s": 2117, "text": "SELECT MIN(duration_minutes) AS min FROM netflix_titles;" }, { "code": null, "e": 2344, "s": 2177, "text": "In PostgreSQL, the maximum value of a numerical field/column is found using the MAX() function. We’ll find the maximum value of duration_minutes field as shown below." }, { "code": null, "e": 2404, "s": 2344, "text": "SELECT MAX(duration_minutes) AS max FROM netflix_titles;" }, { "code": null, "e": 2609, "s": 2404, "text": "In PostgreSQL, there is no function to directly compute the range of a numerical field/column. However, since range is the difference between maximum and minimum values, we can use it as a proxy to range." }, { "code": null, "e": 2696, "s": 2609, "text": "SELECT MAX(duration_minutes) - MIN(duration_minutes) AS range FROM netflix_titles;" }, { "code": null, "e": 2882, "s": 2696, "text": "In PostgreSQL, the standard deviation of a numerical field/column is computed using the STDDEV() function. We’ll compute the standard deviation of duration_minutes field as shown below." }, { "code": null, "e": 2971, "s": 2882, "text": "SELECT ROUND(STDDEV(duration_minutes), 2) AS standard_deviation FROM netflix_titles;" }, { "code": null, "e": 2974, "s": 2971, "text": "OR" }, { "code": null, "e": 3060, "s": 2974, "text": "We can also compute standard deviation as the square root of variance as shown below." }, { "code": null, "e": 3160, "s": 3060, "text": "SELECT ROUND(SQRT(VARIANCE(duration_minutes)), 2) AS stddev_using_variance FROM netflix_titles;" }, { "code": null, "e": 3328, "s": 3160, "text": "In PostgreSQL, the variance of a numerical field/column is computed using the VARIANCE() function. We’ll compute the variance of duration_minutes field as shown below." }, { "code": null, "e": 3409, "s": 3328, "text": "SELECT ROUND(VARIANCE(duration_minutes), 2) AS variance FROM netflix_titles;" }, { "code": null, "e": 3412, "s": 3409, "text": "OR" }, { "code": null, "e": 3493, "s": 3412, "text": "We can also compute variance as the square of standard deviation as shown below." }, { "code": null, "e": 3595, "s": 3493, "text": "SELECT ROUND(POWER(STDDEV(duration_minutes), 2), 2) AS variance_using_stddev FROM netflix_titles;" }, { "code": null, "e": 3841, "s": 3595, "text": "In PostgreSQL, there is no function to directly compute the first quartile (Q1) of a numerical field/column. However, since Q1 is the 25th percentile, we can use it as a proxy to Q1. We’ll compute the Q1 of duration_minutes field as shown below." }, { "code": null, "e": 3941, "s": 3841, "text": "SELECT PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY duration_minutes) AS q1 FROM netflix_titles;" }, { "code": null, "e": 4187, "s": 3941, "text": "In PostgreSQL, there is no function to directly compute the third quartile (Q3) of a numerical field/column. However, since Q3 is the 75th percentile, we can use it as a proxy to Q3. We’ll compute the Q3 of duration_minutes field as shown below." }, { "code": null, "e": 4287, "s": 4187, "text": "SELECT PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY duration_minutes) AS q3 FROM netflix_titles;" }, { "code": null, "e": 4555, "s": 4287, "text": "In PostgreSQL, there is no function to directly compute the interquartile range (IQR) of a numerical field/column. However, since IQR is the difference between Q3 and Q1, we can use it as a proxy to IQR. We’ll compute the IQR of duration_minutes field as shown below." }, { "code": null, "e": 4722, "s": 4555, "text": "SELECT PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY duration_minutes) - PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY duration_minutes) AS iqr FROM netflix_titles;" }, { "code": null, "e": 5091, "s": 4722, "text": "In PostgreSQL, there is no function to directly compute the skewness of a numerical field/column. However, since skewness is 3 * (mean-median) / standard_deviation, we can use it as a proxy to skewness. We’ll compute the skewness of duration_minutes field as shown below. To keep the code more readable we’ll use CTE to compute the mean, median and standard deviation." }, { "code": null, "e": 5377, "s": 5091, "text": "WITH mean_median_sd AS( SELECT AVG(duration_minutes) AS mean, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY duration_minutes) AS median, STDDEV(duration_minutes) AS stddev FROM netflix_titles)SELECT ROUND(3 * (mean - median)::NUMERIC / stddev, 2) AS skewness FROM mean_median_sd;" }, { "code": null, "e": 5673, "s": 5377, "text": "We’ll put all the functions discussed earlier together and return them in a single table. In the below query, we’ll create two CTEs namely summary_stats (which returns the previously discussed statistics one per each column) and row_summary_stats (which returns the statistics one per each row)." }, { "code": null, "e": 6993, "s": 5673, "text": "WITH RECURSIVEsummary_stats AS( SELECT ROUND(AVG(duration_minutes), 2) AS mean, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY duration_minutes) AS median, MIN(duration_minutes) AS min, MAX(duration_minutes) AS max, MAX(duration_minutes) - MIN(duration_minutes) AS range, ROUND(STDDEV(duration_minutes), 2) AS standard_deviation, ROUND(VARIANCE(duration_minutes), 2) AS variance, PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY duration_minutes) AS q1, PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY duration_minutes) AS q3 FROM netflix_titles),row_summary_stats AS(SELECT 1 AS sno, 'mean' AS statistic, mean AS value FROM summary_statsUNIONSELECT 2, 'median', median FROM summary_statsUNIONSELECT 3, 'minimum', min FROM summary_statsUNIONSELECT 4, 'maximum', max FROM summary_statsUNIONSELECT 5, 'range', range FROM summary_statsUNIONSELECT 6, 'standard deviation', standard_deviation FROM summary_statsUNIONSELECT 7, 'variance', variance FROM summary_statsUNIONSELECT 9, 'Q1', q1 FROM summary_statsUNIONSELECT 10, 'Q3', q3 FROM summary_statsUNIONSELECT 11, 'IQR', (q3 - q1) FROM summary_statsUNIONSELECT 12, 'skewness', ROUND(3 * (mean - median)::NUMERIC / standard_deviation, 2) AS skewness FROM summary_stats)SELECT * FROM row_summary_stats ORDER BY sno;" }, { "code": null, "e": 7141, "s": 6993, "text": "Frequently used summary statistics for categorical variables are mode, cardinality (number of unique categories), frequency and relative frequency." }, { "code": null, "e": 7285, "s": 7141, "text": "In PostgreSQL, mode of a categorical field/column is computed using the MODE() function. We’ll compute the mode of rating field as shown below." }, { "code": null, "e": 7361, "s": 7285, "text": "SELECT MODE() WITHIN GROUP (ORDER BY rating) AS mode FROM netflix_titles;" }, { "code": null, "e": 7548, "s": 7361, "text": "In PostgreSQL, there is no function to directly compute the number of unique values of a categorical field/column. However, we can count the distinct values of a variable as shown below." }, { "code": null, "e": 7616, "s": 7548, "text": "SELECT COUNT(DISTINCT rating) AS cardinality FROM netflix_titles;" }, { "code": null, "e": 8010, "s": 7616, "text": "In Postgres, we can compute the frequency of the categories in a categorical variable using GROUP BY and COUNT. For relative frequency, we’ll use a CTE to count the total number of values in rating field and use it to compute the relative frequency. Since, not all databases support window functions we’ll use CTE. We’ll also discuss how to calculate relative frequency using window functions." }, { "code": null, "e": 8296, "s": 8010, "text": "WITH total_count AS(SELECT COUNT(rating) AS total_cnt FROM netflix_titles)SELECT rating, COUNT(rating) AS frequency, ROUND(COUNT(rating)::NUMERIC / (SELECT total_cnt FROM total_count), 4) AS relative_frequency FROM netflix_titles GROUP BY rating ORDER BY frequency DESC;" }, { "code": null, "e": 8762, "s": 8296, "text": "In the above example, we’ve created a CTE that captures the count of values in the rating field. We then used it to calculate the percentage/relative frequency of each category in the rating field. Since, Postgres supports window functions, we’ll see a simpler way of calculating relative frequency using window functions. We’ll use OVER() to compute the sum of the counts of rating across each group which in turn is the total number of values in the rating field." }, { "code": null, "e": 8962, "s": 8762, "text": "SELECT rating, COUNT(rating) AS frequency, ROUND(COUNT(rating)::NUMERIC / SUM(COUNT(rating)) OVER(), 4) AS relative_frequency FROM netflix_titles GROUP BY rating ORDER BY frequency DESC;" } ]
Prototype - AJAX Response() Method
This AJAX Ajax.Response is the object passed as the first argument of all Ajax requests callbacks. This is a wrapper around the native xmlHttpRequest object. It normalizes cross-browser issues while adding support for JSON via the responseJSON and headerJSON properties. document Object or null Object, Array or null Object, Array or null Following is the example to show the usage of status and responseText properties − <html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script> function SubmitRequest() { new Ajax.Request('/cgi-bin/ajax.cgi', { method: 'get', onSuccess: successFunc, onFailure: failureFunc }); } function successFunc(response) { if (200 == response.status) { alert("Call is success"); } var container = $('notice'); var content = response.responseText; container.update(content); } function failureFunc(response) { alert("Call is failed" ); } </script> </head> <body> <p>Click submit button to see how current notice changes.</p> <br /> <div id = "notice">Current Notice</div> <br /> <br /> <input type = "button" value = "Submit" onclick = "SubmitRequest();"/> </body> </html> Here is the content of ajax.cgi. #!/usr/bin/perl print "Content-type: text/html\n\n"; print "This content is returned by AJAX cgi "; print "Current Time " . localtime; Click submit button to see how current notice changes. String or null String or null Following is the example to show the usage of getAllHeaders() and getResponseHeader(name) methods − <html> <head> <title>Prototype examples</title> <script type = "text/javascript" src = "/javascript/prototype.js"></script> <script> function SubmitRequest() { new Ajax.Request('/cgi-bin/ajax.cgi', { method: 'get', onSuccess: successFunc }); } function successFunc(response) { var content = response.getAllHeaders(); var container = $(header1); container.update(content); var content = response.getResponseHeader('Content-Type'); var container = $(header2); container.update(content); } </script> </head> <body> <p>Click submit button to see the result:</p> <br /> <div id = "header1">All Headers</div> <div id = "header2">Content Type</div> <br /> <br /> <input type = "button" value = "Submit" onclick = "SubmitRequest();"/> </body> </html> Click submit button to see the result: 127 Lectures 11.5 hours Aleksandar Cucukovic Print Add Notes Bookmark this page
[ { "code": null, "e": 2160, "s": 2061, "text": "This AJAX Ajax.Response is the object passed as the first argument of all Ajax requests callbacks." }, { "code": null, "e": 2332, "s": 2160, "text": "This is a wrapper around the native xmlHttpRequest object. It normalizes cross-browser issues while adding support for JSON via the responseJSON and headerJSON properties." }, { "code": null, "e": 2348, "s": 2332, "text": "document Object" }, { "code": null, "e": 2356, "s": 2348, "text": "or null" }, { "code": null, "e": 2370, "s": 2356, "text": "Object, Array" }, { "code": null, "e": 2378, "s": 2370, "text": "or null" }, { "code": null, "e": 2392, "s": 2378, "text": "Object, Array" }, { "code": null, "e": 2400, "s": 2392, "text": "or null" }, { "code": null, "e": 2484, "s": 2400, "text": "Following is the example to show the usage of status and responseText properties −" }, { "code": null, "e": 3527, "s": 2484, "text": "<html>\n <head>\n <title>Prototype examples</title>\n <script type = \"text/javascript\" src = \"/javascript/prototype.js\"></script>\n \n <script>\n function SubmitRequest() {\n new Ajax.Request('/cgi-bin/ajax.cgi', {\n method: 'get',\n onSuccess: successFunc,\n onFailure: failureFunc\n });\n }\n function successFunc(response) {\n if (200 == response.status) {\n alert(\"Call is success\");\n }\n var container = $('notice');\n var content = response.responseText;\n container.update(content);\n }\n function failureFunc(response) {\n alert(\"Call is failed\" );\n }\n </script>\n </head>\n\n <body>\n <p>Click submit button to see how current notice changes.</p>\n <br />\n \n <div id = \"notice\">Current Notice</div>\n <br />\n <br />\n <input type = \"button\" value = \"Submit\" onclick = \"SubmitRequest();\"/>\n </body>\n</html>" }, { "code": null, "e": 3560, "s": 3527, "text": "Here is the content of ajax.cgi." }, { "code": null, "e": 3697, "s": 3560, "text": "#!/usr/bin/perl\n\nprint \"Content-type: text/html\\n\\n\";\n\nprint \"This content is returned by AJAX cgi \";\nprint \"Current Time \" . localtime;" }, { "code": null, "e": 3752, "s": 3697, "text": "Click submit button to see how current notice changes." }, { "code": null, "e": 3762, "s": 3752, "text": "String or" }, { "code": null, "e": 3767, "s": 3762, "text": "null" }, { "code": null, "e": 3777, "s": 3767, "text": "String or" }, { "code": null, "e": 3782, "s": 3777, "text": "null" }, { "code": null, "e": 3883, "s": 3782, "text": "Following is the example to show the usage of getAllHeaders() and getResponseHeader(name) methods −" }, { "code": null, "e": 4876, "s": 3883, "text": "<html>\n <head>\n <title>Prototype examples</title>\n <script type = \"text/javascript\" src = \"/javascript/prototype.js\"></script>\n \n <script>\n function SubmitRequest() {\n new Ajax.Request('/cgi-bin/ajax.cgi', {\n method: 'get',\n onSuccess: successFunc\n });\n }\n function successFunc(response) {\n var content = response.getAllHeaders();\n var container = $(header1);\n container.update(content);\n var content = response.getResponseHeader('Content-Type');\n var container = $(header2);\n container.update(content);\n }\n </script>\n </head>\n\n <body>\n <p>Click submit button to see the result:</p>\n <br />\n \n <div id = \"header1\">All Headers</div>\n <div id = \"header2\">Content Type</div>\n <br />\n <br />\n <input type = \"button\" value = \"Submit\" onclick = \"SubmitRequest();\"/>\n </body>\n</html>" }, { "code": null, "e": 4915, "s": 4876, "text": "Click submit button to see the result:" }, { "code": null, "e": 4952, "s": 4915, "text": "\n 127 Lectures \n 11.5 hours \n" }, { "code": null, "e": 4974, "s": 4952, "text": " Aleksandar Cucukovic" }, { "code": null, "e": 4981, "s": 4974, "text": " Print" }, { "code": null, "e": 4992, "s": 4981, "text": " Add Notes" } ]
Display strikethrough text in HTML
The HTML <strike> tag specifies strikethrough text. This tag is deprecated now, use <del> instead. The HTML <del> tag is used for markup of deleted text i.e. strikethrough text. You can try to run the following code to display strikethrough text in HTML − <!DOCTYPE html> <html> <head> <title>HTML strike Tag</title> </head> <body> The HTML strike tag renders a <del>strike</del> through the middle of the text. </body> </html>
[ { "code": null, "e": 1240, "s": 1062, "text": "The HTML <strike> tag specifies strikethrough text. This tag is deprecated now, use <del> instead. The HTML <del> tag is used for markup of deleted text i.e. strikethrough text." }, { "code": null, "e": 1318, "s": 1240, "text": "You can try to run the following code to display strikethrough text in HTML −" }, { "code": null, "e": 1514, "s": 1318, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML strike Tag</title>\n </head>\n <body>\n The HTML strike tag renders a <del>strike</del> through the middle of the text.\n </body>\n</html>" } ]
How do JavaScript primitive/object types passed in functions?
Following is the code to pass JavaScript primitive and object types to function − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Passing primitive/object types to function</h1> <div class="result"></div> <div class="result"></div> <button class="Btn">Click here</button> <h3>Click on the above button to pass primitive and object to a function and call it</h3> <script> let BtnEle = document.querySelector(".Btn"); let resEle = document.querySelector(".result"); let person = { name: "Rohan", age: 12, city: "Delhi" }; function printObj(obj) { resEle.innerHTML = "Name = " + obj.name + "<br>"; resEle.innerHTML += "age = " + obj.age + "<br>"; resEle.innerHTML += "city = " + obj.city + "<br>"; } function printPrimitive(prim) { resEle.innerHTML += prim; } BtnEle.addEventListener("click", () => { printObj(person); printPrimitive(22); }); </script> </body> </html> On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1144, "s": 1062, "text": "Following is the code to pass JavaScript primitive and object types to function −" }, { "code": null, "e": 1155, "s": 1144, "text": " Live Demo" }, { "code": null, "e": 2325, "s": 1155, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>Passing primitive/object types to function</h1>\n<div class=\"result\"></div>\n<div class=\"result\"></div>\n<button class=\"Btn\">Click here</button>\n<h3>Click on the above button to pass primitive and object to a function and call it</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let resEle = document.querySelector(\".result\");\n let person = { name: \"Rohan\", age: 12, city: \"Delhi\" };\n function printObj(obj) {\n resEle.innerHTML = \"Name = \" + obj.name + \"<br>\";\n resEle.innerHTML += \"age = \" + obj.age + \"<br>\";\n resEle.innerHTML += \"city = \" + obj.city + \"<br>\";\n }\n function printPrimitive(prim) {\n resEle.innerHTML += prim;\n }\n BtnEle.addEventListener(\"click\", () => {\n printObj(person);\n printPrimitive(22);\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2363, "s": 2325, "text": "On clicking the ‘CLICK HERE’ button −" } ]
Modeling Functions. From linear to logistic regression | by Shinichi Okada | Towards Data Science
Table of ContentsIntroduction1. Linear models2. Quadratic models3. Cubic models4. Exponential models5. Logarithmic models6. Sinusoidal models7. Logistic modelsConclusion We are going to draw a scatter graph and model a regression line from linear to logistic with Jupyter Notebook. The first one is a linear model. A linear model is express as y=mx+c. We are going to use numpy.array or numpy.arange to create data. If you want to read more about a linear relationship, please read A Measure of Linear Relationship. We import Python libraries numpy and matplotlib. We create a year and a co2 array. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineyear=np.array([1980,1982,1984,1986,1988,1990,1992,1994,1996,1998,2000])co2=np.array([338.7,341.1,344.4,347.2,351.5,354.2,356.4,358.9,362.6,366.6,369.4]) First, we create a scatter plot using matplotlib. Add the title, label, x, and y-axis labels. You need to use show() method. You can plot without it but this will remove unnecessary outputs. plt.scatter(year,co2,label='CO2')plt.title("Year vs CO2")plt.xlabel('Year')plt.ylabel('CO2')plt.legend()plt.show() As you can see in the above graph, you have decimals in the x-axis. We use the first three lines to make them integers in the following codes. from matplotlib.ticker import MaxNLocatorax = plt.figure().gca()ax.xaxis.set_major_locator(MaxNLocator(integer=True))plt.scatter(year,co2,label='CO2')plt.title("Year vs CO2")plt.xlabel('Year')plt.ylabel('CO2')plt.legend()plt.show() The easiest way is to use numpy.polyfit. By setting order to 1, it will return an array of linear coefficients. Using it in numpy.poly1d returns an equation using the coefficients. import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import MaxNLocatorfrom sklearn.linear_model import LinearRegression%matplotlib inlineax = plt.figure().gca()ax.xaxis.set_major_locator(MaxNLocator(integer=True))year=np.array([1980,1982,1984,1986,1988,1990,1992,1994,1996,1998,2000])co2=np.array([338.7,341.1,344.4,347.2,351.5,354.2,356.4,358.9,362.6,366.6,369.4])coef = np.polyfit(year, co2, 1)equ = np.poly1d(coef)x_plot = np.linspace(1975,2005,100)y_plot = equ(x_plot)plt.plot(x_plot, y_plot, color='r')plt.scatter(year,co2,label='CO2')plt.title("Year vs CO2")plt.xlabel('Year')plt.ylabel('CO2')plt.legend()plt.show() The second way to find the regression slope and intercept is to use sklearn.linear_model.LinearRegression. This class requires the x values to be one column. We modify year data using reshape(-1,1). The original year data has 1 by 11 shape. You need to reshape the year data to 11 by 1. year1=year.reshape((-1,1))print(np.shape(year))print(np.shape(year1)) We import sklearn.linear_model.LinearRegression, reshape the year data, fit our data using LinearRegression().fit(). This will return the slope, coef_ and the y-intercept, intercept_. coef_ returns an array, so we take the first item by using reg.coef_[0]. Let’s print out our regression line equation. from sklearn.linear_model import LinearRegressionyear1=year.reshape((-1,1))reg = LinearRegression().fit(year1,co2)slope=reg.coef_[0]intercept=reg.intercept_print(f'The equation of regression line is y={slope:.3f}x+{intercept:.3f}.') We draw a scatter plot and our linear regression line together. We use a new x domain from 1975 to 2005 taking 100 samples for the regression line, np.linspace(1975,2005,100). Then using x domain, slope, and y-intercept to draw a regression line. import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import MaxNLocatorfrom sklearn.linear_model import LinearRegression%matplotlib inlineax = plt.figure().gca()ax.xaxis.set_major_locator(MaxNLocator(integer=True))year=np.array([1980,1982,1984,1986,1988,1990,1992,1994,1996,1998,2000])co2=np.array([338.7,341.1,344.4,347.2,351.5,354.2,356.4,358.9,362.6,366.6,369.4])year1=year.reshape((-1,1))reg = LinearRegression().fit(year1,co2) slope=reg.coef_[0]intercept=reg.intercept_plt.scatter(year,co2,label='CO2')X_plot = np.linspace(1975,2005,100)Y_plot = slope*X_plot+interceptplt.plot(X_plot, Y_plot, color='r')plt.title("Year vs CO2")plt.xlabel('Year')plt.ylabel('CO2')plt.legend()plt.show()print(f'The equation of regression line is y={slope:.3f}x+{intercept:.3f}.') Another way to find the regression slope and intercept is to use scipy.stats.linregress. This returns slope, intercept, rvalue, pvalue, stderr. from scipy.stats import linregressslope, intercept, r_value, p_value, std_err = linregress(year,co2)print(f'The equation of regression line is y={slope:.3f}x+{intercept:.3f}.') To draw a line we need x points. We use np.linspace which is numpy.linspace since we used import numpy as np. Our data is from 1975 to 2000. So let's use 1960 for start, 2005 for stop and 100 for the number of samples. import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import linregress%matplotlib inlineyear=np.array([1980,1982,1984,1986,1988,1990,1992,1994,1996,1998,2000])co2=np.array([338.7,341.1,344.4,347.2,351.5,354.2,356.4,358.9,362.6,366.6,369.4])X_plot = np.linspace(1975,2005,100)Y_plot = slope*X_plot+interceptplt.plot(X_plot, Y_plot, color='r')plt.show() Now we put a scatter plot, regression line, and a regression equation together. import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import MaxNLocatorfrom scipy.stats import linregress%matplotlib inlineax = plt.figure().gca()ax.xaxis.set_major_locator(MaxNLocator(integer=True))slope, intercept, r_value, p_value, std_err = linregress(year,co2)X_plot = np.linspace(1975,2005,100)Y_plot = slope*X_plot+interceptplt.plot(X_plot, Y_plot, color='r')plt.scatter(year,co2,label='CO2')plt.title("Year vs CO2")plt.xlabel('Year')plt.ylabel('CO2')plt.legend()plt.show()print(f'The equation of regression line is y={slope:.3f}x+{intercept:.3f}.') Use the following data to graph a scatter plot and regression line. Find a linear regression equation. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinetemp = np.array([55,60,65,70,75,80,85,90])rate = np.array([45,80,92,114,141,174,202,226]) Did you draw a scatter and regression graph? The regression line should be y=5.119x−236.88. towardsdatascience.com We use Numpy’s arange to create 10 integers from 0 to 9. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinetime = np.arange(10)height = np.array([450,445,430,409,375,331,280,215,144,59]) Let’s plot the above data. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineplt.scatter(time,height,label='Height of a ball')plt.title("Time vs Height")plt.xlabel('Time')plt.ylabel('Height')plt.legend()plt.show() numpy.polyfit fits a polynomial. It requires x, y, and degree of the fitting polynomial. 2 for a quadratic, 3 for a cubic, etc. It returns an array with polynomial coefficients from a higher power to the constant. For a quadratic function, these are a, b and c in: coef = np.polyfit(time, height, 2)coef Let’s print out the quadratic regression line. print(f'The equation of regression line is y=')print(equ) Or using coefficients the regression line is: print(f'The equation of regression line is y={coef[0]:.3f}x^2+{coef[1]:.3f}x+{coef[2]:.3f}.') We use NumPy's poly1d and polyfitagain. np.poly1d(coefficients) will return a polynomial equation using our coefficient. equ = np.poly1d(coef) We can find a value for any x. For example, if you want to find y value when x=1: equ(1) We use this to draw our regression line. We use numpy.linspace to define x values from 0 to 10 for 100 samples. And use it in the equ for y values. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinex_plot = np.linspace(0,10,100)y_plot = equ(x_plot)plt.plot(x_plot, y_plot, color='r')plt.show() We put it all together. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinetime = np.arange(10)height = np.array([450,445,430,409,375,331,280,215,144,59])coef = np.polyfit(time, height, 2)equ = np.poly1d(coef)x_plot = np.linspace(0,10,100)y_plot = equ(x_plot)plt.plot(x_plot, y_plot, color='r')plt.scatter(time,height,label='Height of a ball')plt.title("Time vs Height")plt.xlabel('Time')plt.ylabel('Height')plt.legend()plt.show()print(f'The equation of regression line is y=')print(equ) By using the following data, draw a scatter plot and regression line in a graph. Find the quadratic regression equation. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineangle = np.arange(20,80,10)distance = np.array([371,465,511,498,439,325]) Could you draw a scatter and regression line? The quadratic equation should be: towardsdatascience.com You can use the same method as the quadratic function above. We are going to use plyfit and poly1d. First, we prepare the data. And let’s draw a scatter plot. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineengspeed = np.arange(9,23,2)avespeed = np.array([6.45,7.44,8.88,9.66,10.98,12.56,15.44])plt.scatter(engspeed,avespeed,label='Speed of different boat engine')plt.title("Average speed of different boat engine")plt.xlabel('Engine speed')plt.ylabel('Boad speed')plt.ylim(0,20)plt.legend()plt.show() Using polyfit returns coefficients. For a cubic function, a, b, c, and d in: coef = np.polyfit(engspeed, avespeed, 3)print(coef) We put all together. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineengspeed = np.arange(9,23,2)avespeed = np.array([6.45,7.44,8.88,9.66,10.98,12.56,15.44])plt.scatter(engspeed,avespeed,label='Speed of different boat engine')coef = np.polyfit(engspeed, avespeed, 3)equ = np.poly1d(coef)x_plot = np.linspace(8,25,100)y_plot = equ(x_plot)plt.plot(x_plot, y_plot, color='r')plt.title("Average speed of different boat engine")plt.xlabel('Engine speed')plt.ylabel('Boad speed')plt.ylim(0,20)plt.legend()plt.show()a, b, c, d = coefprint(f'The equation of regression line is y={a:.3f}x^3+{b:.3f}x^2+{c:.3f}x+{d}.') Draw a scatter plot and a cubic regression line using the following data. Print the cubic equation. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinex=np.arange(1,8)y=np.array([0,0.012,0.06,0.162,0.336,0.6,0.972]) Could you plot a scatter and a regression line? The regression line equation should be: The coefficients are [ 3.00000000e-03, -1.16796094e-16, -9.00000000e-03, 6.00000000e-03]. These means: The second one is practically 0. Try the following to see both are the same 0.3. print(300e-03)print(300*10**(-3)) We are going to explore three exponential models. Let’s set up the data. And draw a scatter plot. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineday = np.arange(0,8)weight = np.array([251,209,157,129,103,81,66,49])plt.scatter(day,weight,label='Weight change')plt.title("Day vs Weight")plt.xlabel('Day')plt.ylabel('Weight')plt.legend()plt.show() We are going to use scipy.optimize.curve_fit. This requires a function, x and y values, and initial values, p0 in array form. Finding proper p0 is a bit of trial and error. You have to test different values. We use p0=(1, 1e-6, 1). It returns optimal values for the parameters and the estimated covariance of popt. Our first exponential function uses a, b, and c. We are going to define a function first. This is used in the curve_fit method. For a smooth curve, we set x values using numpy.linspace from 0 to 7 with 100 samples. import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlinedef func(x, a, b, c): return a * np.exp(-b * x) + cpopt, pcov = curve_fit(func, day, weight, p0=[1, 1e-6, 1])x_plot=np.linspace(0,7,100)plt.plot(x_plot, func(x_plot, *popt), 'r-')plt.scatter(day,weight,label='Day vs Weight')plt.title("Day vs Weight a*e^-bx +c")plt.xlabel('Day')plt.ylabel('Weight')plt.legend()plt.show()# equationa=popt[0].round(2)b=popt[1].round(2)c=popt[2].round(2)print(f'The equation of regression line is y={a}e^({b}x)+{c}') The second function uses a and b. We define the function accordingly. import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlinedef func2(x, a, b): return a * np.exp(-b * x)popt, pcov = curve_fit(func2, day, weight, p0=[1, 1e-6])x_plot=np.linspace(0,7,100)plt.plot(x_plot, func2(x_plot, *popt), 'r-')plt.scatter(day,weight,label='Day vs Weight')plt.title("Day vs Weight a*e^-bx")plt.xlabel('Day')plt.ylabel('Weight')plt.legend()plt.show()# equationa=popt[0].round(2)b=popt[1].round(2)print(f'The equation of regression line is y={a}e^({b}x)') The last exponential function uses a and b. We modify the function accordingly. import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlinedef func3(x, a, b): return a * b ** xpopt, pcov = curve_fit(func3, day, weight, p0=[1, 1e-6])x_plot=np.linspace(0,7,100)plt.plot(x_plot, func3(x_plot, *popt), 'r-')plt.scatter(day,weight,label='Day vs Weight')plt.title("Day vs Weight a*b^x")plt.xlabel('Day')plt.ylabel('Weight')plt.legend()plt.show()# equationa=popt[0].round(4)b=popt[1].round(4)print(f'The equation of regression line is y={a}*{b}^x') TI Nspire’s exponential regression fits the model equation y=ab^x to the data using a least-squares fit on transformed values x and ln(y). It returns a different value. Using the following data find an exponential function in the form of ab^x. Plot a scatter diagram and draw a regression line. import numpy as npweek = np.arange(1,21)views = np.array([102365, 38716,21617,24305,9321,14148,2103,8285,5098,3777,831,1007,834,34,378,204,6,42,54,31]) Generally, we use the semi-log model for an exponential function: We set up our mock data and plot a scatter diagram. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinetime = np.arange(0,30,4)bacteria = np.array([20,150,453,920,1820,9765,15487,19450])plt.scatter(time,bacteria,label='Bacteria')plt.title("Time vs Bacteria")plt.xlabel('time')plt.ylabel('bacteria')plt.legend()plt.show() We are going to take a natural log for the bacteria values by using numpy.log. numpy.log is the natural logarithm. This should show a linear trend. We need to modify the title and y label with ln(bacteria). import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinetime = np.arange(0,30,4)bacteria = np.array([20,150,453,920,1820,9765,15487,19450])plt.scatter(time,np.log(bacteria),label='Bacteria')plt.title("Time vs ln(Bacteria)")plt.xlabel('time')plt.ylabel('ln(bacteria)')plt.legend()plt.show() We use numpy.polyfit which we used in a quadratic and cubic function. We use 1 in numpy.polyfit() so that it will return a linear regression. numpy.polyfit returns all coefficients for our equation. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinetime = np.arange(0,30,4)bacteria = np.array([20,150,453,920,1820,9765,15487,19450])p = np.polyfit(time, np.log(bacteria), 1)plt.plot(time, p[0] * time + p[1], 'g--', label='Semi-log graph')plt.scatter(time,np.log(bacteria),label='Bacteria')plt.title("Time vs Bacteria")plt.xlabel('time')plt.ylabel('bacteria')plt.legend()plt.show()print(f'The equation of regression line is y={p[0]:.3f} * x + {p[1]:.3f}') The log-log model is used for a power function. Let’s set up data and plot a scatter diagram. import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinex=np.array([2,30,70,100,150])y=np.array([4.24,16.4,25.1,30,36.7])plt.scatter(x,y,label='Log-log')plt.title("Log-Log model")plt.xlabel('x')plt.ylabel('y')plt.legend()plt.show() We take a natural log for x and y values using numpy.log. We need to modify the x and y labels to ln(x) and ln(y). import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinex=np.array([2,30,70,100,150])y=np.array([4.24,16.4,25.1,30,36.7])p = np.polyfit(np.log(x), np.log(y), 1)plt.plot(np.log(x), p[0] * np.log(x) + p[1], 'r--', label='Regression line')plt.scatter(np.log(x),np.log(y),label='log-log')plt.title("Log-log regression")plt.xlabel('ln(x)')plt.ylabel('ln(y)')plt.legend()plt.show()print(f'The equation of regression line is ln(y)={p[0]:.3f} * ln(x) + {p[1]:.3f}') Let’s try a sinusoidal function. We set our data and plot a scatter graph. Since we are going to use scipy.optimize.curve_fit, let's import it as well. We used it in the exponential models. We set up our data and draw a scatter plot. import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlineyear=np.arange(0,24,2)population=np.array([10.2,11.1,12,11.7,10.6,10,10.6,11.7,12,11.1,10.2,10.2])plt.scatter(year,population,label='Population')plt.title("Year vs Population")plt.xlabel('Year')plt.ylabel('Population')plt.legend()plt.show() We define a function called sinfunc. This takes parameters x, a, b, c, d. We use numpy.radians for c. import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlineyear=np.arange(0,24,2)population=np.array([10.2,11.1,12,11.7,10.6,10,10.6,11.7,12,11.1,10.2,10.2])def sinfunc(x, a, b, c, d): return a * np.sin(b * (x - np.radians(c)))+dpopt, pcov = curve_fit(sinfunc, year, population, p0=[1,0.4,1,5])x_data = np.linspace(0, 25, num=100)plt.scatter(year,population,label='Population')plt.plot(x_data, sinfunc(x_data, *popt), 'r-',label='Fitted function')plt.title("Year vs Population")plt.xlabel('Year')plt.ylabel('Population')plt.legend()plt.show()a, b, c, d = poptprint(f'The equation of regression line is y={a:.3f} * sin({b:.3f}(x-{np.radians(c):.3f}))+{d:.3f}') Using the table below, draw a scatter plot and find a cosine regression function. You may have different coefficients. I used We set up data and plot a scatter diagram. We set the domain from -10 to 10 and range from 0 to 250, using plt.xlim and plt.ylim. We are going to use scipy.optimize.curve_fit for logistic regression. import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlinex=np.arange(0,10)y=np.array([52,133,203,230,237,239.5,239.8,239.9,240,240])plt.scatter(x, y, label='Regression line')plt.title("Logistic regression")plt.xlabel('x')plt.ylabel('y')plt.xlim(-10,10)plt.ylim(0,250)plt.legend()plt.show() We define our logistic function using logifunc. We find the function parameter in popt using curve_fit. For the regression line, we set a new domain for the function, x_data from -10 to 10. We plot the line using plt.plot. import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlinex=np.arange(0,10.0)y=np.array([52,133,203,230,237,239.5,239.8,239.9,240,240])def logifunc(x,L,c,k): return L/ (1 + c*np.exp(-k*x))popt, pcov = curve_fit(logifunc, x, y, p0=[200,1,1])x_data = np.linspace(-10, 10, num=100)plt.scatter(x,y,label='Logistic function')plt.plot(x_data, logifunc(x_data, *popt), 'r-',label='Fitted function')plt.title("Logistic")plt.xlabel('x')plt.ylabel('y')plt.xlim(-10,10)plt.ylim(0,250)plt.legend()plt.show() Sometimes your data may have negative values in y coordinates. import pandas as pddf = pd.read_csv('http://bit.ly/2tUIZjK')df.head() The minimum value for the data needs to be zero. And ideally, the sigmoid midpoint is also zero. But the above data set satisfies neither of them. Using equation (1–2), and adding offset value works for this data set. x=df.T.iloc[0]y=df.T.iloc[1]def logifunc(x,L,x0,k,off): return L / (1 + np.exp(-k*(x-x0)))+offplt.scatter(x,y,label='Logistic function')popt, pcov = curve_fit(logifunc, x, y, p0=[50,185,0.1,-222])plt.scatter(x,y,label='Logistic function')x_data = np.linspace(170,205,num=100)plt.plot(x_data, logifunc(x_data, *popt), 'r-',label='Fitted function')plt.legend()plt.show()print(popt) scipy.optimize.curve_fit was useful for many functions. The only problem was to find good initial values in p0. Sometimes different p0 values return different popt. You can try LMFIT. Get full access to every story on Medium by becoming a member.
[ { "code": null, "e": 217, "s": 47, "text": "Table of ContentsIntroduction1. Linear models2. Quadratic models3. Cubic models4. Exponential models5. Logarithmic models6. Sinusoidal models7. Logistic modelsConclusion" }, { "code": null, "e": 329, "s": 217, "text": "We are going to draw a scatter graph and model a regression line from linear to logistic with Jupyter Notebook." }, { "code": null, "e": 646, "s": 329, "text": "The first one is a linear model. A linear model is express as y=mx+c. We are going to use numpy.array or numpy.arange to create data. If you want to read more about a linear relationship, please read A Measure of Linear Relationship. We import Python libraries numpy and matplotlib. We create a year and a co2 array." }, { "code": null, "e": 866, "s": 646, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineyear=np.array([1980,1982,1984,1986,1988,1990,1992,1994,1996,1998,2000])co2=np.array([338.7,341.1,344.4,347.2,351.5,354.2,356.4,358.9,362.6,366.6,369.4])" }, { "code": null, "e": 1057, "s": 866, "text": "First, we create a scatter plot using matplotlib. Add the title, label, x, and y-axis labels. You need to use show() method. You can plot without it but this will remove unnecessary outputs." }, { "code": null, "e": 1172, "s": 1057, "text": "plt.scatter(year,co2,label='CO2')plt.title(\"Year vs CO2\")plt.xlabel('Year')plt.ylabel('CO2')plt.legend()plt.show()" }, { "code": null, "e": 1315, "s": 1172, "text": "As you can see in the above graph, you have decimals in the x-axis. We use the first three lines to make them integers in the following codes." }, { "code": null, "e": 1547, "s": 1315, "text": "from matplotlib.ticker import MaxNLocatorax = plt.figure().gca()ax.xaxis.set_major_locator(MaxNLocator(integer=True))plt.scatter(year,co2,label='CO2')plt.title(\"Year vs CO2\")plt.xlabel('Year')plt.ylabel('CO2')plt.legend()plt.show()" }, { "code": null, "e": 1728, "s": 1547, "text": "The easiest way is to use numpy.polyfit. By setting order to 1, it will return an array of linear coefficients. Using it in numpy.poly1d returns an equation using the coefficients." }, { "code": null, "e": 2370, "s": 1728, "text": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import MaxNLocatorfrom sklearn.linear_model import LinearRegression%matplotlib inlineax = plt.figure().gca()ax.xaxis.set_major_locator(MaxNLocator(integer=True))year=np.array([1980,1982,1984,1986,1988,1990,1992,1994,1996,1998,2000])co2=np.array([338.7,341.1,344.4,347.2,351.5,354.2,356.4,358.9,362.6,366.6,369.4])coef = np.polyfit(year, co2, 1)equ = np.poly1d(coef)x_plot = np.linspace(1975,2005,100)y_plot = equ(x_plot)plt.plot(x_plot, y_plot, color='r')plt.scatter(year,co2,label='CO2')plt.title(\"Year vs CO2\")plt.xlabel('Year')plt.ylabel('CO2')plt.legend()plt.show()" }, { "code": null, "e": 2657, "s": 2370, "text": "The second way to find the regression slope and intercept is to use sklearn.linear_model.LinearRegression. This class requires the x values to be one column. We modify year data using reshape(-1,1). The original year data has 1 by 11 shape. You need to reshape the year data to 11 by 1." }, { "code": null, "e": 2727, "s": 2657, "text": "year1=year.reshape((-1,1))print(np.shape(year))print(np.shape(year1))" }, { "code": null, "e": 3030, "s": 2727, "text": "We import sklearn.linear_model.LinearRegression, reshape the year data, fit our data using LinearRegression().fit(). This will return the slope, coef_ and the y-intercept, intercept_. coef_ returns an array, so we take the first item by using reg.coef_[0]. Let’s print out our regression line equation." }, { "code": null, "e": 3263, "s": 3030, "text": "from sklearn.linear_model import LinearRegressionyear1=year.reshape((-1,1))reg = LinearRegression().fit(year1,co2)slope=reg.coef_[0]intercept=reg.intercept_print(f'The equation of regression line is y={slope:.3f}x+{intercept:.3f}.')" }, { "code": null, "e": 3510, "s": 3263, "text": "We draw a scatter plot and our linear regression line together. We use a new x domain from 1975 to 2005 taking 100 samples for the regression line, np.linspace(1975,2005,100). Then using x domain, slope, and y-intercept to draw a regression line." }, { "code": null, "e": 4295, "s": 3510, "text": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import MaxNLocatorfrom sklearn.linear_model import LinearRegression%matplotlib inlineax = plt.figure().gca()ax.xaxis.set_major_locator(MaxNLocator(integer=True))year=np.array([1980,1982,1984,1986,1988,1990,1992,1994,1996,1998,2000])co2=np.array([338.7,341.1,344.4,347.2,351.5,354.2,356.4,358.9,362.6,366.6,369.4])year1=year.reshape((-1,1))reg = LinearRegression().fit(year1,co2) slope=reg.coef_[0]intercept=reg.intercept_plt.scatter(year,co2,label='CO2')X_plot = np.linspace(1975,2005,100)Y_plot = slope*X_plot+interceptplt.plot(X_plot, Y_plot, color='r')plt.title(\"Year vs CO2\")plt.xlabel('Year')plt.ylabel('CO2')plt.legend()plt.show()print(f'The equation of regression line is y={slope:.3f}x+{intercept:.3f}.')" }, { "code": null, "e": 4439, "s": 4295, "text": "Another way to find the regression slope and intercept is to use scipy.stats.linregress. This returns slope, intercept, rvalue, pvalue, stderr." }, { "code": null, "e": 4616, "s": 4439, "text": "from scipy.stats import linregressslope, intercept, r_value, p_value, std_err = linregress(year,co2)print(f'The equation of regression line is y={slope:.3f}x+{intercept:.3f}.')" }, { "code": null, "e": 4835, "s": 4616, "text": "To draw a line we need x points. We use np.linspace which is numpy.linspace since we used import numpy as np. Our data is from 1975 to 2000. So let's use 1960 for start, 2005 for stop and 100 for the number of samples." }, { "code": null, "e": 5200, "s": 4835, "text": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.stats import linregress%matplotlib inlineyear=np.array([1980,1982,1984,1986,1988,1990,1992,1994,1996,1998,2000])co2=np.array([338.7,341.1,344.4,347.2,351.5,354.2,356.4,358.9,362.6,366.6,369.4])X_plot = np.linspace(1975,2005,100)Y_plot = slope*X_plot+interceptplt.plot(X_plot, Y_plot, color='r')plt.show()" }, { "code": null, "e": 5280, "s": 5200, "text": "Now we put a scatter plot, regression line, and a regression equation together." }, { "code": null, "e": 5856, "s": 5280, "text": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.ticker import MaxNLocatorfrom scipy.stats import linregress%matplotlib inlineax = plt.figure().gca()ax.xaxis.set_major_locator(MaxNLocator(integer=True))slope, intercept, r_value, p_value, std_err = linregress(year,co2)X_plot = np.linspace(1975,2005,100)Y_plot = slope*X_plot+interceptplt.plot(X_plot, Y_plot, color='r')plt.scatter(year,co2,label='CO2')plt.title(\"Year vs CO2\")plt.xlabel('Year')plt.ylabel('CO2')plt.legend()plt.show()print(f'The equation of regression line is y={slope:.3f}x+{intercept:.3f}.')" }, { "code": null, "e": 5959, "s": 5856, "text": "Use the following data to graph a scatter plot and regression line. Find a linear regression equation." }, { "code": null, "e": 6116, "s": 5959, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinetemp = np.array([55,60,65,70,75,80,85,90])rate = np.array([45,80,92,114,141,174,202,226])" }, { "code": null, "e": 6208, "s": 6116, "text": "Did you draw a scatter and regression graph? The regression line should be y=5.119x−236.88." }, { "code": null, "e": 6231, "s": 6208, "text": "towardsdatascience.com" }, { "code": null, "e": 6288, "s": 6231, "text": "We use Numpy’s arange to create 10 integers from 0 to 9." }, { "code": null, "e": 6435, "s": 6288, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinetime = np.arange(10)height = np.array([450,445,430,409,375,331,280,215,144,59])" }, { "code": null, "e": 6462, "s": 6435, "text": "Let’s plot the above data." }, { "code": null, "e": 6666, "s": 6462, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineplt.scatter(time,height,label='Height of a ball')plt.title(\"Time vs Height\")plt.xlabel('Time')plt.ylabel('Height')plt.legend()plt.show()" }, { "code": null, "e": 6931, "s": 6666, "text": "numpy.polyfit fits a polynomial. It requires x, y, and degree of the fitting polynomial. 2 for a quadratic, 3 for a cubic, etc. It returns an array with polynomial coefficients from a higher power to the constant. For a quadratic function, these are a, b and c in:" }, { "code": null, "e": 6970, "s": 6931, "text": "coef = np.polyfit(time, height, 2)coef" }, { "code": null, "e": 7017, "s": 6970, "text": "Let’s print out the quadratic regression line." }, { "code": null, "e": 7075, "s": 7017, "text": "print(f'The equation of regression line is y=')print(equ)" }, { "code": null, "e": 7121, "s": 7075, "text": "Or using coefficients the regression line is:" }, { "code": null, "e": 7215, "s": 7121, "text": "print(f'The equation of regression line is y={coef[0]:.3f}x^2+{coef[1]:.3f}x+{coef[2]:.3f}.')" }, { "code": null, "e": 7336, "s": 7215, "text": "We use NumPy's poly1d and polyfitagain. np.poly1d(coefficients) will return a polynomial equation using our coefficient." }, { "code": null, "e": 7358, "s": 7336, "text": "equ = np.poly1d(coef)" }, { "code": null, "e": 7440, "s": 7358, "text": "We can find a value for any x. For example, if you want to find y value when x=1:" }, { "code": null, "e": 7447, "s": 7440, "text": "equ(1)" }, { "code": null, "e": 7595, "s": 7447, "text": "We use this to draw our regression line. We use numpy.linspace to define x values from 0 to 10 for 100 samples. And use it in the equ for y values." }, { "code": null, "e": 7758, "s": 7595, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinex_plot = np.linspace(0,10,100)y_plot = equ(x_plot)plt.plot(x_plot, y_plot, color='r')plt.show()" }, { "code": null, "e": 7782, "s": 7758, "text": "We put it all together." }, { "code": null, "e": 8262, "s": 7782, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinetime = np.arange(10)height = np.array([450,445,430,409,375,331,280,215,144,59])coef = np.polyfit(time, height, 2)equ = np.poly1d(coef)x_plot = np.linspace(0,10,100)y_plot = equ(x_plot)plt.plot(x_plot, y_plot, color='r')plt.scatter(time,height,label='Height of a ball')plt.title(\"Time vs Height\")plt.xlabel('Time')plt.ylabel('Height')plt.legend()plt.show()print(f'The equation of regression line is y=')print(equ)" }, { "code": null, "e": 8383, "s": 8262, "text": "By using the following data, draw a scatter plot and regression line in a graph. Find the quadratic regression equation." }, { "code": null, "e": 8524, "s": 8383, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineangle = np.arange(20,80,10)distance = np.array([371,465,511,498,439,325])" }, { "code": null, "e": 8604, "s": 8524, "text": "Could you draw a scatter and regression line? The quadratic equation should be:" }, { "code": null, "e": 8627, "s": 8604, "text": "towardsdatascience.com" }, { "code": null, "e": 8786, "s": 8627, "text": "You can use the same method as the quadratic function above. We are going to use plyfit and poly1d. First, we prepare the data. And let’s draw a scatter plot." }, { "code": null, "e": 9148, "s": 8786, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineengspeed = np.arange(9,23,2)avespeed = np.array([6.45,7.44,8.88,9.66,10.98,12.56,15.44])plt.scatter(engspeed,avespeed,label='Speed of different boat engine')plt.title(\"Average speed of different boat engine\")plt.xlabel('Engine speed')plt.ylabel('Boad speed')plt.ylim(0,20)plt.legend()plt.show()" }, { "code": null, "e": 9225, "s": 9148, "text": "Using polyfit returns coefficients. For a cubic function, a, b, c, and d in:" }, { "code": null, "e": 9277, "s": 9225, "text": "coef = np.polyfit(engspeed, avespeed, 3)print(coef)" }, { "code": null, "e": 9298, "s": 9277, "text": "We put all together." }, { "code": null, "e": 9905, "s": 9298, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineengspeed = np.arange(9,23,2)avespeed = np.array([6.45,7.44,8.88,9.66,10.98,12.56,15.44])plt.scatter(engspeed,avespeed,label='Speed of different boat engine')coef = np.polyfit(engspeed, avespeed, 3)equ = np.poly1d(coef)x_plot = np.linspace(8,25,100)y_plot = equ(x_plot)plt.plot(x_plot, y_plot, color='r')plt.title(\"Average speed of different boat engine\")plt.xlabel('Engine speed')plt.ylabel('Boad speed')plt.ylim(0,20)plt.legend()plt.show()a, b, c, d = coefprint(f'The equation of regression line is y={a:.3f}x^3+{b:.3f}x^2+{c:.3f}x+{d}.')" }, { "code": null, "e": 10005, "s": 9905, "text": "Draw a scatter plot and a cubic regression line using the following data. Print the cubic equation." }, { "code": null, "e": 10137, "s": 10005, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinex=np.arange(1,8)y=np.array([0,0.012,0.06,0.162,0.336,0.6,0.972])" }, { "code": null, "e": 10225, "s": 10137, "text": "Could you plot a scatter and a regression line? The regression line equation should be:" }, { "code": null, "e": 10328, "s": 10225, "text": "The coefficients are [ 3.00000000e-03, -1.16796094e-16, -9.00000000e-03, 6.00000000e-03]. These means:" }, { "code": null, "e": 10409, "s": 10328, "text": "The second one is practically 0. Try the following to see both are the same 0.3." }, { "code": null, "e": 10443, "s": 10409, "text": "print(300e-03)print(300*10**(-3))" }, { "code": null, "e": 10493, "s": 10443, "text": "We are going to explore three exponential models." }, { "code": null, "e": 10541, "s": 10493, "text": "Let’s set up the data. And draw a scatter plot." }, { "code": null, "e": 10808, "s": 10541, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlineday = np.arange(0,8)weight = np.array([251,209,157,129,103,81,66,49])plt.scatter(day,weight,label='Weight change')plt.title(\"Day vs Weight\")plt.xlabel('Day')plt.ylabel('Weight')plt.legend()plt.show()" }, { "code": null, "e": 11123, "s": 10808, "text": "We are going to use scipy.optimize.curve_fit. This requires a function, x and y values, and initial values, p0 in array form. Finding proper p0 is a bit of trial and error. You have to test different values. We use p0=(1, 1e-6, 1). It returns optimal values for the parameters and the estimated covariance of popt." }, { "code": null, "e": 11338, "s": 11123, "text": "Our first exponential function uses a, b, and c. We are going to define a function first. This is used in the curve_fit method. For a smooth curve, we set x values using numpy.linspace from 0 to 7 with 100 samples." }, { "code": null, "e": 11891, "s": 11338, "text": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlinedef func(x, a, b, c): return a * np.exp(-b * x) + cpopt, pcov = curve_fit(func, day, weight, p0=[1, 1e-6, 1])x_plot=np.linspace(0,7,100)plt.plot(x_plot, func(x_plot, *popt), 'r-')plt.scatter(day,weight,label='Day vs Weight')plt.title(\"Day vs Weight a*e^-bx +c\")plt.xlabel('Day')plt.ylabel('Weight')plt.legend()plt.show()# equationa=popt[0].round(2)b=popt[1].round(2)c=popt[2].round(2)print(f'The equation of regression line is y={a}e^({b}x)+{c}')" }, { "code": null, "e": 11961, "s": 11891, "text": "The second function uses a and b. We define the function accordingly." }, { "code": null, "e": 12482, "s": 11961, "text": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlinedef func2(x, a, b): return a * np.exp(-b * x)popt, pcov = curve_fit(func2, day, weight, p0=[1, 1e-6])x_plot=np.linspace(0,7,100)plt.plot(x_plot, func2(x_plot, *popt), 'r-')plt.scatter(day,weight,label='Day vs Weight')plt.title(\"Day vs Weight a*e^-bx\")plt.xlabel('Day')plt.ylabel('Weight')plt.legend()plt.show()# equationa=popt[0].round(2)b=popt[1].round(2)print(f'The equation of regression line is y={a}e^({b}x)')" }, { "code": null, "e": 12562, "s": 12482, "text": "The last exponential function uses a and b. We modify the function accordingly." }, { "code": null, "e": 13071, "s": 12562, "text": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlinedef func3(x, a, b): return a * b ** xpopt, pcov = curve_fit(func3, day, weight, p0=[1, 1e-6])x_plot=np.linspace(0,7,100)plt.plot(x_plot, func3(x_plot, *popt), 'r-')plt.scatter(day,weight,label='Day vs Weight')plt.title(\"Day vs Weight a*b^x\")plt.xlabel('Day')plt.ylabel('Weight')plt.legend()plt.show()# equationa=popt[0].round(4)b=popt[1].round(4)print(f'The equation of regression line is y={a}*{b}^x')" }, { "code": null, "e": 13240, "s": 13071, "text": "TI Nspire’s exponential regression fits the model equation y=ab^x to the data using a least-squares fit on transformed values x and ln(y). It returns a different value." }, { "code": null, "e": 13366, "s": 13240, "text": "Using the following data find an exponential function in the form of ab^x. Plot a scatter diagram and draw a regression line." }, { "code": null, "e": 13518, "s": 13366, "text": "import numpy as npweek = np.arange(1,21)views = np.array([102365, 38716,21617,24305,9321,14148,2103,8285,5098,3777,831,1007,834,34,378,204,6,42,54,31])" }, { "code": null, "e": 13584, "s": 13518, "text": "Generally, we use the semi-log model for an exponential function:" }, { "code": null, "e": 13636, "s": 13584, "text": "We set up our mock data and plot a scatter diagram." }, { "code": null, "e": 13921, "s": 13636, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinetime = np.arange(0,30,4)bacteria = np.array([20,150,453,920,1820,9765,15487,19450])plt.scatter(time,bacteria,label='Bacteria')plt.title(\"Time vs Bacteria\")plt.xlabel('time')plt.ylabel('bacteria')plt.legend()plt.show()" }, { "code": null, "e": 14128, "s": 13921, "text": "We are going to take a natural log for the bacteria values by using numpy.log. numpy.log is the natural logarithm. This should show a linear trend. We need to modify the title and y label with ln(bacteria)." }, { "code": null, "e": 14429, "s": 14128, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinetime = np.arange(0,30,4)bacteria = np.array([20,150,453,920,1820,9765,15487,19450])plt.scatter(time,np.log(bacteria),label='Bacteria')plt.title(\"Time vs ln(Bacteria)\")plt.xlabel('time')plt.ylabel('ln(bacteria)')plt.legend()plt.show()" }, { "code": null, "e": 14628, "s": 14429, "text": "We use numpy.polyfit which we used in a quadratic and cubic function. We use 1 in numpy.polyfit() so that it will return a linear regression. numpy.polyfit returns all coefficients for our equation." }, { "code": null, "e": 15101, "s": 14628, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinetime = np.arange(0,30,4)bacteria = np.array([20,150,453,920,1820,9765,15487,19450])p = np.polyfit(time, np.log(bacteria), 1)plt.plot(time, p[0] * time + p[1], 'g--', label='Semi-log graph')plt.scatter(time,np.log(bacteria),label='Bacteria')plt.title(\"Time vs Bacteria\")plt.xlabel('time')plt.ylabel('bacteria')plt.legend()plt.show()print(f'The equation of regression line is y={p[0]:.3f} * x + {p[1]:.3f}')" }, { "code": null, "e": 15149, "s": 15101, "text": "The log-log model is used for a power function." }, { "code": null, "e": 15195, "s": 15149, "text": "Let’s set up data and plot a scatter diagram." }, { "code": null, "e": 15438, "s": 15195, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinex=np.array([2,30,70,100,150])y=np.array([4.24,16.4,25.1,30,36.7])plt.scatter(x,y,label='Log-log')plt.title(\"Log-Log model\")plt.xlabel('x')plt.ylabel('y')plt.legend()plt.show()" }, { "code": null, "e": 15553, "s": 15438, "text": "We take a natural log for x and y values using numpy.log. We need to modify the x and y labels to ln(x) and ln(y)." }, { "code": null, "e": 16022, "s": 15553, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inlinex=np.array([2,30,70,100,150])y=np.array([4.24,16.4,25.1,30,36.7])p = np.polyfit(np.log(x), np.log(y), 1)plt.plot(np.log(x), p[0] * np.log(x) + p[1], 'r--', label='Regression line')plt.scatter(np.log(x),np.log(y),label='log-log')plt.title(\"Log-log regression\")plt.xlabel('ln(x)')plt.ylabel('ln(y)')plt.legend()plt.show()print(f'The equation of regression line is ln(y)={p[0]:.3f} * ln(x) + {p[1]:.3f}')" }, { "code": null, "e": 16256, "s": 16022, "text": "Let’s try a sinusoidal function. We set our data and plot a scatter graph. Since we are going to use scipy.optimize.curve_fit, let's import it as well. We used it in the exponential models. We set up our data and draw a scatter plot." }, { "code": null, "e": 16600, "s": 16256, "text": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlineyear=np.arange(0,24,2)population=np.array([10.2,11.1,12,11.7,10.6,10,10.6,11.7,12,11.1,10.2,10.2])plt.scatter(year,population,label='Population')plt.title(\"Year vs Population\")plt.xlabel('Year')plt.ylabel('Population')plt.legend()plt.show()" }, { "code": null, "e": 16702, "s": 16600, "text": "We define a function called sinfunc. This takes parameters x, a, b, c, d. We use numpy.radians for c." }, { "code": null, "e": 17409, "s": 16702, "text": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlineyear=np.arange(0,24,2)population=np.array([10.2,11.1,12,11.7,10.6,10,10.6,11.7,12,11.1,10.2,10.2])def sinfunc(x, a, b, c, d): return a * np.sin(b * (x - np.radians(c)))+dpopt, pcov = curve_fit(sinfunc, year, population, p0=[1,0.4,1,5])x_data = np.linspace(0, 25, num=100)plt.scatter(year,population,label='Population')plt.plot(x_data, sinfunc(x_data, *popt), 'r-',label='Fitted function')plt.title(\"Year vs Population\")plt.xlabel('Year')plt.ylabel('Population')plt.legend()plt.show()a, b, c, d = poptprint(f'The equation of regression line is y={a:.3f} * sin({b:.3f}(x-{np.radians(c):.3f}))+{d:.3f}')" }, { "code": null, "e": 17491, "s": 17409, "text": "Using the table below, draw a scatter plot and find a cosine regression function." }, { "code": null, "e": 17535, "s": 17491, "text": "You may have different coefficients. I used" }, { "code": null, "e": 17735, "s": 17535, "text": "We set up data and plot a scatter diagram. We set the domain from -10 to 10 and range from 0 to 250, using plt.xlim and plt.ylim. We are going to use scipy.optimize.curve_fit for logistic regression." }, { "code": null, "e": 18071, "s": 17735, "text": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlinex=np.arange(0,10)y=np.array([52,133,203,230,237,239.5,239.8,239.9,240,240])plt.scatter(x, y, label='Regression line')plt.title(\"Logistic regression\")plt.xlabel('x')plt.ylabel('y')plt.xlim(-10,10)plt.ylim(0,250)plt.legend()plt.show()" }, { "code": null, "e": 18294, "s": 18071, "text": "We define our logistic function using logifunc. We find the function parameter in popt using curve_fit. For the regression line, we set a new domain for the function, x_data from -10 to 10. We plot the line using plt.plot." }, { "code": null, "e": 18838, "s": 18294, "text": "import numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fit%matplotlib inlinex=np.arange(0,10.0)y=np.array([52,133,203,230,237,239.5,239.8,239.9,240,240])def logifunc(x,L,c,k): return L/ (1 + c*np.exp(-k*x))popt, pcov = curve_fit(logifunc, x, y, p0=[200,1,1])x_data = np.linspace(-10, 10, num=100)plt.scatter(x,y,label='Logistic function')plt.plot(x_data, logifunc(x_data, *popt), 'r-',label='Fitted function')plt.title(\"Logistic\")plt.xlabel('x')plt.ylabel('y')plt.xlim(-10,10)plt.ylim(0,250)plt.legend()plt.show()" }, { "code": null, "e": 18901, "s": 18838, "text": "Sometimes your data may have negative values in y coordinates." }, { "code": null, "e": 18971, "s": 18901, "text": "import pandas as pddf = pd.read_csv('http://bit.ly/2tUIZjK')df.head()" }, { "code": null, "e": 19189, "s": 18971, "text": "The minimum value for the data needs to be zero. And ideally, the sigmoid midpoint is also zero. But the above data set satisfies neither of them. Using equation (1–2), and adding offset value works for this data set." }, { "code": null, "e": 19572, "s": 19189, "text": "x=df.T.iloc[0]y=df.T.iloc[1]def logifunc(x,L,x0,k,off): return L / (1 + np.exp(-k*(x-x0)))+offplt.scatter(x,y,label='Logistic function')popt, pcov = curve_fit(logifunc, x, y, p0=[50,185,0.1,-222])plt.scatter(x,y,label='Logistic function')x_data = np.linspace(170,205,num=100)plt.plot(x_data, logifunc(x_data, *popt), 'r-',label='Fitted function')plt.legend()plt.show()print(popt)" }, { "code": null, "e": 19756, "s": 19572, "text": "scipy.optimize.curve_fit was useful for many functions. The only problem was to find good initial values in p0. Sometimes different p0 values return different popt. You can try LMFIT." } ]
Check if it is possible to create a polygon with given n sides - GeeksforGeeks
30 Apr, 2021 Given an array arr[] that contains the lengths of n sides that may or may not form a polygon. The task is to determine whether it is possible to form a polygon with all the given sides. Print Yes if possible else print No.Examples: Input: arr[] = {2, 3, 4} Output: YesInput: arr[] = {3, 4, 9, 2} Output: No Approach: In order to create a polygon with given n sides, there is a certain property that must be satisfied by the sides of the polygon. Property: The length of the every given side must be less than the sum of the other remaining sides. Find the largest side among the given sides. Then, check whether it is smaller than the sum of the other sides or not. If it is smaller then print Yes else print No.Below is the implementation of the above approach: C++ Java Python C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if it is possible// to form a polygon with the given sidesbool isPossible(int a[], int n){ // Sum stores the sum of all the sides // and maxS stores the length of // the largest side int sum = 0, maxS = 0; for (int i = 0; i < n; i++) { sum += a[i]; maxS = max(a[i], maxS); } // If the length of the largest side // is less than the sum of the // other remaining sides if ((sum - maxS) > maxS) return true; return false;} // Driver codeint main(){ int a[] = { 2, 3, 4 }; int n = sizeof(a) / sizeof(a[0]); if (isPossible(a, n)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation of the approachclass GFG { // Function that returns true if it is possible // to form a polygon with the given sides static boolean isPossible(int a[], int n) { // Sum stores the sum of all the sides // and maxS stores the length of // the largest side int sum = 0, maxS = 0; for (int i = 0; i < n; i++) { sum += a[i]; maxS = Math.max(a[i], maxS); } // If the length of the largest side // is less than the sum of the // other remaining sides if ((sum - maxS) > maxS) return true; return false; } // Driver code public static void main(String[] args) { int a[] = { 2, 3, 4 }; int n = a.length; if (isPossible(a, n)) System.out.print("Yes"); else System.out.print("No"); }} # Python 3 implementation of the approach # Function to check whether# it is possible to create a# polygon with given sides lengthdef isPossible(a, n): # Sum stores the sum of all the sides # and maxS stores the length of # the largest side sum = 0 maxS = 0 for i in range(n): sum += a[i] maxS = max(a[i], maxS) # If the length of the largest side # is less than the sum of the # other remaining sides if ((sum - maxS) > maxS): return True return False # Driver codea =[2, 3, 4]n = len(a) if(isPossible(a, n)): print("Yes")else: print("No") // C# implementation of the approachusing System;class GFG { // Function that returns true if it is possible // to form a polygon with the given sides static bool isPossible(int[] a, int n) { // Sum stores the sum of all the sides // and maxS stores the length of // the largest side int sum = 0, maxS = 0; for (int i = 0; i < n; i++) { sum += a[i]; maxS = Math.Max(a[i], maxS); } // If the length of the largest side // is less than the sum of the // other remaining sides if ((sum - maxS) > maxS) return true; return false; } // Driver code static void Main() { int[] a = { 2, 3, 4 }; int n = a.Length; if (isPossible(a, n)) Console.Write("Yes"); else Console.Write("No"); }} <?php// PHP implementation of the approach // Function that returns true if it is possible// to form a polygon with the given sidesfunction isPossible($a, $n){ // Sum stores the sum of all the sides // and maxS stores the length of // the largest side $sum = 0; $maxS = 0; for ($i = 0; $i < $n; $i++) { $sum += $a[$i]; $maxS = max($a[$i], $maxS); } // If the length of the largest side // is less than the sum of the // other remaining sides if (($sum - $maxS) > $maxS) return true; return false;} // Driver code$a = array(2, 3, 4);$n = count($a); if(isPossible($a, $n)) echo "Yes";else echo "No";?> <script> // Javascript implementation of the approach // Function that returns true if it is possible// to form a polygon with the given sidesfunction isPossible( a, n){ // Sum stores the sum of all the sides // and maxS stores the length of // the largest side let sum = 0, maxS = 0; for (let i = 0; i < n; i++) { sum += a[i]; maxS = Math.max(a[i], maxS); } // If the length of the largest side // is less than the sum of the // other remaining sides if ((sum - maxS) > maxS) return true; return false;} // Driver Code let a = [ 2, 3, 4 ]; let n = a.length; if (isPossible(a, n)) document.write("Yes"); else document.write("No"); </script> Yes jana_sayantan math school-programming Geometric Mathematical School Programming Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Convex Hull | Set 2 (Graham Scan) Given n line segments, find if any two segments intersect Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25500, "s": 25472, "text": "\n30 Apr, 2021" }, { "code": null, "e": 25734, "s": 25500, "text": "Given an array arr[] that contains the lengths of n sides that may or may not form a polygon. The task is to determine whether it is possible to form a polygon with all the given sides. Print Yes if possible else print No.Examples: " }, { "code": null, "e": 25811, "s": 25734, "text": "Input: arr[] = {2, 3, 4} Output: YesInput: arr[] = {3, 4, 9, 2} Output: No " }, { "code": null, "e": 25954, "s": 25813, "text": "Approach: In order to create a polygon with given n sides, there is a certain property that must be satisfied by the sides of the polygon. " }, { "code": null, "e": 26055, "s": 25954, "text": "Property: The length of the every given side must be less than the sum of the other remaining sides." }, { "code": null, "e": 26273, "s": 26055, "text": " Find the largest side among the given sides. Then, check whether it is smaller than the sum of the other sides or not. If it is smaller then print Yes else print No.Below is the implementation of the above approach: " }, { "code": null, "e": 26277, "s": 26273, "text": "C++" }, { "code": null, "e": 26282, "s": 26277, "text": "Java" }, { "code": null, "e": 26289, "s": 26282, "text": "Python" }, { "code": null, "e": 26292, "s": 26289, "text": "C#" }, { "code": null, "e": 26296, "s": 26292, "text": "PHP" }, { "code": null, "e": 26307, "s": 26296, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if it is possible// to form a polygon with the given sidesbool isPossible(int a[], int n){ // Sum stores the sum of all the sides // and maxS stores the length of // the largest side int sum = 0, maxS = 0; for (int i = 0; i < n; i++) { sum += a[i]; maxS = max(a[i], maxS); } // If the length of the largest side // is less than the sum of the // other remaining sides if ((sum - maxS) > maxS) return true; return false;} // Driver codeint main(){ int a[] = { 2, 3, 4 }; int n = sizeof(a) / sizeof(a[0]); if (isPossible(a, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 27078, "s": 26307, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function that returns true if it is possible // to form a polygon with the given sides static boolean isPossible(int a[], int n) { // Sum stores the sum of all the sides // and maxS stores the length of // the largest side int sum = 0, maxS = 0; for (int i = 0; i < n; i++) { sum += a[i]; maxS = Math.max(a[i], maxS); } // If the length of the largest side // is less than the sum of the // other remaining sides if ((sum - maxS) > maxS) return true; return false; } // Driver code public static void main(String[] args) { int a[] = { 2, 3, 4 }; int n = a.length; if (isPossible(a, n)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }}", "e": 27966, "s": 27078, "text": null }, { "code": "# Python 3 implementation of the approach # Function to check whether# it is possible to create a# polygon with given sides lengthdef isPossible(a, n): # Sum stores the sum of all the sides # and maxS stores the length of # the largest side sum = 0 maxS = 0 for i in range(n): sum += a[i] maxS = max(a[i], maxS) # If the length of the largest side # is less than the sum of the # other remaining sides if ((sum - maxS) > maxS): return True return False # Driver codea =[2, 3, 4]n = len(a) if(isPossible(a, n)): print(\"Yes\")else: print(\"No\")", "e": 28573, "s": 27966, "text": null }, { "code": "// C# implementation of the approachusing System;class GFG { // Function that returns true if it is possible // to form a polygon with the given sides static bool isPossible(int[] a, int n) { // Sum stores the sum of all the sides // and maxS stores the length of // the largest side int sum = 0, maxS = 0; for (int i = 0; i < n; i++) { sum += a[i]; maxS = Math.Max(a[i], maxS); } // If the length of the largest side // is less than the sum of the // other remaining sides if ((sum - maxS) > maxS) return true; return false; } // Driver code static void Main() { int[] a = { 2, 3, 4 }; int n = a.Length; if (isPossible(a, n)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }}", "e": 29443, "s": 28573, "text": null }, { "code": "<?php// PHP implementation of the approach // Function that returns true if it is possible// to form a polygon with the given sidesfunction isPossible($a, $n){ // Sum stores the sum of all the sides // and maxS stores the length of // the largest side $sum = 0; $maxS = 0; for ($i = 0; $i < $n; $i++) { $sum += $a[$i]; $maxS = max($a[$i], $maxS); } // If the length of the largest side // is less than the sum of the // other remaining sides if (($sum - $maxS) > $maxS) return true; return false;} // Driver code$a = array(2, 3, 4);$n = count($a); if(isPossible($a, $n)) echo \"Yes\";else echo \"No\";?>", "e": 30112, "s": 29443, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function that returns true if it is possible// to form a polygon with the given sidesfunction isPossible( a, n){ // Sum stores the sum of all the sides // and maxS stores the length of // the largest side let sum = 0, maxS = 0; for (let i = 0; i < n; i++) { sum += a[i]; maxS = Math.max(a[i], maxS); } // If the length of the largest side // is less than the sum of the // other remaining sides if ((sum - maxS) > maxS) return true; return false;} // Driver Code let a = [ 2, 3, 4 ]; let n = a.length; if (isPossible(a, n)) document.write(\"Yes\"); else document.write(\"No\"); </script>", "e": 30856, "s": 30112, "text": null }, { "code": null, "e": 30860, "s": 30856, "text": "Yes" }, { "code": null, "e": 30876, "s": 30862, "text": "jana_sayantan" }, { "code": null, "e": 30881, "s": 30876, "text": "math" }, { "code": null, "e": 30900, "s": 30881, "text": "school-programming" }, { "code": null, "e": 30910, "s": 30900, "text": "Geometric" }, { "code": null, "e": 30923, "s": 30910, "text": "Mathematical" }, { "code": null, "e": 30942, "s": 30923, "text": "School Programming" }, { "code": null, "e": 30955, "s": 30942, "text": "Mathematical" }, { "code": null, "e": 30965, "s": 30955, "text": "Geometric" }, { "code": null, "e": 31063, "s": 30965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31112, "s": 31063, "text": "Program for distance between two points on earth" }, { "code": null, "e": 31165, "s": 31112, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 31199, "s": 31165, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 31257, "s": 31199, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 31308, "s": 31257, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 31338, "s": 31308, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31398, "s": 31338, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31413, "s": 31398, "text": "C++ Data Types" }, { "code": null, "e": 31456, "s": 31413, "text": "Set in C++ Standard Template Library (STL)" } ]
Abstract Base Class (abc) in Python - GeeksforGeeks
29 Aug, 2020 Have you ever thought about checking whether the objects you are using adheres to a particular specification? It is necessary to verify whether an object implements a given method or property, especially while creating a library where other developers make use of it. A developer can use hasattr or isinstance methods to check whether the input conforms to a particular identity. But sometimes it is inconvenient to use those methods to check a myriad of different properties and methods. As a solution to this inconvenience, Python introduced a concept called abstract base class (abc). In this section, we will discuss the abstract base class and its importance. Abstract Base Class Declaring an Abstract Base Class Why declare an Abstract Base Class? Abstract Properties Built-In Abstract Classes The main goal of the abstract base class is to provide a standardized way to test whether an object adheres to a given specification. It can also prevent any attempt to instantiate a subclass that doesn’t override a particular method in the superclass. And finally, using an abstract class, a class can derive identity from another class without any object inheritance. Python has a module called abc (abstract base class) that offers the necessary tools for crafting an abstract base class. First and foremost, you should understand the ABCMeta metaclass provided by the abstract base class. The rule is every abstract class must use ABCMeta metaclass. ABCMeta metaclass provides a method called register method that can be invoked by its instance. By using this register method, any abstract base class can become an ancestor of any arbitrary concrete class. Let’s understand this process by considering an example of an abstract base class that registers itself as an ancestor of dict. Python3 import abc class AbstractClass(metaclass=abc.ABCMeta): def abstractfunc(self): return None print(AbstractClass.register(dict)) Output: <class 'dict'> Here, dict identifies itself as a subclass of AbstractClass. Let’s do a check. Python3 import abc class AbstractClass(metaclass=abc.ABCMeta): def abstractfunc(self): return None AbstractClass.register(dict)print(issubclass(dict, AbstractClass)) Output: True To understand the need to declare a virtual subclass, we need to consider the example of a list-like object where you don’t want to put a restriction of only considering list or tuple. Before that let’s see how to use isinstance to check against a list or tuple of class. isinstance([], (list, tuple)) This isinstance check meets the purpose if you are accepting only a list or tuple. But here the case is different, there is no such restriction. So, this solution is not extensible for a developer who uses your library to send something else other than a list or tuple. Here comes the importance of abstract class. Let’s understand through the below code. Python3 import abc class MySequence(metaclass=abc.ABCMeta): pass MySequence.register(list)MySequence.register(tuple) a = [1, 2, 3]b = ('x', 'y', 'z') print('List instance:', isinstance(a, MySequence))print('Tuple instance:', isinstance(b, MySequence))print('Object instance:', isinstance(object(), MySequence)) Output: List instance: True Tuple instance: True Object instance: False As you can see, when you do isinstance check, it returns true for both the list and tuple; for the other objects, it returns false. Let’s consider a scenario where a developer expects a class object itself. In the above case, the isinstance will return false. But it can be achieved by creating a custom class and registering it with the abstract base class. Here ‘MySequence’ is an abstract class within the library. A developer can import it and register a custom class. Let’s have a look at the below code. Python3 import abc class MySequence(metaclass=abc.ABCMeta): pass class CustomListLikeObjCls(object): pass MySequence.register(CustomListLikeObjCls)print(issubclass(CustomListLikeObjCls, MySequence)) Output: True Here, CustomListLikeObjCls instance is passed to the library by registering it with MySequence. Therefore, the instance check returns True. Apart from the above method, you can also use the register method as a decorator to register a custom class. Let’s see how to use the register method as a decorator. Python3 import abc class MySequence(metaclass=abc.ABCMeta): pass @MySequence.registerclass CustomListLikeObjCls(object): pass print(issubclass(CustomListLikeObjCls, MySequence)) Output: True Registering a class using the above-implemented method meets the purpose. However, you have to do manual registration for every intended subclass. How about automatic subclassing based on a particular method?. An abstract class has a concept called __subclasshook__ to subclass the classes. It is a special magic method defined by ABCMeta. The __subclasshook__ must be defined as a class method using @classmethod decorator. It takes one additional positional argument other than the class and can return either of the three values – True, False, or NotImplemented. Let’s look at the below implementation. Python3 import abc class AbstractClass(metaclass=abc.ABCMeta): @classmethod def __subclasshook__(cls, other): print('subclass hook:', other) hookmethod = getattr(other, 'hookmethod', None) return callable(hookmethod) class SubClass(object): def hookmethod(self): pass class NormalClass(object): hookmethod = 'hook' print(issubclass(SubClass, AbstractClass))print(issubclass(NormalClass, AbstractClass)) Output: subclass hook: <class '__main__.SubClass'> True subclass hook: <class '__main__.NormalClass'> False From the above discussion, you understood how to hook subclasses automatically. Now we will look into how to avoid instantiating a subclass that doesn’t override a particular method in the superclass. This feature can be achieved using @abc.abstractmethod. @abc.abstractmethod prevents any attempt to instantiate a subclass that doesn’t override a particular method in the superclass. Let’s have a look at the below code: Python3 import abc class AbstractClass(metaclass=abc.ABCMeta): @abc.abstractmethod def abstractName(self): pass class InvalidSubClass(AbstractClass): pass isc = InvalidSubClass() Since the InvalidSubclass doesn’t override the method abstractName, the @abc.abstractmethod prevents the subclass from instantiation and throws the below error. Traceback (most recent call last): File “/home/553d5199a662239eae3ff58efb37b6ec.py”, line 11, in <module> isc = InvalidSubClass()TypeError: Can’t instantiate abstract class InvalidSubClass with abstract methods abstractName Let’s look into another example where the subclass overrides the abstract method. Python3 import abc class AbstractClass(metaclass=abc.ABCMeta): @abc.abstractmethod def abstractName(self): pass class ValidSubClass(AbstractClass): def abstractName(self): return 'Abstract 1' vc = ValidSubClass()print(vc.abstractName()) Output: Abstract 1 Next, let’s see how to declare properties as an abstract class. We can use @property decorator and @abc.abstractmethod to declare properties as an abstract class. Let’s look into the below code. Python3 import abc class AbstractClass(metaclass=abc.ABCMeta): @property @abc.abstractmethod def abstractName(self): pass class ValidSubClass(AbstractClass): @property def abstractName(self): return 'Abstract 1' vc = ValidSubClass()print(vc.abstractName) Output: Abstract 1 Python 3 standard library provides a few built-in abstract classes for both abstract and non-abstract methods. These include sequence, mutable sequence, iterable, and so on. It often serves as an alternative to subclassing a built-in Python class. For example, subclassing the MutableSequence can substitute the subclassing of list or str. The main purpose of using Abstract class is that it allows you to consider a common type of collection rather than coding for each type of collection. Here we will discuss Single-Method ABCs and Alternative-Collection ABCs. Single-Method ABCs Alternative-Collection ABCs Python has five abstract base classes. They are as follows: Callable (__call__) Container (__contains__) Hashable (__hash__) Iterable (__iter__) Sized (__len__) These abstract base classes contain one abstract method each. Let’s consider an example of the __len__ method. Python3 from collections.abc import Sized class SingleMethod(object): def __len__(self): return 10 print(issubclass(SingleMethod, Sized)) Output: True Any class that has the appropriate method is considered as the subclass of the abstract base class. Out of the above five abstract base classes, the Iterator is slightly different. It provides an implementation for __iter__ and adds an abstract method called __next__. Alternative-Collection ABCs are built-in abstract base classes that identify subclasses, which serve similar purposes. They can be divided into three categories. Let’s go through one by one. Sequence and Mutable Sequence: Sequence and Mutable Sequence are abstract base classes that generally behaves like tuples or list. A sequence abstract base class requires __getitem__ and __len__ , whereas mutable sequence needs __setitem__ and __getitem__. Mapping: Mapping comes with mutable mapping, which is mainly for dictionary-like objects Set: The set comes with a mutable set that is intended for unordered collections. The key purpose of the abstract class is to check whether an object conforms to a particular protocol. It is a valuable class for testing certain attributes of a class or testing class itself. However, there are many other things that the abstract class does not check. Some of them are signatures, return type, etc. Another advantage is it provides a flexible way for developers to test common types of collections. python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24128, "s": 24100, "text": "\n29 Aug, 2020" }, { "code": null, "e": 24621, "s": 24128, "text": "Have you ever thought about checking whether the objects you are using adheres to a particular specification? It is necessary to verify whether an object implements a given method or property, especially while creating a library where other developers make use of it. A developer can use hasattr or isinstance methods to check whether the input conforms to a particular identity. But sometimes it is inconvenient to use those methods to check a myriad of different properties and methods. " }, { "code": null, "e": 24799, "s": 24621, "text": "As a solution to this inconvenience, Python introduced a concept called abstract base class (abc). In this section, we will discuss the abstract base class and its importance. " }, { "code": null, "e": 24819, "s": 24799, "text": "Abstract Base Class" }, { "code": null, "e": 24852, "s": 24819, "text": "Declaring an Abstract Base Class" }, { "code": null, "e": 24888, "s": 24852, "text": "Why declare an Abstract Base Class?" }, { "code": null, "e": 24908, "s": 24888, "text": "Abstract Properties" }, { "code": null, "e": 24934, "s": 24908, "text": "Built-In Abstract Classes" }, { "code": null, "e": 25304, "s": 24934, "text": "The main goal of the abstract base class is to provide a standardized way to test whether an object adheres to a given specification. It can also prevent any attempt to instantiate a subclass that doesn’t override a particular method in the superclass. And finally, using an abstract class, a class can derive identity from another class without any object inheritance." }, { "code": null, "e": 25588, "s": 25304, "text": "Python has a module called abc (abstract base class) that offers the necessary tools for crafting an abstract base class. First and foremost, you should understand the ABCMeta metaclass provided by the abstract base class. The rule is every abstract class must use ABCMeta metaclass." }, { "code": null, "e": 25923, "s": 25588, "text": "ABCMeta metaclass provides a method called register method that can be invoked by its instance. By using this register method, any abstract base class can become an ancestor of any arbitrary concrete class. Let’s understand this process by considering an example of an abstract base class that registers itself as an ancestor of dict." }, { "code": null, "e": 25931, "s": 25923, "text": "Python3" }, { "code": "import abc class AbstractClass(metaclass=abc.ABCMeta): def abstractfunc(self): return None print(AbstractClass.register(dict))", "e": 26074, "s": 25931, "text": null }, { "code": null, "e": 26082, "s": 26074, "text": "Output:" }, { "code": null, "e": 26097, "s": 26082, "text": "<class 'dict'>" }, { "code": null, "e": 26176, "s": 26097, "text": "Here, dict identifies itself as a subclass of AbstractClass. Let’s do a check." }, { "code": null, "e": 26184, "s": 26176, "text": "Python3" }, { "code": "import abc class AbstractClass(metaclass=abc.ABCMeta): def abstractfunc(self): return None AbstractClass.register(dict)print(issubclass(dict, AbstractClass))", "e": 26358, "s": 26184, "text": null }, { "code": null, "e": 26366, "s": 26358, "text": "Output:" }, { "code": null, "e": 26371, "s": 26366, "text": "True" }, { "code": null, "e": 26644, "s": 26371, "text": "To understand the need to declare a virtual subclass, we need to consider the example of a list-like object where you don’t want to put a restriction of only considering list or tuple. Before that let’s see how to use isinstance to check against a list or tuple of class. " }, { "code": null, "e": 26675, "s": 26644, "text": "isinstance([], (list, tuple))\n" }, { "code": null, "e": 27031, "s": 26675, "text": "This isinstance check meets the purpose if you are accepting only a list or tuple. But here the case is different, there is no such restriction. So, this solution is not extensible for a developer who uses your library to send something else other than a list or tuple. Here comes the importance of abstract class. Let’s understand through the below code." }, { "code": null, "e": 27039, "s": 27031, "text": "Python3" }, { "code": "import abc class MySequence(metaclass=abc.ABCMeta): pass MySequence.register(list)MySequence.register(tuple) a = [1, 2, 3]b = ('x', 'y', 'z') print('List instance:', isinstance(a, MySequence))print('Tuple instance:', isinstance(b, MySequence))print('Object instance:', isinstance(object(), MySequence))", "e": 27351, "s": 27039, "text": null }, { "code": null, "e": 27359, "s": 27351, "text": "Output:" }, { "code": null, "e": 27423, "s": 27359, "text": "List instance: True\nTuple instance: True\nObject instance: False" }, { "code": null, "e": 27783, "s": 27423, "text": "As you can see, when you do isinstance check, it returns true for both the list and tuple; for the other objects, it returns false. Let’s consider a scenario where a developer expects a class object itself. In the above case, the isinstance will return false. But it can be achieved by creating a custom class and registering it with the abstract base class. " }, { "code": null, "e": 27934, "s": 27783, "text": "Here ‘MySequence’ is an abstract class within the library. A developer can import it and register a custom class. Let’s have a look at the below code." }, { "code": null, "e": 27942, "s": 27934, "text": "Python3" }, { "code": "import abc class MySequence(metaclass=abc.ABCMeta): pass class CustomListLikeObjCls(object): pass MySequence.register(CustomListLikeObjCls)print(issubclass(CustomListLikeObjCls, MySequence))", "e": 28144, "s": 27942, "text": null }, { "code": null, "e": 28152, "s": 28144, "text": "Output:" }, { "code": null, "e": 28157, "s": 28152, "text": "True" }, { "code": null, "e": 28463, "s": 28157, "text": "Here, CustomListLikeObjCls instance is passed to the library by registering it with MySequence. Therefore, the instance check returns True. Apart from the above method, you can also use the register method as a decorator to register a custom class. Let’s see how to use the register method as a decorator." }, { "code": null, "e": 28471, "s": 28463, "text": "Python3" }, { "code": "import abc class MySequence(metaclass=abc.ABCMeta): pass @MySequence.registerclass CustomListLikeObjCls(object): pass print(issubclass(CustomListLikeObjCls, MySequence))", "e": 28652, "s": 28471, "text": null }, { "code": null, "e": 28660, "s": 28652, "text": "Output:" }, { "code": null, "e": 28665, "s": 28660, "text": "True" }, { "code": null, "e": 28960, "s": 28665, "text": "Registering a class using the above-implemented method meets the purpose. However, you have to do manual registration for every intended subclass. How about automatic subclassing based on a particular method?. An abstract class has a concept called __subclasshook__ to subclass the classes. " }, { "code": null, "e": 29276, "s": 28960, "text": "It is a special magic method defined by ABCMeta. The __subclasshook__ must be defined as a class method using @classmethod decorator. It takes one additional positional argument other than the class and can return either of the three values – True, False, or NotImplemented. Let’s look at the below implementation." }, { "code": null, "e": 29284, "s": 29276, "text": "Python3" }, { "code": "import abc class AbstractClass(metaclass=abc.ABCMeta): @classmethod def __subclasshook__(cls, other): print('subclass hook:', other) hookmethod = getattr(other, 'hookmethod', None) return callable(hookmethod) class SubClass(object): def hookmethod(self): pass class NormalClass(object): hookmethod = 'hook' print(issubclass(SubClass, AbstractClass))print(issubclass(NormalClass, AbstractClass))", "e": 29727, "s": 29284, "text": null }, { "code": null, "e": 29735, "s": 29727, "text": "Output:" }, { "code": null, "e": 29835, "s": 29735, "text": "subclass hook: <class '__main__.SubClass'>\nTrue\nsubclass hook: <class '__main__.NormalClass'>\nFalse" }, { "code": null, "e": 30092, "s": 29835, "text": "From the above discussion, you understood how to hook subclasses automatically. Now we will look into how to avoid instantiating a subclass that doesn’t override a particular method in the superclass. This feature can be achieved using @abc.abstractmethod." }, { "code": null, "e": 30257, "s": 30092, "text": "@abc.abstractmethod prevents any attempt to instantiate a subclass that doesn’t override a particular method in the superclass. Let’s have a look at the below code:" }, { "code": null, "e": 30265, "s": 30257, "text": "Python3" }, { "code": "import abc class AbstractClass(metaclass=abc.ABCMeta): @abc.abstractmethod def abstractName(self): pass class InvalidSubClass(AbstractClass): pass isc = InvalidSubClass()", "e": 30457, "s": 30265, "text": null }, { "code": null, "e": 30618, "s": 30457, "text": "Since the InvalidSubclass doesn’t override the method abstractName, the @abc.abstractmethod prevents the subclass from instantiation and throws the below error." }, { "code": null, "e": 30844, "s": 30618, "text": "Traceback (most recent call last): File “/home/553d5199a662239eae3ff58efb37b6ec.py”, line 11, in <module> isc = InvalidSubClass()TypeError: Can’t instantiate abstract class InvalidSubClass with abstract methods abstractName" }, { "code": null, "e": 30926, "s": 30844, "text": "Let’s look into another example where the subclass overrides the abstract method." }, { "code": null, "e": 30934, "s": 30926, "text": "Python3" }, { "code": "import abc class AbstractClass(metaclass=abc.ABCMeta): @abc.abstractmethod def abstractName(self): pass class ValidSubClass(AbstractClass): def abstractName(self): return 'Abstract 1' vc = ValidSubClass()print(vc.abstractName())", "e": 31189, "s": 30934, "text": null }, { "code": null, "e": 31197, "s": 31189, "text": "Output:" }, { "code": null, "e": 31208, "s": 31197, "text": "Abstract 1" }, { "code": null, "e": 31272, "s": 31208, "text": "Next, let’s see how to declare properties as an abstract class." }, { "code": null, "e": 31404, "s": 31272, "text": "We can use @property decorator and @abc.abstractmethod to declare properties as an abstract class. Let’s look into the below code." }, { "code": null, "e": 31412, "s": 31404, "text": "Python3" }, { "code": "import abc class AbstractClass(metaclass=abc.ABCMeta): @property @abc.abstractmethod def abstractName(self): pass class ValidSubClass(AbstractClass): @property def abstractName(self): return 'Abstract 1' vc = ValidSubClass()print(vc.abstractName)", "e": 31697, "s": 31412, "text": null }, { "code": null, "e": 31705, "s": 31697, "text": "Output:" }, { "code": null, "e": 31716, "s": 31705, "text": "Abstract 1" }, { "code": null, "e": 32280, "s": 31716, "text": "Python 3 standard library provides a few built-in abstract classes for both abstract and non-abstract methods. These include sequence, mutable sequence, iterable, and so on. It often serves as an alternative to subclassing a built-in Python class. For example, subclassing the MutableSequence can substitute the subclassing of list or str. The main purpose of using Abstract class is that it allows you to consider a common type of collection rather than coding for each type of collection. Here we will discuss Single-Method ABCs and Alternative-Collection ABCs." }, { "code": null, "e": 32299, "s": 32280, "text": "Single-Method ABCs" }, { "code": null, "e": 32327, "s": 32299, "text": "Alternative-Collection ABCs" }, { "code": null, "e": 32387, "s": 32327, "text": "Python has five abstract base classes. They are as follows:" }, { "code": null, "e": 32407, "s": 32387, "text": "Callable (__call__)" }, { "code": null, "e": 32432, "s": 32407, "text": "Container (__contains__)" }, { "code": null, "e": 32452, "s": 32432, "text": "Hashable (__hash__)" }, { "code": null, "e": 32472, "s": 32452, "text": "Iterable (__iter__)" }, { "code": null, "e": 32488, "s": 32472, "text": "Sized (__len__)" }, { "code": null, "e": 32599, "s": 32488, "text": "These abstract base classes contain one abstract method each. Let’s consider an example of the __len__ method." }, { "code": null, "e": 32607, "s": 32599, "text": "Python3" }, { "code": "from collections.abc import Sized class SingleMethod(object): def __len__(self): return 10 print(issubclass(SingleMethod, Sized))", "e": 32753, "s": 32607, "text": null }, { "code": null, "e": 32761, "s": 32753, "text": "Output:" }, { "code": null, "e": 32766, "s": 32761, "text": "True" }, { "code": null, "e": 33035, "s": 32766, "text": "Any class that has the appropriate method is considered as the subclass of the abstract base class. Out of the above five abstract base classes, the Iterator is slightly different. It provides an implementation for __iter__ and adds an abstract method called __next__." }, { "code": null, "e": 33226, "s": 33035, "text": "Alternative-Collection ABCs are built-in abstract base classes that identify subclasses, which serve similar purposes. They can be divided into three categories. Let’s go through one by one." }, { "code": null, "e": 33484, "s": 33226, "text": "Sequence and Mutable Sequence: Sequence and Mutable Sequence are abstract base classes that generally behaves like tuples or list. A sequence abstract base class requires __getitem__ and __len__ , whereas mutable sequence needs __setitem__ and __getitem__." }, { "code": null, "e": 33573, "s": 33484, "text": "Mapping: Mapping comes with mutable mapping, which is mainly for dictionary-like objects" }, { "code": null, "e": 33655, "s": 33573, "text": "Set: The set comes with a mutable set that is intended for unordered collections." }, { "code": null, "e": 34075, "s": 33655, "text": "The key purpose of the abstract class is to check whether an object conforms to a particular protocol. It is a valuable class for testing certain attributes of a class or testing class itself. However, there are many other things that the abstract class does not check. Some of them are signatures, return type, etc. Another advantage is it provides a flexible way for developers to test common types of collections. " }, { "code": null, "e": 34095, "s": 34075, "text": "python-oop-concepts" }, { "code": null, "e": 34102, "s": 34095, "text": "Python" }, { "code": null, "e": 34200, "s": 34102, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34218, "s": 34200, "text": "Python Dictionary" }, { "code": null, "e": 34253, "s": 34218, "text": "Read a file line by line in Python" }, { "code": null, "e": 34275, "s": 34253, "text": "Enumerate() in Python" }, { "code": null, "e": 34307, "s": 34275, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34337, "s": 34307, "text": "Iterate over a list in Python" }, { "code": null, "e": 34379, "s": 34337, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 34405, "s": 34379, "text": "Python String | replace()" }, { "code": null, "e": 34448, "s": 34405, "text": "Python program to convert a list to string" }, { "code": null, "e": 34485, "s": 34448, "text": "Create a Pandas DataFrame from Lists" } ]
Hashing by Division in Data Structure
Here we will discuss about the hashing with division. For this we use the hash function − h(x) = x mod m To use this hash function we maintain an array A[0, ... m – 1]. Where each element of the array is a pointer to the head of the linked list. The linked list Li is pointed to array element A[i] holds all elements x such that h(x) = i. This technique is known as hashing by chaining. In such hash table, if we want to increase an element x, this will take O(1) time. we compute the index i = h(x). Then append or prepend x to the list Li. If we want to search or delete an element, that process is not so easy. We have to find index i = h(x). Then traverse list Li. Until we reach the desired value or the list is exhausted. This operation is taking time corresponding to the size of list Li. If our set S has 0, m, 2m, 3m, ...., nm elements, then all elements stored in L0 will take linear time to search and delete. This kind of situation is very rare. For example, if S are uniformly and independently distributed in the universal set U, and u is a multiple of m, then the expected size of each list Li is only n/m. In this case the searching and deleting takes O(1 + α) amount of time. To avoid the mentioned scenario, we have to choose m wisely. generally, we avoid m as power of 2. Taking m as a prime which is not too closer to power of 2 is recommended.
[ { "code": null, "e": 1152, "s": 1062, "text": "Here we will discuss about the hashing with division. For this we use the hash function −" }, { "code": null, "e": 1167, "s": 1152, "text": "h(x) = x mod m" }, { "code": null, "e": 1449, "s": 1167, "text": "To use this hash function we maintain an array A[0, ... m – 1]. Where each element of the array is a pointer to the head of the linked list. The linked list Li is pointed to array element A[i] holds all elements x such that h(x) = i. This technique is known as hashing by chaining." }, { "code": null, "e": 1983, "s": 1449, "text": "In such hash table, if we want to increase an element x, this will take O(1) time. we compute the index i = h(x). Then append or prepend x to the list Li. If we want to search or delete an element, that process is not so easy. We have to find index i = h(x). Then traverse list Li. Until we reach the desired value or the list is exhausted. This operation is taking time corresponding to the size of list Li. If our set S has 0, m, 2m, 3m, ...., nm elements, then all elements stored in L0 will take linear time to search and delete." }, { "code": null, "e": 2427, "s": 1983, "text": "This kind of situation is very rare. For example, if S are uniformly and independently distributed in the universal set U, and u is a multiple of m, then the expected size of each list Li is only n/m. In this case the searching and deleting takes O(1 + α) amount of time. To avoid the mentioned scenario, we have to choose m wisely. generally, we avoid m as power of 2. Taking m as a prime which is not too closer to power of 2 is recommended." } ]
Boxing and Unboxing in C#
Boxing is the implicit conversion of a value type to a reference type. Unboxing is the explicit conversion of the reference type created by boxing, back to a value type. Let us see an example code snippet − // int int myVal = 12; // Boxing object myBoxed = myVal; // Unboxing int myUnBoxed = (int) myBoxed; Let us see another example that shows an array list in C# − int a = 5; ArrayList arr = new ArrayList(); // Boxing arr.Add(a); // UnBoxing int b = (int)arr[0];
[ { "code": null, "e": 1133, "s": 1062, "text": "Boxing is the implicit conversion of a value type to a reference type." }, { "code": null, "e": 1232, "s": 1133, "text": "Unboxing is the explicit conversion of the reference type created by boxing, back to a value type." }, { "code": null, "e": 1269, "s": 1232, "text": "Let us see an example code snippet −" }, { "code": null, "e": 1369, "s": 1269, "text": "// int\nint myVal = 12;\n// Boxing\nobject myBoxed = myVal;\n// Unboxing\nint myUnBoxed = (int) myBoxed;" }, { "code": null, "e": 1429, "s": 1369, "text": "Let us see another example that shows an array list in C# −" }, { "code": null, "e": 1528, "s": 1429, "text": "int a = 5;\nArrayList arr = new ArrayList();\n// Boxing\narr.Add(a);\n// UnBoxing\nint b = (int)arr[0];" } ]
How to mark strikethrough text in HTML?
To mark strikethrough text in HTML, use the <strike>...</strike> tag. It renders a strikethrough text. HTML deprecated this tag and it shouldn’t be used in HTML5. As an alternative, use the CSS text-decoration property. To use the CSS property, use the style attribute. The style attribute specifies an inline style for an element. The attribute can be used with the HTML <p> tag. Just keep in mind, HTML5 does not support the <strike> tag, so the CSS style should be used. You can try to run the following code to mark strikethrough text in HTML <!DOCTYPE html> <html> <head> <title>HTML Strikethrough text</title> </head> <body> <h1>Heading</h1> <p style="text-decoration: line-through;"> Strikethrough text </p> </body> </html>
[ { "code": null, "e": 1282, "s": 1062, "text": "To mark strikethrough text in HTML, use the <strike>...</strike> tag. It renders a strikethrough text. HTML deprecated this tag and it shouldn’t be used in HTML5. As an alternative, use the CSS text-decoration property." }, { "code": null, "e": 1536, "s": 1282, "text": "To use the CSS property, use the style attribute. The style attribute specifies an inline style for an element. The attribute can be used with the HTML <p> tag. Just keep in mind, HTML5 does not support the <strike> tag, so the CSS style should be used." }, { "code": null, "e": 1609, "s": 1536, "text": "You can try to run the following code to mark strikethrough text in HTML" }, { "code": null, "e": 1794, "s": 1609, "text": "<!DOCTYPE html>\n<html>\n<head>\n<title>HTML Strikethrough text</title>\n</head>\n\n<body>\n<h1>Heading</h1>\n<p style=\"text-decoration: line-through;\">\nStrikethrough text\n</p>\n</body>\n</html>" } ]
Fine-Tuning Transformer Model for Invoice Recognition | by Walid Amamou | Towards Data Science
Building on my recent tutorial on how to annotate PDFs and scanned images for NLP applications, we will attempt to fine-tune the recently released Microsoft’s Layout LM model on an annotated custom dataset that includes French and English invoices. While the previous tutorials focused on using the publicly available FUNSD dataset to fine-tune the model, here we will show the entire process starting from annotation and pre-processing to training and inference. The LayoutLM model is based on BERT architecture but with two additional types of input embeddings. The first is a 2-D position embedding that denotes the relative position of a token within a document, and the second is an image embedding for scanned token images within a document. This model achieved new state-of-the-art results in several downstream tasks, including form understanding (from 70.72 to 79.27), receipt understanding (from 94.02 to 95.24), and document image classification (from 93.07 to 94.42). For more information, refer to the original article. Thankfully, the model was open sourced and made available in huggingface library. Thanks, Microsoft! For this tutorial, we will clone the model directly from the huggingface library and fine-tune it on our own dataset, link to google colab is below. But first, we need to create the training data. https://colab.research.google.com/drive/1KnkVuYW6Ne25hOZ_IApiv_MIYb4lxCAq?usp=sharing Using the UBIAI text annotation tool, I have annotated around 50 personal invoices. I am interested to extract both the keys and values of the entities; for example in the following text “Date: 06/12/2021” we would annotate “Date” as DATE_ID and “06/12/2021” as DATE. Extracting both the keys and values will help us correlate the numerical values to their attributes. Here are all the entities that have been annotated: DATE_ID, DATE, INVOICE_ID, INVOICE_NUMBER,SELLER_ID, SELLER, MONTANT_HT_ID, MONTANT_HT, TVA_ID, TVA, TTC_ID, TTC Here are a few entity definitions: MONTANT_HT: Total price pre-taxTTC: Total price with taxTVA: Tax amount Below is an example of an annotated invoice using UBIAI: After annotation, we export the train and test files from UBIAI directly in the correct format without any pre-processing step. The export will include three files for each training and test datasets and one text file containing all the labels named labels.txt: Train/Test.txt 2018 OSous-total Oen OEUR O3,20 O€ OTVA S-TVA_ID(0%) O0,00 € S-TVATotal B-TTC_IDen I-TTC_IDEUR E-TTC_ID3,20 S-TTC€ OServices Osoumis Oau Omécanisme Od'autoliquidation O- O Train/Test_box.txt (contain bounding box for each token): € 912 457 920 466Services 80 486 133 495soumis 136 487 182 495au 185 488 200 495mécanisme 204 486 276 495d'autoliquidation 279 486 381 497- 383 490 388 492 Train/Test_image.txt (contain bounding box, document size, and name): € 912 425 920 434 1653 2339 image1.jpgTVA 500 441 526 449 1653 2339 image1.jpg(0%) 529 441 557 451 1653 2339 image1.jpg0,00 € 882 441 920 451 1653 2339 image1.jpgTotal 500 457 531 466 1653 2339 image1.jpgen 534 459 549 466 1653 2339 image1.jpgEUR 553 457 578 466 1653 2339 image1.jpg3,20 882 457 911 467 1653 2339 image1.jpg€ 912 457 920 466 1653 2339 image1.jpgServices 80 486 133 495 1653 2339 image1.jpgsoumis 136 487 182 495 1653 2339 image1.jpgau 185 488 200 495 1653 2339 image1.jpgmécanisme 204 486 276 495 1653 2339 image1.jpgd'autoliquidation 279 486 381 497 1653 2339 image1.jpg- 383 490 388 492 1653 2339 image1.jpg labels.txt: B-DATE_IDB-INVOICE_IDB-INVOICE_NUMBERB-MONTANT_HTB-MONTANT_HT_IDB-SELLERB-TTCB-DATEB-TTC_IDB-TVAB-TVA_IDE-DATE_IDE-DATEE-INVOICE_IDE-INVOICE_NUMBERE-MONTANT_HTE-MONTANT_HT_IDE-SELLERE-TTCE-TTC_IDE-TVAE-TVA_IDI-DATE_IDI-DATEI-SELLERI-INVOICE_IDI-MONTANT_HT_IDI-TTCI-TTC_IDI-TVA_IDOS-DATE_IDS-DATES-INVOICE_IDS-INVOICE_NUMBERS-MONTANT_HT_IDS-MONTANT_HTS-SELLERS-TTCS-TTC_IDS-TVAS-TVA_ID Here, we use google colab with GPU to fine-tune the model. The code below is based on the original layoutLM paper and this tutorial . First, install the layoutLM package... ! rm -r unilm! git clone -b remove_torch_save https://github.com/NielsRogge/unilm.git! cd unilm/layoutlm! pip install unilm/layoutlm ...as well as the transformer package from where the model will be downloaded: ! rm -r transformers! git clone https://github.com/huggingface/transformers.git! cd transformers! pip install ./transformers Next, create a list containing the unique labels from labels.txt: from torch.nn import CrossEntropyLossdef get_labels(path): with open(path, "r") as f: labels = f.read().splitlines() if "O" not in labels: labels = ["O"] + labels return labelslabels = get_labels("./labels.txt")num_labels = len(labels)label_map = {i: label for i, label in enumerate(labels)}pad_token_label_id = CrossEntropyLoss().ignore_index Then, create a pytorch dataset and dataloader: from transformers import LayoutLMTokenizerfrom layoutlm.data.funsd import FunsdDataset, InputFeaturesfrom torch.utils.data import DataLoader, RandomSampler, SequentialSamplerargs = {'local_rank': -1, 'overwrite_cache': True, 'data_dir': '/content/data', 'model_name_or_path':'microsoft/layoutlm-base-uncased', 'max_seq_length': 512, 'model_type': 'layoutlm',}# class to turn the keys of a dict into attributesclass AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = selfargs = AttrDict(args)tokenizer = LayoutLMTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")# the LayoutLM authors already defined a specific FunsdDataset, so we are going to use this heretrain_dataset = FunsdDataset(args, tokenizer, labels, pad_token_label_id, mode="train")train_sampler = RandomSampler(train_dataset)train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=2)eval_dataset = FunsdDataset(args, tokenizer, labels, pad_token_label_id, mode="test")eval_sampler = SequentialSampler(eval_dataset)eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=2)batch = next(iter(train_dataloader))input_ids = batch[0][0]tokenizer.decode(input_ids) Load the model from huggingface. This will be fine-tuned on the dataset. from transformers import LayoutLMForTokenClassificationimport torchdevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")model = LayoutLMForTokenClassification.from_pretrained("microsoft/layoutlm-base-uncased", num_labels=num_labels)model.to(device) Finally, start the training: from transformers import AdamWfrom tqdm import tqdmoptimizer = AdamW(model.parameters(), lr=5e-5)global_step = 0num_train_epochs = 50t_total = len(train_dataloader) * num_train_epochs # total number of training steps#put the model in training modemodel.train()for epoch in range(num_train_epochs): for batch in tqdm(train_dataloader, desc="Training"): input_ids = batch[0].to(device) bbox = batch[4].to(device) attention_mask = batch[1].to(device) token_type_ids = batch[2].to(device) labels = batch[3].to(device)# forward pass outputs = model(input_ids=input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids, labels=labels) loss = outputs.loss# print loss every 100 steps if global_step % 100 == 0: print(f"Loss after {global_step} steps: {loss.item()}")# backward pass to get the gradients loss.backward()#print("Gradients on classification head:") #print(model.classifier.weight.grad[6,:].sum())# update optimizer.step() optimizer.zero_grad() global_step += 1 You should be able to see the training progress and the loss getting updated. After training, evaluate the model performance with the following function: import numpy as npfrom seqeval.metrics import ( classification_report, f1_score, precision_score, recall_score,)eval_loss = 0.0nb_eval_steps = 0preds = Noneout_label_ids = None# put model in evaluation modemodel.eval()for batch in tqdm(eval_dataloader, desc="Evaluating"): with torch.no_grad(): input_ids = batch[0].to(device) bbox = batch[4].to(device) attention_mask = batch[1].to(device) token_type_ids = batch[2].to(device) labels = batch[3].to(device)# forward pass outputs = model(input_ids=input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids, labels=labels) # get the loss and logits tmp_eval_loss = outputs.loss logits = outputs.logitseval_loss += tmp_eval_loss.item() nb_eval_steps += 1# compute the predictions if preds is None: preds = logits.detach().cpu().numpy() out_label_ids = labels.detach().cpu().numpy() else: preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) out_label_ids = np.append( out_label_ids, labels.detach().cpu().numpy(), axis=0 )# compute average evaluation losseval_loss = eval_loss / nb_eval_stepspreds = np.argmax(preds, axis=2)out_label_list = [[] for _ in range(out_label_ids.shape[0])]preds_list = [[] for _ in range(out_label_ids.shape[0])]for i in range(out_label_ids.shape[0]): for j in range(out_label_ids.shape[1]): if out_label_ids[i, j] != pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]]) preds_list[i].append(label_map[preds[i][j]])results = { "loss": eval_loss, "precision": precision_score(out_label_list, preds_list), "recall": recall_score(out_label_list, preds_list), "f1": f1_score(out_label_list, preds_list),} With only 50 documents, we get the following scores: With more annotations, we should certainly get higher scores. Finally, save the model for future prediction: PATH='./drive/MyDrive/trained_layoutlm/layoutlm_UBIAI.pt'torch.save(model.state_dict(), PATH) Now comes the fun part, let’s upload an invoice, OCR it, and extract relevant entities. For this test, we are using an invoice that was not in the training or test dataset. To parse the text from the invoice, we use the open source Tesseract package. Let’s install the package: !sudo apt install tesseract-ocr!pip install pytesseract Before running predictions, we need to parse the text from the image and pre-process the tokens and bounding boxes into features. To do so, I have created a preprocess python file layoutLM_preprocess.py that will make it easier to preprocess the image: import syssys.path.insert(1, './drive/MyDrive/UBIAI_layoutlm')from layoutlm_preprocess import *image_path='./content/invoice_test.jpg'image, words, boxes, actual_boxes = preprocess(image_path) Next, load the model and get word predictions with their bounding boxes: model_path='./drive/MyDrive/trained_layoutlm/layoutlm_UBIAI.pt'model=model_load(model_path,num_labels)word_level_predictions, final_boxes=convert_to_features(image, words, boxes, actual_boxes, model) Finally, display the image with the predicted entities and bounding boxes: draw = ImageDraw.Draw(image)font = ImageFont.load_default()def iob_to_label(label): if label != 'O': return label[2:] else: return ""label2color = {'data_id':'green','date':'green','invoice_id':'blue','invoice_number':'blue','montant_ht_id':'black','montant_ht':'black','seller_id':'red','seller':'red', 'ttc_id':'grey','ttc':'grey','':'violet', 'tva_id':'orange','tva':'orange'}for prediction, box in zip(word_level_predictions, final_boxes): predicted_label = iob_to_label(label_map[prediction]).lower() draw.rectangle(box, outline=label2color[predicted_label]) draw.text((box[0] + 10, box[1] - 10), text=predicted_label, fill=label2color[predicted_label], font=font)image Et voila: While the model made few mistakes such as assigning the TTC label to a purchased item or not identifying some IDs, it was able to extract the seller, invoice number, date, and TTC correctly. The results are impressive and very promising given the low number of annotated documents (only 50)! With more annotated invoices, we will be able to reach higher F scores and more accurate predictions. Overall, the results from the LayoutLM model are very promising and demonstrate the usefulness of transformers in analyzing semi-structured text. The model can be fine-tuned on any other semi-structured documents such as driver licences, contracts, government documents, financial documents, etc. If you have any question, don’t hesitate to ask below or send us an email at admin@ubiai.tools. If you liked this article, please like and share! Follow us on Twitter @UBIAI5 or subscribe here!
[ { "code": null, "e": 636, "s": 172, "text": "Building on my recent tutorial on how to annotate PDFs and scanned images for NLP applications, we will attempt to fine-tune the recently released Microsoft’s Layout LM model on an annotated custom dataset that includes French and English invoices. While the previous tutorials focused on using the publicly available FUNSD dataset to fine-tune the model, here we will show the entire process starting from annotation and pre-processing to training and inference." }, { "code": null, "e": 1205, "s": 636, "text": "The LayoutLM model is based on BERT architecture but with two additional types of input embeddings. The first is a 2-D position embedding that denotes the relative position of a token within a document, and the second is an image embedding for scanned token images within a document. This model achieved new state-of-the-art results in several downstream tasks, including form understanding (from 70.72 to 79.27), receipt understanding (from 94.02 to 95.24), and document image classification (from 93.07 to 94.42). For more information, refer to the original article." }, { "code": null, "e": 1306, "s": 1205, "text": "Thankfully, the model was open sourced and made available in huggingface library. Thanks, Microsoft!" }, { "code": null, "e": 1503, "s": 1306, "text": "For this tutorial, we will clone the model directly from the huggingface library and fine-tune it on our own dataset, link to google colab is below. But first, we need to create the training data." }, { "code": null, "e": 1589, "s": 1503, "text": "https://colab.research.google.com/drive/1KnkVuYW6Ne25hOZ_IApiv_MIYb4lxCAq?usp=sharing" }, { "code": null, "e": 2010, "s": 1589, "text": "Using the UBIAI text annotation tool, I have annotated around 50 personal invoices. I am interested to extract both the keys and values of the entities; for example in the following text “Date: 06/12/2021” we would annotate “Date” as DATE_ID and “06/12/2021” as DATE. Extracting both the keys and values will help us correlate the numerical values to their attributes. Here are all the entities that have been annotated:" }, { "code": null, "e": 2123, "s": 2010, "text": "DATE_ID, DATE, INVOICE_ID, INVOICE_NUMBER,SELLER_ID, SELLER, MONTANT_HT_ID, MONTANT_HT, TVA_ID, TVA, TTC_ID, TTC" }, { "code": null, "e": 2158, "s": 2123, "text": "Here are a few entity definitions:" }, { "code": null, "e": 2230, "s": 2158, "text": "MONTANT_HT: Total price pre-taxTTC: Total price with taxTVA: Tax amount" }, { "code": null, "e": 2287, "s": 2230, "text": "Below is an example of an annotated invoice using UBIAI:" }, { "code": null, "e": 2549, "s": 2287, "text": "After annotation, we export the train and test files from UBIAI directly in the correct format without any pre-processing step. The export will include three files for each training and test datasets and one text file containing all the labels named labels.txt:" }, { "code": null, "e": 2564, "s": 2549, "text": "Train/Test.txt" }, { "code": null, "e": 2737, "s": 2564, "text": "2018\tOSous-total\tOen\tOEUR\tO3,20\tO€\tOTVA\tS-TVA_ID(0%)\tO0,00 €\tS-TVATotal\tB-TTC_IDen\tI-TTC_IDEUR\tE-TTC_ID3,20\tS-TTC€\tOServices\tOsoumis\tOau\tOmécanisme\tOd'autoliquidation\tO-\tO" }, { "code": null, "e": 2795, "s": 2737, "text": "Train/Test_box.txt (contain bounding box for each token):" }, { "code": null, "e": 2952, "s": 2795, "text": "€\t912 457 920 466Services\t80 486 133 495soumis\t136 487 182 495au\t185 488 200 495mécanisme\t204 486 276 495d'autoliquidation\t279 486 381 497-\t383 490 388 492" }, { "code": null, "e": 3022, "s": 2952, "text": "Train/Test_image.txt (contain bounding box, document size, and name):" }, { "code": null, "e": 3664, "s": 3022, "text": "€ 912 425 920 434 1653 2339 image1.jpgTVA 500 441 526 449 1653 2339 image1.jpg(0%) 529 441 557 451 1653 2339 image1.jpg0,00 € 882 441 920 451 1653 2339 image1.jpgTotal 500 457 531 466 1653 2339 image1.jpgen 534 459 549 466 1653 2339 image1.jpgEUR 553 457 578 466 1653 2339 image1.jpg3,20 882 457 911 467 1653 2339 image1.jpg€ 912 457 920 466 1653 2339 image1.jpgServices 80 486 133 495 1653 2339 image1.jpgsoumis 136 487 182 495 1653 2339 image1.jpgau 185 488 200 495 1653 2339 image1.jpgmécanisme 204 486 276 495 1653 2339 image1.jpgd'autoliquidation 279 486 381 497 1653 2339 image1.jpg- 383 490 388 492 1653 2339 image1.jpg" }, { "code": null, "e": 3676, "s": 3664, "text": "labels.txt:" }, { "code": null, "e": 4061, "s": 3676, "text": "B-DATE_IDB-INVOICE_IDB-INVOICE_NUMBERB-MONTANT_HTB-MONTANT_HT_IDB-SELLERB-TTCB-DATEB-TTC_IDB-TVAB-TVA_IDE-DATE_IDE-DATEE-INVOICE_IDE-INVOICE_NUMBERE-MONTANT_HTE-MONTANT_HT_IDE-SELLERE-TTCE-TTC_IDE-TVAE-TVA_IDI-DATE_IDI-DATEI-SELLERI-INVOICE_IDI-MONTANT_HT_IDI-TTCI-TTC_IDI-TVA_IDOS-DATE_IDS-DATES-INVOICE_IDS-INVOICE_NUMBERS-MONTANT_HT_IDS-MONTANT_HTS-SELLERS-TTCS-TTC_IDS-TVAS-TVA_ID" }, { "code": null, "e": 4195, "s": 4061, "text": "Here, we use google colab with GPU to fine-tune the model. The code below is based on the original layoutLM paper and this tutorial ." }, { "code": null, "e": 4234, "s": 4195, "text": "First, install the layoutLM package..." }, { "code": null, "e": 4367, "s": 4234, "text": "! rm -r unilm! git clone -b remove_torch_save https://github.com/NielsRogge/unilm.git! cd unilm/layoutlm! pip install unilm/layoutlm" }, { "code": null, "e": 4446, "s": 4367, "text": "...as well as the transformer package from where the model will be downloaded:" }, { "code": null, "e": 4571, "s": 4446, "text": "! rm -r transformers! git clone https://github.com/huggingface/transformers.git! cd transformers! pip install ./transformers" }, { "code": null, "e": 4637, "s": 4571, "text": "Next, create a list containing the unique labels from labels.txt:" }, { "code": null, "e": 5004, "s": 4637, "text": "from torch.nn import CrossEntropyLossdef get_labels(path): with open(path, \"r\") as f: labels = f.read().splitlines() if \"O\" not in labels: labels = [\"O\"] + labels return labelslabels = get_labels(\"./labels.txt\")num_labels = len(labels)label_map = {i: label for i, label in enumerate(labels)}pad_token_label_id = CrossEntropyLoss().ignore_index" }, { "code": null, "e": 5051, "s": 5004, "text": "Then, create a pytorch dataset and dataloader:" }, { "code": null, "e": 6457, "s": 5051, "text": "from transformers import LayoutLMTokenizerfrom layoutlm.data.funsd import FunsdDataset, InputFeaturesfrom torch.utils.data import DataLoader, RandomSampler, SequentialSamplerargs = {'local_rank': -1, 'overwrite_cache': True, 'data_dir': '/content/data', 'model_name_or_path':'microsoft/layoutlm-base-uncased', 'max_seq_length': 512, 'model_type': 'layoutlm',}# class to turn the keys of a dict into attributesclass AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = selfargs = AttrDict(args)tokenizer = LayoutLMTokenizer.from_pretrained(\"microsoft/layoutlm-base-uncased\")# the LayoutLM authors already defined a specific FunsdDataset, so we are going to use this heretrain_dataset = FunsdDataset(args, tokenizer, labels, pad_token_label_id, mode=\"train\")train_sampler = RandomSampler(train_dataset)train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=2)eval_dataset = FunsdDataset(args, tokenizer, labels, pad_token_label_id, mode=\"test\")eval_sampler = SequentialSampler(eval_dataset)eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=2)batch = next(iter(train_dataloader))input_ids = batch[0][0]tokenizer.decode(input_ids)" }, { "code": null, "e": 6530, "s": 6457, "text": "Load the model from huggingface. This will be fine-tuned on the dataset." }, { "code": null, "e": 6795, "s": 6530, "text": "from transformers import LayoutLMForTokenClassificationimport torchdevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")model = LayoutLMForTokenClassification.from_pretrained(\"microsoft/layoutlm-base-uncased\", num_labels=num_labels)model.to(device)" }, { "code": null, "e": 6824, "s": 6795, "text": "Finally, start the training:" }, { "code": null, "e": 7910, "s": 6824, "text": "from transformers import AdamWfrom tqdm import tqdmoptimizer = AdamW(model.parameters(), lr=5e-5)global_step = 0num_train_epochs = 50t_total = len(train_dataloader) * num_train_epochs # total number of training steps#put the model in training modemodel.train()for epoch in range(num_train_epochs): for batch in tqdm(train_dataloader, desc=\"Training\"): input_ids = batch[0].to(device) bbox = batch[4].to(device) attention_mask = batch[1].to(device) token_type_ids = batch[2].to(device) labels = batch[3].to(device)# forward pass outputs = model(input_ids=input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids, labels=labels) loss = outputs.loss# print loss every 100 steps if global_step % 100 == 0: print(f\"Loss after {global_step} steps: {loss.item()}\")# backward pass to get the gradients loss.backward()#print(\"Gradients on classification head:\") #print(model.classifier.weight.grad[6,:].sum())# update optimizer.step() optimizer.zero_grad() global_step += 1" }, { "code": null, "e": 7988, "s": 7910, "text": "You should be able to see the training progress and the loss getting updated." }, { "code": null, "e": 8064, "s": 7988, "text": "After training, evaluate the model performance with the following function:" }, { "code": null, "e": 9936, "s": 8064, "text": "import numpy as npfrom seqeval.metrics import ( classification_report, f1_score, precision_score, recall_score,)eval_loss = 0.0nb_eval_steps = 0preds = Noneout_label_ids = None# put model in evaluation modemodel.eval()for batch in tqdm(eval_dataloader, desc=\"Evaluating\"): with torch.no_grad(): input_ids = batch[0].to(device) bbox = batch[4].to(device) attention_mask = batch[1].to(device) token_type_ids = batch[2].to(device) labels = batch[3].to(device)# forward pass outputs = model(input_ids=input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids, labels=labels) # get the loss and logits tmp_eval_loss = outputs.loss logits = outputs.logitseval_loss += tmp_eval_loss.item() nb_eval_steps += 1# compute the predictions if preds is None: preds = logits.detach().cpu().numpy() out_label_ids = labels.detach().cpu().numpy() else: preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) out_label_ids = np.append( out_label_ids, labels.detach().cpu().numpy(), axis=0 )# compute average evaluation losseval_loss = eval_loss / nb_eval_stepspreds = np.argmax(preds, axis=2)out_label_list = [[] for _ in range(out_label_ids.shape[0])]preds_list = [[] for _ in range(out_label_ids.shape[0])]for i in range(out_label_ids.shape[0]): for j in range(out_label_ids.shape[1]): if out_label_ids[i, j] != pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]]) preds_list[i].append(label_map[preds[i][j]])results = { \"loss\": eval_loss, \"precision\": precision_score(out_label_list, preds_list), \"recall\": recall_score(out_label_list, preds_list), \"f1\": f1_score(out_label_list, preds_list),}" }, { "code": null, "e": 9989, "s": 9936, "text": "With only 50 documents, we get the following scores:" }, { "code": null, "e": 10051, "s": 9989, "text": "With more annotations, we should certainly get higher scores." }, { "code": null, "e": 10098, "s": 10051, "text": "Finally, save the model for future prediction:" }, { "code": null, "e": 10192, "s": 10098, "text": "PATH='./drive/MyDrive/trained_layoutlm/layoutlm_UBIAI.pt'torch.save(model.state_dict(), PATH)" }, { "code": null, "e": 10470, "s": 10192, "text": "Now comes the fun part, let’s upload an invoice, OCR it, and extract relevant entities. For this test, we are using an invoice that was not in the training or test dataset. To parse the text from the invoice, we use the open source Tesseract package. Let’s install the package:" }, { "code": null, "e": 10526, "s": 10470, "text": "!sudo apt install tesseract-ocr!pip install pytesseract" }, { "code": null, "e": 10779, "s": 10526, "text": "Before running predictions, we need to parse the text from the image and pre-process the tokens and bounding boxes into features. To do so, I have created a preprocess python file layoutLM_preprocess.py that will make it easier to preprocess the image:" }, { "code": null, "e": 10972, "s": 10779, "text": "import syssys.path.insert(1, './drive/MyDrive/UBIAI_layoutlm')from layoutlm_preprocess import *image_path='./content/invoice_test.jpg'image, words, boxes, actual_boxes = preprocess(image_path)" }, { "code": null, "e": 11045, "s": 10972, "text": "Next, load the model and get word predictions with their bounding boxes:" }, { "code": null, "e": 11245, "s": 11045, "text": "model_path='./drive/MyDrive/trained_layoutlm/layoutlm_UBIAI.pt'model=model_load(model_path,num_labels)word_level_predictions, final_boxes=convert_to_features(image, words, boxes, actual_boxes, model)" }, { "code": null, "e": 11320, "s": 11245, "text": "Finally, display the image with the predicted entities and bounding boxes:" }, { "code": null, "e": 12012, "s": 11320, "text": "draw = ImageDraw.Draw(image)font = ImageFont.load_default()def iob_to_label(label): if label != 'O': return label[2:] else: return \"\"label2color = {'data_id':'green','date':'green','invoice_id':'blue','invoice_number':'blue','montant_ht_id':'black','montant_ht':'black','seller_id':'red','seller':'red', 'ttc_id':'grey','ttc':'grey','':'violet', 'tva_id':'orange','tva':'orange'}for prediction, box in zip(word_level_predictions, final_boxes): predicted_label = iob_to_label(label_map[prediction]).lower() draw.rectangle(box, outline=label2color[predicted_label]) draw.text((box[0] + 10, box[1] - 10), text=predicted_label, fill=label2color[predicted_label], font=font)image" }, { "code": null, "e": 12022, "s": 12012, "text": "Et voila:" }, { "code": null, "e": 12416, "s": 12022, "text": "While the model made few mistakes such as assigning the TTC label to a purchased item or not identifying some IDs, it was able to extract the seller, invoice number, date, and TTC correctly. The results are impressive and very promising given the low number of annotated documents (only 50)! With more annotated invoices, we will be able to reach higher F scores and more accurate predictions." }, { "code": null, "e": 12713, "s": 12416, "text": "Overall, the results from the LayoutLM model are very promising and demonstrate the usefulness of transformers in analyzing semi-structured text. The model can be fine-tuned on any other semi-structured documents such as driver licences, contracts, government documents, financial documents, etc." }, { "code": null, "e": 12809, "s": 12713, "text": "If you have any question, don’t hesitate to ask below or send us an email at admin@ubiai.tools." }, { "code": null, "e": 12859, "s": 12809, "text": "If you liked this article, please like and share!" } ]