title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
C# | Double.ToString() Method | Set - 2 - GeeksforGeeks
21 Oct, 2021 Double.ToString() Method is used to convert the numeric value of the current instance to its equivalent string representation. There are 4 methods in the overload list of this method as follows: ToString(String) Method ToString() Method ToString(IFormatProvider) Method ToString(String, IFormatProvider) Method Here, we will discuss the last two methods. This method is used to convert the numeric value of the current instance to its equivalent string representation using the specified culture-specific format information.Syntax: public string ToString (IFormatProvider provider); Parameters: This method takes an object of type IFormatProvider which supplies culture-specific formatting information.Return Value: This method returns the string representation of the value of the current instance in the format specified by the provider parameter.Example: csharp // C# program to demonstrate// Double.ToString(IFormatProvider)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // declaring and initializing Double value double d1 = 568912.4587d; // creating and initializing // the object of CultureInfo CultureInfo provider = new CultureInfo("en-us"); // using the method string value = d1.ToString(provider); // Display the value Console.WriteLine("The Value is {0} and provider is {1}", value, provider.Name); }} The Value is 568912.4587 and provider is en-US This method is used to convert the numeric value of the current instance to its equivalent string representation using the specified format and culture-specific formatting information.Syntax: public string ToString (string format, IFormatProvider provider); Parameters: format: It is a numeric format string. provider: It is an object that supplies culture-specific formatting information. Return Value: This method returns the string representation of the value of the current instance in the format specified by the provider parameter.Example: csharp // C# program to demonstrate the// Double.ToString(String, IFormatProvider)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // declaring and initializing Double value double d1 = 7876312.7823d; // creating and initializing // the object of CultureInfo CultureInfo provider = new CultureInfo("fr-FR"); // declaring and initializing format string format = "E04"; // using the method string val = d1.ToString(format, provider); // Displaying the details Console.WriteLine("The value is {0}",val); Console.WriteLine("The Format is {0}",format); Console.WriteLine("The Provider is {0}", provider.Name); }} The value is 7,8763E+006 The Format is E04 The Provider is fr-FR Reference: https://docs.microsoft.com/en-us/dotnet/api/system.double.tostring?view=netframework-4.7.2 sagartomar9927 CSharp-Double-Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Replace() Method C# | Class and Object C# | Constructors Introduction to .NET Framework
[ { "code": null, "e": 26047, "s": 26019, "text": "\n21 Oct, 2021" }, { "code": null, "e": 26243, "s": 26047, "text": "Double.ToString() Method is used to convert the numeric value of the current instance to its equivalent string representation. There are 4 methods in the overload list of this method as follows: " }, { "code": null, "e": 26267, "s": 26243, "text": "ToString(String) Method" }, { "code": null, "e": 26285, "s": 26267, "text": "ToString() Method" }, { "code": null, "e": 26318, "s": 26285, "text": "ToString(IFormatProvider) Method" }, { "code": null, "e": 26359, "s": 26318, "text": "ToString(String, IFormatProvider) Method" }, { "code": null, "e": 26404, "s": 26359, "text": "Here, we will discuss the last two methods. " }, { "code": null, "e": 26582, "s": 26404, "text": "This method is used to convert the numeric value of the current instance to its equivalent string representation using the specified culture-specific format information.Syntax: " }, { "code": null, "e": 26633, "s": 26582, "text": "public string ToString (IFormatProvider provider);" }, { "code": null, "e": 26909, "s": 26633, "text": "Parameters: This method takes an object of type IFormatProvider which supplies culture-specific formatting information.Return Value: This method returns the string representation of the value of the current instance in the format specified by the provider parameter.Example: " }, { "code": null, "e": 26916, "s": 26909, "text": "csharp" }, { "code": "// C# program to demonstrate// Double.ToString(IFormatProvider)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // declaring and initializing Double value double d1 = 568912.4587d; // creating and initializing // the object of CultureInfo CultureInfo provider = new CultureInfo(\"en-us\"); // using the method string value = d1.ToString(provider); // Display the value Console.WriteLine(\"The Value is {0} and provider is {1}\", value, provider.Name); }}", "e": 27544, "s": 26916, "text": null }, { "code": null, "e": 27591, "s": 27544, "text": "The Value is 568912.4587 and provider is en-US" }, { "code": null, "e": 27787, "s": 27593, "text": "This method is used to convert the numeric value of the current instance to its equivalent string representation using the specified format and culture-specific formatting information.Syntax: " }, { "code": null, "e": 27853, "s": 27787, "text": "public string ToString (string format, IFormatProvider provider);" }, { "code": null, "e": 27867, "s": 27853, "text": "Parameters: " }, { "code": null, "e": 27989, "s": 27867, "text": "format: It is a numeric format string. provider: It is an object that supplies culture-specific formatting information. " }, { "code": null, "e": 28146, "s": 27989, "text": "Return Value: This method returns the string representation of the value of the current instance in the format specified by the provider parameter.Example: " }, { "code": null, "e": 28153, "s": 28146, "text": "csharp" }, { "code": "// C# program to demonstrate the// Double.ToString(String, IFormatProvider)// Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // declaring and initializing Double value double d1 = 7876312.7823d; // creating and initializing // the object of CultureInfo CultureInfo provider = new CultureInfo(\"fr-FR\"); // declaring and initializing format string format = \"E04\"; // using the method string val = d1.ToString(format, provider); // Displaying the details Console.WriteLine(\"The value is {0}\",val); Console.WriteLine(\"The Format is {0}\",format); Console.WriteLine(\"The Provider is {0}\", provider.Name); }}", "e": 28919, "s": 28153, "text": null }, { "code": null, "e": 28984, "s": 28919, "text": "The value is 7,8763E+006\nThe Format is E04\nThe Provider is fr-FR" }, { "code": null, "e": 28999, "s": 28986, "text": "Reference: " }, { "code": null, "e": 29090, "s": 28999, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.double.tostring?view=netframework-4.7.2" }, { "code": null, "e": 29107, "s": 29092, "text": "sagartomar9927" }, { "code": null, "e": 29128, "s": 29107, "text": "CSharp-Double-Struct" }, { "code": null, "e": 29142, "s": 29128, "text": "CSharp-method" }, { "code": null, "e": 29145, "s": 29142, "text": "C#" }, { "code": null, "e": 29243, "s": 29145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29271, "s": 29243, "text": "C# Dictionary with examples" }, { "code": null, "e": 29286, "s": 29271, "text": "C# | Delegates" }, { "code": null, "e": 29309, "s": 29286, "text": "C# | Method Overriding" }, { "code": null, "e": 29331, "s": 29309, "text": "C# | Abstract Classes" }, { "code": null, "e": 29377, "s": 29331, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29400, "s": 29377, "text": "Extension Method in C#" }, { "code": null, "e": 29422, "s": 29400, "text": "C# | Replace() Method" }, { "code": null, "e": 29444, "s": 29422, "text": "C# | Class and Object" }, { "code": null, "e": 29462, "s": 29444, "text": "C# | Constructors" } ]
How to make an image responsive in HTML?
To make an image responsive, you need to set two properties. Add image using the <img> tag and add CSS style for height and max-width to make it responsive. For example, style="height:auto;max-width:100%;" You can try to run the following code to make an image responsive in HTML −Note − To check the responsiveness of an image, resize the browser tab. If the image resizes correctly, then it means it is responsive. <!DOCTYPE html> <html> <head></head> <body> <img src="https://www.tutorialspoint.com/images/video_tutorial_intro.jpg" alt="Video Tutorials" style="height:auto;max-width:100%;"> </body> </html>
[ { "code": null, "e": 1268, "s": 1062, "text": "To make an image responsive, you need to set two properties. Add image using the <img> tag and add CSS style for height and max-width to make it responsive. For example, style=\"height:auto;max-width:100%;\"" }, { "code": null, "e": 1479, "s": 1268, "text": "You can try to run the following code to make an image responsive in HTML −Note − To check the responsiveness of an image, resize the browser tab. If the image resizes correctly, then it means it is responsive." }, { "code": null, "e": 1687, "s": 1479, "text": "<!DOCTYPE html>\n<html>\n <head></head>\n <body>\n <img src=\"https://www.tutorialspoint.com/images/video_tutorial_intro.jpg\" alt=\"Video Tutorials\" style=\"height:auto;max-width:100%;\">\n </body>\n</html>" } ]
Swift - Data Types
While doing programming in any programming language, you need to use different types of variables to store information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory. You may like to store information of various data types like string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Swift 4 offers the programmer a rich assortment of built-in as well as user-defined data types. The following types of basic data types are most frequently when declaring variables − Int or UInt − This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64 bit signed integer, whereas UInt32 or UInt64 to define 32 or 64 bit unsigned integer variables. For example, 42 and -23. Int or UInt − This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64 bit signed integer, whereas UInt32 or UInt64 to define 32 or 64 bit unsigned integer variables. For example, 42 and -23. Float − This is used to represent a 32-bit floating-point number and numbers with smaller decimal points. For example, 3.14159, 0.1, and -273.158. Float − This is used to represent a 32-bit floating-point number and numbers with smaller decimal points. For example, 3.14159, 0.1, and -273.158. Double − This is used to represent a 64-bit floating-point number and used when floating-point values must be very large. For example, 3.14159, 0.1, and -273.158. Double − This is used to represent a 64-bit floating-point number and used when floating-point values must be very large. For example, 3.14159, 0.1, and -273.158. Bool − This represents a Boolean value which is either true or false. Bool − This represents a Boolean value which is either true or false. String − This is an ordered collection of characters. For example, "Hello, World!" String − This is an ordered collection of characters. For example, "Hello, World!" Character − This is a single-character string literal. For example, "C" Character − This is a single-character string literal. For example, "C" Optional − This represents a variable that can hold either a value or no value. Optional − This represents a variable that can hold either a value or no value. Tuples − This is used to group multiple values in single Compound Value. Tuples − This is used to group multiple values in single Compound Value. We have listed here a few important points related to Integer types − On a 32-bit platform, Int is the same size as Int32. On a 32-bit platform, Int is the same size as Int32. On a 64-bit platform, Int is the same size as Int64. On a 64-bit platform, Int is the same size as Int64. On a 32-bit platform, UInt is the same size as UInt32. On a 32-bit platform, UInt is the same size as UInt32. On a 64-bit platform, UInt is the same size as UInt64. On a 64-bit platform, UInt is the same size as UInt64. Int8, Int16, Int32, Int64 can be used to represent 8 Bit, 16 Bit, 32 Bit, and 64 Bit forms of signed integer. Int8, Int16, Int32, Int64 can be used to represent 8 Bit, 16 Bit, 32 Bit, and 64 Bit forms of signed integer. UInt8, UInt16, UInt32, and UInt64 can be used to represent 8 Bit, 16 Bit, 32 Bit and 64 Bit forms of unsigned integer. UInt8, UInt16, UInt32, and UInt64 can be used to represent 8 Bit, 16 Bit, 32 Bit and 64 Bit forms of unsigned integer. The following table shows the variable type, how much memory it takes to store the value in memory, and what is the maximum and minimum value which can be stored in such type of variables. You can create a new name for an existing type using typealias. Here is the simple syntax to define a new type using typealias − typealias newname = type For example, the following line instructs the compiler that Feet is another name for Int − typealias Feet = Int Now, the following declaration is perfectly legal and creates an integer variable called distance − typealias Feet = Int var distance: Feet = 100 print(distance) When we run the above program using playground, we get the following result. 100 Swift 4 is a type-safe language which means if a part of your code expects a String, you can't pass it an Int by mistake. As Swift 4 is type-safe, it performs type-checks when compiling your code and flags any mismatched types as errors. var varA = 42 varA = "This is hello" print(varA) When we compile the above program, it produces the following compile time error. main.swift:2:8: error: cannot assign value of type 'String' to type 'Int' varA = "This is hello" Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide. Swift 4 uses type inference to work out the appropriate type as follows. // varA is inferred to be of type Int var varA = 42 print(varA) // varB is inferred to be of type Double var varB = 3.14159 print(varB) // varC is also inferred to be of type Double var varC = 3 + 0.14159 print(varC) When we run the above program using playground, we get the following result − 42 3.14159 3.14159 38 Lectures 1 hours Ashish Sharma 13 Lectures 2 hours Three Millennials 7 Lectures 1 hours Three Millennials 22 Lectures 1 hours Frahaan Hussain 12 Lectures 39 mins Devasena Rajendran 40 Lectures 2.5 hours Grant Klimaytys Print Add Notes Bookmark this page
[ { "code": null, "e": 2520, "s": 2253, "text": "While doing programming in any programming language, you need to use different types of variables to store information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable, you reserve some space in memory." }, { "code": null, "e": 2786, "s": 2520, "text": "You may like to store information of various data types like string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory." }, { "code": null, "e": 2969, "s": 2786, "text": "Swift 4 offers the programmer a rich assortment of built-in as well as user-defined data types. The following types of basic data types are most frequently when declaring variables −" }, { "code": null, "e": 3199, "s": 2969, "text": "Int or UInt − This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64 bit signed integer, whereas UInt32 or UInt64 to define 32 or 64 bit unsigned integer variables. For example, 42 and -23." }, { "code": null, "e": 3429, "s": 3199, "text": "Int or UInt − This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64 bit signed integer, whereas UInt32 or UInt64 to define 32 or 64 bit unsigned integer variables. For example, 42 and -23." }, { "code": null, "e": 3576, "s": 3429, "text": "Float − This is used to represent a 32-bit floating-point number and numbers with smaller decimal points. For example, 3.14159, 0.1, and -273.158." }, { "code": null, "e": 3723, "s": 3576, "text": "Float − This is used to represent a 32-bit floating-point number and numbers with smaller decimal points. For example, 3.14159, 0.1, and -273.158." }, { "code": null, "e": 3886, "s": 3723, "text": "Double − This is used to represent a 64-bit floating-point number and used when floating-point values must be very large. For example, 3.14159, 0.1, and -273.158." }, { "code": null, "e": 4049, "s": 3886, "text": "Double − This is used to represent a 64-bit floating-point number and used when floating-point values must be very large. For example, 3.14159, 0.1, and -273.158." }, { "code": null, "e": 4119, "s": 4049, "text": "Bool − This represents a Boolean value which is either true or false." }, { "code": null, "e": 4189, "s": 4119, "text": "Bool − This represents a Boolean value which is either true or false." }, { "code": null, "e": 4272, "s": 4189, "text": "String − This is an ordered collection of characters. For example, \"Hello, World!\"" }, { "code": null, "e": 4355, "s": 4272, "text": "String − This is an ordered collection of characters. For example, \"Hello, World!\"" }, { "code": null, "e": 4427, "s": 4355, "text": "Character − This is a single-character string literal. For example, \"C\"" }, { "code": null, "e": 4499, "s": 4427, "text": "Character − This is a single-character string literal. For example, \"C\"" }, { "code": null, "e": 4579, "s": 4499, "text": "Optional − This represents a variable that can hold either a value or no value." }, { "code": null, "e": 4659, "s": 4579, "text": "Optional − This represents a variable that can hold either a value or no value." }, { "code": null, "e": 4732, "s": 4659, "text": "Tuples − This is used to group multiple values in single Compound Value." }, { "code": null, "e": 4805, "s": 4732, "text": "Tuples − This is used to group multiple values in single Compound Value." }, { "code": null, "e": 4875, "s": 4805, "text": "We have listed here a few important points related to Integer types −" }, { "code": null, "e": 4928, "s": 4875, "text": "On a 32-bit platform, Int is the same size as Int32." }, { "code": null, "e": 4981, "s": 4928, "text": "On a 32-bit platform, Int is the same size as Int32." }, { "code": null, "e": 5034, "s": 4981, "text": "On a 64-bit platform, Int is the same size as Int64." }, { "code": null, "e": 5087, "s": 5034, "text": "On a 64-bit platform, Int is the same size as Int64." }, { "code": null, "e": 5142, "s": 5087, "text": "On a 32-bit platform, UInt is the same size as UInt32." }, { "code": null, "e": 5197, "s": 5142, "text": "On a 32-bit platform, UInt is the same size as UInt32." }, { "code": null, "e": 5252, "s": 5197, "text": "On a 64-bit platform, UInt is the same size as UInt64." }, { "code": null, "e": 5307, "s": 5252, "text": "On a 64-bit platform, UInt is the same size as UInt64." }, { "code": null, "e": 5417, "s": 5307, "text": "Int8, Int16, Int32, Int64 can be used to represent 8 Bit, 16 Bit, 32 Bit, and 64 Bit forms of signed integer." }, { "code": null, "e": 5527, "s": 5417, "text": "Int8, Int16, Int32, Int64 can be used to represent 8 Bit, 16 Bit, 32 Bit, and 64 Bit forms of signed integer." }, { "code": null, "e": 5646, "s": 5527, "text": "UInt8, UInt16, UInt32, and UInt64 can be used to represent 8 Bit, 16 Bit, 32 Bit and 64 Bit forms of unsigned integer." }, { "code": null, "e": 5765, "s": 5646, "text": "UInt8, UInt16, UInt32, and UInt64 can be used to represent 8 Bit, 16 Bit, 32 Bit and 64 Bit forms of unsigned integer." }, { "code": null, "e": 5954, "s": 5765, "text": "The following table shows the variable type, how much memory it takes to store the value in memory, and what is the maximum and minimum value which can be stored in such type of variables." }, { "code": null, "e": 6083, "s": 5954, "text": "You can create a new name for an existing type using typealias. Here is the simple syntax to define a new type using typealias −" }, { "code": null, "e": 6109, "s": 6083, "text": "typealias newname = type\n" }, { "code": null, "e": 6200, "s": 6109, "text": "For example, the following line instructs the compiler that Feet is another name for Int −" }, { "code": null, "e": 6222, "s": 6200, "text": "typealias Feet = Int\n" }, { "code": null, "e": 6322, "s": 6222, "text": "Now, the following declaration is perfectly legal and creates an integer variable called distance −" }, { "code": null, "e": 6384, "s": 6322, "text": "typealias Feet = Int\nvar distance: Feet = 100\nprint(distance)" }, { "code": null, "e": 6461, "s": 6384, "text": "When we run the above program using playground, we get the following result." }, { "code": null, "e": 6466, "s": 6461, "text": "100\n" }, { "code": null, "e": 6588, "s": 6466, "text": "Swift 4 is a type-safe language which means if a part of your code expects a String, you can't pass it an Int by mistake." }, { "code": null, "e": 6704, "s": 6588, "text": "As Swift 4 is type-safe, it performs type-checks when compiling your code and flags any mismatched types as errors." }, { "code": null, "e": 6753, "s": 6704, "text": "var varA = 42\nvarA = \"This is hello\"\nprint(varA)" }, { "code": null, "e": 6834, "s": 6753, "text": "When we compile the above program, it produces the following compile time error." }, { "code": null, "e": 6932, "s": 6834, "text": "main.swift:2:8: error: cannot assign value of type 'String' to type 'Int'\nvarA = \"This is hello\"\n" }, { "code": null, "e": 7171, "s": 6932, "text": "Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide. Swift 4 uses type inference to work out the appropriate type as follows." }, { "code": null, "e": 7390, "s": 7171, "text": "// varA is inferred to be of type Int\nvar varA = 42\nprint(varA)\n\n// varB is inferred to be of type Double\nvar varB = 3.14159\nprint(varB)\n\n// varC is also inferred to be of type Double\nvar varC = 3 + 0.14159\nprint(varC)" }, { "code": null, "e": 7468, "s": 7390, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 7488, "s": 7468, "text": "42\n3.14159\n3.14159\n" }, { "code": null, "e": 7521, "s": 7488, "text": "\n 38 Lectures \n 1 hours \n" }, { "code": null, "e": 7536, "s": 7521, "text": " Ashish Sharma" }, { "code": null, "e": 7569, "s": 7536, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 7588, "s": 7569, "text": " Three Millennials" }, { "code": null, "e": 7620, "s": 7588, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 7639, "s": 7620, "text": " Three Millennials" }, { "code": null, "e": 7672, "s": 7639, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 7689, "s": 7672, "text": " Frahaan Hussain" }, { "code": null, "e": 7721, "s": 7689, "text": "\n 12 Lectures \n 39 mins\n" }, { "code": null, "e": 7741, "s": 7721, "text": " Devasena Rajendran" }, { "code": null, "e": 7776, "s": 7741, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7793, "s": 7776, "text": " Grant Klimaytys" }, { "code": null, "e": 7800, "s": 7793, "text": " Print" }, { "code": null, "e": 7811, "s": 7800, "text": " Add Notes" } ]
Convert list of numerical string to list of Integers in Python
For data manipulation using python, we may come across scenario where we have strings containing numbers in a list. To be able to make calculations, we will need to change the strings into numbers. In this article we will see the ways to change the strings into numbers inside a list. The int function can be applied to the string elements of a list converting them to integers . We have to carefully design the for loops to go through each element and get the result even if there are multiple strings inside a single element. Live Demo listA = [['29','12'], ['25'], ['70']] # Given lists print("Given list A: ", listA) # Use int res = [[int(n) for n in element] for i in listA for element in i] # Result print("The numeric lists: ",res) Running the above code gives us the following result − Given list A: [['29', '12'], ['25'], ['70']] The numeric lists: [[2, 9], [1, 2], [2, 5], [7, 0]] We can also use the map function which will apply a given function again and again to each parameter that is supplied to this function. We create a for loop which fetches the elements form each of the inner lists. This approach does not work if the inner lists have multiple elements inside them. Live Demo listA = [['29'], ['25'], ['70']] # Given lists print("Given list A: ", listA) # Use map res = [list(map(int, list(elem[0]))) for elem in listA if elem ] # Result print("The numeric lists: ",res) Running the above code gives us the following result − Given list A: [['29'], ['25'], ['70']] The numeric lists: [[2, 9], [2, 5], [7, 0]]
[ { "code": null, "e": 1347, "s": 1062, "text": "For data manipulation using python, we may come across scenario where we have strings containing numbers in a list. To be able to make calculations, we will need to change the strings into numbers. In this article we will see the ways to change the strings into numbers inside a list." }, { "code": null, "e": 1590, "s": 1347, "text": "The int function can be applied to the string elements of a list converting them to integers . We have to carefully design the for loops to go through each element and get the result even if there are multiple strings inside a single element." }, { "code": null, "e": 1601, "s": 1590, "text": " Live Demo" }, { "code": null, "e": 1802, "s": 1601, "text": "listA = [['29','12'], ['25'], ['70']]\n# Given lists\nprint(\"Given list A: \", listA)\n# Use int\nres = [[int(n) for n in element] for i in listA for element in i]\n# Result\nprint(\"The numeric lists: \",res)" }, { "code": null, "e": 1857, "s": 1802, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1954, "s": 1857, "text": "Given list A: [['29', '12'], ['25'], ['70']]\nThe numeric lists: [[2, 9], [1, 2], [2, 5], [7, 0]]" }, { "code": null, "e": 2251, "s": 1954, "text": "We can also use the map function which will apply a given function again and again to each parameter that is supplied to this function. We create a for loop which fetches the elements form each of the inner lists. This approach does not work if the inner lists have multiple elements inside them." }, { "code": null, "e": 2262, "s": 2251, "text": " Live Demo" }, { "code": null, "e": 2457, "s": 2262, "text": "listA = [['29'], ['25'], ['70']]\n# Given lists\nprint(\"Given list A: \", listA)\n# Use map\nres = [list(map(int, list(elem[0]))) for elem in listA if elem ]\n# Result\nprint(\"The numeric lists: \",res)" }, { "code": null, "e": 2512, "s": 2457, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2595, "s": 2512, "text": "Given list A: [['29'], ['25'], ['70']]\nThe numeric lists: [[2, 9], [2, 5], [7, 0]]" } ]
Why window function in SQL is so important that you should learn it right now | by WY Fok | Towards Data Science
In my last article, I mentioned that I was asked about how to use a window function many times. And after mastering it, I am sure that I should learn much earlier because it can help me carry out more in-depth analysis through SQL. My last article about using SQL for data analysis towardsdatascience.com Not like group by function which will reduce the number of rows, window function can perform the aggregation for each row without reducing. There are a number of different window functions. But today I will tell you basic knowledge on how to use window function and how you can apply in your data analysis. The dataset that I will use today is “student-mat” from “Student Alcohol Consumption” obtained from Kaggle. Then the dataset is stored in dataset.student_mat. You can download the dataset from the below link: www.kaggle.com In general, there are two types of window functions; one is built-in function like row_number, dense_rank, lag, and lead; another is aggregation just like usual aggregation function. For window function, there is a significant keyword “over” . Once you notice “over” within a query, you can tell there is a window function. In the first part, I will explain how to use the aggregate window function since I believe you already have some knowledge of using normal aggregation function. After knowing the basics of window function it is easier to understand built-in functions. Aggregate window functionBuilt-in window function Aggregate window function Built-in window function The basic syntax for an aggregate window function is a normal aggregation function but following an over clause statement. Here I will use the data to demonstrate. The first three columns in the dataset are school, sex, and age. And now you want to know the age difference for each sex versus overall in each school. Then you can use the window function. The first step is to calculate the average age per school. This can be obtained from ‘avg(age) over (partition by school)’ . The first part before over is the same as the normal average function. The second part after over is called “partition by” clause which is required to be enclosed by parentheses. “Partition by school” means all records with the same values in school are selected and carry the calculation. select school, sex,age, avg(age) over (partition by school) as age_avg_by_shl , age - avg(age) over (partition by school) as age_diff_from_shl_avg from dataset.student_mat 16.5215 for school equal to “GP” and 18.0217 for school equal to MS match with normal average function group by the school. So now you can calculate the difference between each student and the average, as what age_diff_from_shl_avg performs in the query. Finally, you can get the average age difference by school and sex. select school, sex, round(avg(age),2) as avg_age , round(avg(age_avg_by_shl),2) as avg_age_school, round(avg(age_diff_from_shl_avg),2) as avg_age_diff_from_shlfrom (select school, sex,age, avg(age) over (partition by school) as age_avg_by_shl , age - avg(age) over (partition by school) as age_diff_from_shl_avg from dataset.student_mat ) agroup by school, sex From now you can tell the age for females is higher than males in GP but not in MS. There is another column address showing whether the student lives in urban or rural areas. Then you can use a window function to calculate the percentage of students living in each area by school and area. The first step is to calculate the number of students in each combination of school and address as a usual group by aggregation. Then to calculate the number of students over the total number of students in each school and in each address area by using window functions. “sum(student_cnt) over (partition by school)” will return the total numbers of students for GP and MS while “student_cnt / sum(student_cnt) over (partition by address)” will return the total numbers of students for urban and rural areas. As a result, you can get the percentage of students by school and address area. select school, address, student_cnt, student_cnt / sum(student_cnt) over (partition by school) as percent_by_shl, student_cnt / sum(student_cnt) over (partition by address) as percent_by_addressfrom (select school, address, count(1) as student_cntfrom dataset.student_mat group by school, address) a So you can tell there are more students in GP living in an urban area while there are more students in MS living in a rural area. And if you find a student living in urban area, you are almost certain that this student is from GP since over 93% of urban students study in GP. This already becomes a predictive analysis that you can use to classify the school for the student by its address only. The third example of the aggregation window function is a bit more complex. Since the dataset is called “Student Alcohol Consumption”, of course, we should do some analyses on it. There are two categorical columns “Dalc” and “Walc” showing consumption on workday and weekend. Then we can find out if alcohol consumption will impact the final result indicated by column “g3”. To simplify, I will just add up two columns together rather than separating them. Then to calculate the overall average of g3 and also the difference between individual g3 and the overall average of g3. To calculate the overall average of g3, here we cannot use group by function since this will reduce the number of rows. Instead, we use the window function to obtain and put the result on each row. The second part after over for syntax “avg(g3) over ()” is empty because we don’t need to categorize the dataset. We need the whole dataset to calculate the overall average. Therefore the parentheses are empty inside. Now you can calculate the average difference for each wkalc group. select wkalc, round(avg(avg_g3_overall),2) as avg_g3_overall, round(avg(g3),2) as avg_g3, round(avg(g3_diff),2) as avg_g3_difffrom (select (Dalc + Walc) as wkalc, g3, avg(g3) over () as avg_g3_overall, g3 - avg(g3) over () as g3_difffrom dataset.student_mat) a group by wkalcorder by wkalc There is no clear relationship between alcohol consumption and g3 results. So let’s drink (?) Now I hope you know basic usage on aggregation window function. Next, I will talk about the built-in window function. Below is the list for 11 built-in window functions : CUME_DIST(), DENSE_RANK(), FIRST_VALUE(), LAG(), LAST_VALUE() LEAD(), NTH_VALUE(), NTILE(), PERCENT_RANK(), RANK(), ROW_NUMBER() I will not explain all in detail. You can get the detailed information from the below link: dev.mysql.com I will use rank() as an example to demonstrate how to use it. Similar to the aggregation window function, an over clause statement is required. There is a categorical column “studytime” from 1 to 4. And we want to know if study time is a factor of g3. Apart from calculating the average of g3 by studytime, we can use rank() to get the order. After getting the average of g3 for each studytime, we can use the average result to rank the order by descending order. Then we can order the ranking to get the comparison directly. This method is useful especially when there are many groups that it is not possible to get ranking by naked eyes. select studytime, avg_g3, rank() over (order by avg_g3 desc) as ranking from (select studytime, avg(g3) as avg_g3from dataset.student_matgroup by studytime) aorder by ranking So it is still true the studying more will get better results. PS: There are other two built-in functions which also provide a ranking, one is dense_rank(), another is row_number(). The difference is how they return ranks when there are rows with the same values. You can know more from the below link: https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html#function_rank Mastering window functions provides you much more in-depth data analysis and sometimes it can even help you perform predictive analytics. As I said in my last article, mastering SQL is necessary for landing a data analyst position and window function is constantly asked during an interview (I can’t remember how many times I was asked about it during interviews). Therefore you should also start learning window functions after reading my article. I hope you can master it as well and get your dream job. That’s all for today’s article. If you enjoy it, please leave your comment and give me a clap. And share this article to let more people know the importance of window function. See you next time.
[ { "code": null, "e": 404, "s": 172, "text": "In my last article, I mentioned that I was asked about how to use a window function many times. And after mastering it, I am sure that I should learn much earlier because it can help me carry out more in-depth analysis through SQL." }, { "code": null, "e": 454, "s": 404, "text": "My last article about using SQL for data analysis" }, { "code": null, "e": 477, "s": 454, "text": "towardsdatascience.com" }, { "code": null, "e": 784, "s": 477, "text": "Not like group by function which will reduce the number of rows, window function can perform the aggregation for each row without reducing. There are a number of different window functions. But today I will tell you basic knowledge on how to use window function and how you can apply in your data analysis." }, { "code": null, "e": 993, "s": 784, "text": "The dataset that I will use today is “student-mat” from “Student Alcohol Consumption” obtained from Kaggle. Then the dataset is stored in dataset.student_mat. You can download the dataset from the below link:" }, { "code": null, "e": 1008, "s": 993, "text": "www.kaggle.com" }, { "code": null, "e": 1332, "s": 1008, "text": "In general, there are two types of window functions; one is built-in function like row_number, dense_rank, lag, and lead; another is aggregation just like usual aggregation function. For window function, there is a significant keyword “over” . Once you notice “over” within a query, you can tell there is a window function." }, { "code": null, "e": 1584, "s": 1332, "text": "In the first part, I will explain how to use the aggregate window function since I believe you already have some knowledge of using normal aggregation function. After knowing the basics of window function it is easier to understand built-in functions." }, { "code": null, "e": 1634, "s": 1584, "text": "Aggregate window functionBuilt-in window function" }, { "code": null, "e": 1660, "s": 1634, "text": "Aggregate window function" }, { "code": null, "e": 1685, "s": 1660, "text": "Built-in window function" }, { "code": null, "e": 2040, "s": 1685, "text": "The basic syntax for an aggregate window function is a normal aggregation function but following an over clause statement. Here I will use the data to demonstrate. The first three columns in the dataset are school, sex, and age. And now you want to know the age difference for each sex versus overall in each school. Then you can use the window function." }, { "code": null, "e": 2455, "s": 2040, "text": "The first step is to calculate the average age per school. This can be obtained from ‘avg(age) over (partition by school)’ . The first part before over is the same as the normal average function. The second part after over is called “partition by” clause which is required to be enclosed by parentheses. “Partition by school” means all records with the same values in school are selected and carry the calculation." }, { "code": null, "e": 2627, "s": 2455, "text": "select school, sex,age, avg(age) over (partition by school) as age_avg_by_shl , age - avg(age) over (partition by school) as age_diff_from_shl_avg from dataset.student_mat" }, { "code": null, "e": 2751, "s": 2627, "text": "16.5215 for school equal to “GP” and 18.0217 for school equal to MS match with normal average function group by the school." }, { "code": null, "e": 2882, "s": 2751, "text": "So now you can calculate the difference between each student and the average, as what age_diff_from_shl_avg performs in the query." }, { "code": null, "e": 2949, "s": 2882, "text": "Finally, you can get the average age difference by school and sex." }, { "code": null, "e": 3310, "s": 2949, "text": "select school, sex, round(avg(age),2) as avg_age , round(avg(age_avg_by_shl),2) as avg_age_school, round(avg(age_diff_from_shl_avg),2) as avg_age_diff_from_shlfrom (select school, sex,age, avg(age) over (partition by school) as age_avg_by_shl , age - avg(age) over (partition by school) as age_diff_from_shl_avg from dataset.student_mat ) agroup by school, sex" }, { "code": null, "e": 3394, "s": 3310, "text": "From now you can tell the age for females is higher than males in GP but not in MS." }, { "code": null, "e": 3600, "s": 3394, "text": "There is another column address showing whether the student lives in urban or rural areas. Then you can use a window function to calculate the percentage of students living in each area by school and area." }, { "code": null, "e": 4189, "s": 3600, "text": "The first step is to calculate the number of students in each combination of school and address as a usual group by aggregation. Then to calculate the number of students over the total number of students in each school and in each address area by using window functions. “sum(student_cnt) over (partition by school)” will return the total numbers of students for GP and MS while “student_cnt / sum(student_cnt) over (partition by address)” will return the total numbers of students for urban and rural areas. As a result, you can get the percentage of students by school and address area." }, { "code": null, "e": 4489, "s": 4189, "text": "select school, address, student_cnt, student_cnt / sum(student_cnt) over (partition by school) as percent_by_shl, student_cnt / sum(student_cnt) over (partition by address) as percent_by_addressfrom (select school, address, count(1) as student_cntfrom dataset.student_mat group by school, address) a" }, { "code": null, "e": 4885, "s": 4489, "text": "So you can tell there are more students in GP living in an urban area while there are more students in MS living in a rural area. And if you find a student living in urban area, you are almost certain that this student is from GP since over 93% of urban students study in GP. This already becomes a predictive analysis that you can use to classify the school for the student by its address only." }, { "code": null, "e": 5260, "s": 4885, "text": "The third example of the aggregation window function is a bit more complex. Since the dataset is called “Student Alcohol Consumption”, of course, we should do some analyses on it. There are two categorical columns “Dalc” and “Walc” showing consumption on workday and weekend. Then we can find out if alcohol consumption will impact the final result indicated by column “g3”." }, { "code": null, "e": 5661, "s": 5260, "text": "To simplify, I will just add up two columns together rather than separating them. Then to calculate the overall average of g3 and also the difference between individual g3 and the overall average of g3. To calculate the overall average of g3, here we cannot use group by function since this will reduce the number of rows. Instead, we use the window function to obtain and put the result on each row." }, { "code": null, "e": 5879, "s": 5661, "text": "The second part after over for syntax “avg(g3) over ()” is empty because we don’t need to categorize the dataset. We need the whole dataset to calculate the overall average. Therefore the parentheses are empty inside." }, { "code": null, "e": 5946, "s": 5879, "text": "Now you can calculate the average difference for each wkalc group." }, { "code": null, "e": 6237, "s": 5946, "text": "select wkalc, round(avg(avg_g3_overall),2) as avg_g3_overall, round(avg(g3),2) as avg_g3, round(avg(g3_diff),2) as avg_g3_difffrom (select (Dalc + Walc) as wkalc, g3, avg(g3) over () as avg_g3_overall, g3 - avg(g3) over () as g3_difffrom dataset.student_mat) a group by wkalcorder by wkalc" }, { "code": null, "e": 6331, "s": 6237, "text": "There is no clear relationship between alcohol consumption and g3 results. So let’s drink (?)" }, { "code": null, "e": 6502, "s": 6331, "text": "Now I hope you know basic usage on aggregation window function. Next, I will talk about the built-in window function. Below is the list for 11 built-in window functions :" }, { "code": null, "e": 6631, "s": 6502, "text": "CUME_DIST(), DENSE_RANK(), FIRST_VALUE(), LAG(), LAST_VALUE() LEAD(), NTH_VALUE(), NTILE(), PERCENT_RANK(), RANK(), ROW_NUMBER()" }, { "code": null, "e": 6723, "s": 6631, "text": "I will not explain all in detail. You can get the detailed information from the below link:" }, { "code": null, "e": 6737, "s": 6723, "text": "dev.mysql.com" }, { "code": null, "e": 6799, "s": 6737, "text": "I will use rank() as an example to demonstrate how to use it." }, { "code": null, "e": 6881, "s": 6799, "text": "Similar to the aggregation window function, an over clause statement is required." }, { "code": null, "e": 7080, "s": 6881, "text": "There is a categorical column “studytime” from 1 to 4. And we want to know if study time is a factor of g3. Apart from calculating the average of g3 by studytime, we can use rank() to get the order." }, { "code": null, "e": 7377, "s": 7080, "text": "After getting the average of g3 for each studytime, we can use the average result to rank the order by descending order. Then we can order the ranking to get the comparison directly. This method is useful especially when there are many groups that it is not possible to get ranking by naked eyes." }, { "code": null, "e": 7552, "s": 7377, "text": "select studytime, avg_g3, rank() over (order by avg_g3 desc) as ranking from (select studytime, avg(g3) as avg_g3from dataset.student_matgroup by studytime) aorder by ranking" }, { "code": null, "e": 7615, "s": 7552, "text": "So it is still true the studying more will get better results." }, { "code": null, "e": 7855, "s": 7615, "text": "PS: There are other two built-in functions which also provide a ranking, one is dense_rank(), another is row_number(). The difference is how they return ranks when there are rows with the same values. You can know more from the below link:" }, { "code": null, "e": 7943, "s": 7855, "text": "https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html#function_rank" } ]
Day of the week | Practice | GeeksforGeeks
Write a program that calculates the day of the week for any particular date in the past or future. Example 1: Input: d = 28, m = 12, y = 1995 Output: Thursday Explanation: 28 December 1995 was a Thursday. Example 2: Input: d = 30, m = 8, y = 2010 Output: Monday Explanation: 30 August 2010 was a Monday. Your Task: You don't need to read input or print anything. Your task is to complete the function getDayOfWeek() which takes 3 Integers d, m and y denoting day, month and year as input and return a String denoting the answer. Expected Time Complexity: O(1) Expected Auxiliary Space: O(1) Constraints: 1 <= d <= 31 1 <= m <= 12 1990 <= y <= 2100 0 aloksinghmp552 weeks ago in this question it says 29/02/2100 ,it will be monday and 01/03/2100 ,it will also monday. how can it possible. what is wrong in this code ??? string getDayOfWeek(int d, int m, int y) { string day[7]={ "Sunday","Monday","Tuesday","Wednesday","Thursday", "Friday","Saturday"}; int i,j; int mon[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; long long sum=0; for(int i=1990;i<y;i++){ if(i%4==0){ sum=sum+366; } else{ sum=sum+365; } } for(j=1;j<m;j++){ if(j==2 && (y%4==0)){ sum=sum+1; } sum=sum+mon[j]; } sum=sum+d; return day[sum%7]; } +1 rahulgupta067892 months ago string getDayOfWeek(int d, int m, int y) { string days[]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}; static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; y -= m < 3; int n=( y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7; return days[n]; } 0 ankitparashxr4 months ago lass Solution { static String getDayOfWeek(int d, int m, int y) { String days[] ={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday",}; //k is the day of the month. //m is the month number. //D is the last two digits of the year. //C is the first two digits of the year. if(m<3) { m+=12; y-=1; } int k = d; int D = y%100; int C = y/100; int x =(C/4-2*C+D+D/4+13*(m+1)/5+k-1)%7; int val = x%7; if(val<0) { int num = val/7; num = num-1; int num2 = num*7; int num3 = val-num2; return days[num3]; } return days[x%7]; }}; 0 bhavit mathur11 months ago bhavit mathur string getDayOfWeek(int d, int m, int y) { static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; y -= m < 3; int x= ( y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7; if(x==0) { return "Sunday"; } if(x==1) { return "Monday"; } if(x==2) { return "Tuesday"; } if(x==3) { return "Wednesday"; } if(x==4) { return "Thursday"; } if(x==5) { return "Friday"; } if(x==6) { return "Saturday"; } } 0 Raj Kumar11 months ago Raj Kumar TC : 0.42Map<integer ,="" string=""> map = new HashMap<>(); map.put(0,"Sunday"); map.put(1,"Monday"); map.put(2,"Tuesday"); map.put(3,"Wednesday"); map.put(4,"Thursday"); map.put(5,"Friday"); map.put(6,"Saturday"); //the Tomohiko Sakamoto Algorithm int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; // if month is less than 3 reduce year by 1 if (m < 3) y -= 1; int day = (y + (y/4) - (y/100) + (y/400) + (t[m - 1] + d)) % 7; String dayOftheWeek= map.get(day); return dayOftheWeek; 0 Bharat Gupta1 year ago Bharat Gupta Test cases don't match with constraints. Mine gave a WA for year 1435. 0 Aman Kumar Mishra1 year ago Aman Kumar Mishra The test cases used are wrong. For 1 1 492 , it is showing correct answer is Tuesday but actually it should be Wednesday. Here is the correct code in java 1.8:- static String getDayOfWeek(int d, int m, int y) { // code here Map<integer,integer> monthCode = new HashMap<integer,integer>(); monthCode.put(1,1); monthCode.put(2,4); monthCode.put(3,4); monthCode.put(4,0); monthCode.put(5,2); monthCode.put(6,5); monthCode.put(7,0); monthCode.put(8,3); monthCode.put(9,6); monthCode.put(10,1); monthCode.put(11,4); monthCode.put(12,6); Map<integer,string> dayCode = new HashMap<integer,string>(); dayCode.put(0,"Saturday"); dayCode.put(1,"Sunday"); dayCode.put(2,"Monday"); dayCode.put(3,"Tuesday"); dayCode.put(4,"Wednesday"); dayCode.put(5,"Thursday"); dayCode.put(6,"Friday"); int n = y; int count = 0; int sum = 0,r; while(count < 2) { r = n % 10; n = n / 10; sum = sum + (int)Math.pow(10,count)*r; count++; } int leap = sum / 4; sum = d + monthCode.get(m) + centuryCode(n) + sum + sum/4; int ans = sum % 7; return dayCode.get(ans); } static int centuryCode(int century) { int[] code = {6,4,2,0}; int x = 0, res = 0; for(int i = 0; i <= century; i++) { res = code[x%4]; x++; } return res; } 0 SUMITHRA S2 years ago SUMITHRA S import datetimedef dateday(l): week_days=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] day=datetime.date(l[2],l[1],l[0]).weekday() print(week_days[day])for i in range(int(input())): l=list(map(int,input().split())) dateday(l) 0 Riya kashyap2 years ago Riya kashyap solution in javaimport java.util.*;import java.lang.*;import java.io.*;import java.time.LocalDate;class GFG {public static void main (String[] args) { //code Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t--!=0) { int day = sc.nextInt(); int month = sc.nextInt(); int year = sc.nextInt(); LocalDate days = LocalDate.of(year,month,day); String s = days.getDayOfWeek().toString(); char y[] = s.toCharArray(); for(int i=1;i<y.length;i++) {="" y[i]="(char)(y[i]+32);" }="" system.out.println(y);="" }="" }="" }=""> 0 Shashwat Sharma2 years ago Shashwat Sharma 0.01 sec...#include <iostream>using namespace std; int main() {//codeint t; cin>>t;while(t-->0){ int day,month,year; cin>>day>>month>>year; if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } int q = day; int m = month; int k = year % 100; int j = year / 100; int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j; h = h % 7; switch (h) { case 0 : cout<<"Saturday"<<endl; break;="" case="" 1="" :="" cout<<"sunday"<<endl;="" break;="" case="" 2="" :="" cout<<"monday"<<endl;="" break;="" case="" 3="" :="" cout<<"tuesday"<<endl;="" break;="" case="" 4="" :="" cout<<"wednesday"<<endl;="" break;="" case="" 5="" :="" cout<<"thursday"<<endl;="" break;="" case="" 6="" :="" cout<<"friday"<<endl;="" break;="" }="" }="" return="" 0;="" }=""> 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": 337, "s": 238, "text": "Write a program that calculates the day of the week for any particular date in the past or future." }, { "code": null, "e": 348, "s": 337, "text": "Example 1:" }, { "code": null, "e": 443, "s": 348, "text": "Input:\nd = 28, m = 12, y = 1995\nOutput:\nThursday\nExplanation:\n28 December 1995 was a Thursday." }, { "code": null, "e": 454, "s": 443, "text": "Example 2:" }, { "code": null, "e": 543, "s": 454, "text": "Input:\nd = 30, m = 8, y = 2010\nOutput:\nMonday\nExplanation:\n30 August 2010 was a Monday.\n" }, { "code": null, "e": 768, "s": 543, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function getDayOfWeek() which takes 3 Integers d, m and y denoting day, month and year as input and return a String denoting the answer." }, { "code": null, "e": 830, "s": 768, "text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 887, "s": 830, "text": "Constraints:\n1 <= d <= 31\n1 <= m <= 12\n1990 <= y <= 2100" }, { "code": null, "e": 889, "s": 887, "text": "0" }, { "code": null, "e": 914, "s": 889, "text": "aloksinghmp552 weeks ago" }, { "code": null, "e": 974, "s": 914, "text": "in this question it says 29/02/2100 ,it will be monday and " }, { "code": null, "e": 1028, "s": 974, "text": "01/03/2100 ,it will also monday. how can it possible." }, { "code": null, "e": 1059, "s": 1028, "text": "what is wrong in this code ???" }, { "code": null, "e": 1609, "s": 1059, "text": "string getDayOfWeek(int d, int m, int y) { string day[7]={ \"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\", \"Friday\",\"Saturday\"}; int i,j; int mon[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; long long sum=0; for(int i=1990;i<y;i++){ if(i%4==0){ sum=sum+366; } else{ sum=sum+365; } } for(j=1;j<m;j++){ if(j==2 && (y%4==0)){ sum=sum+1; } sum=sum+mon[j]; } sum=sum+d; return day[sum%7]; }" }, { "code": null, "e": 1612, "s": 1609, "text": "+1" }, { "code": null, "e": 1640, "s": 1612, "text": "rahulgupta067892 months ago" }, { "code": null, "e": 1949, "s": 1640, "text": "string getDayOfWeek(int d, int m, int y) { string days[]={\"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\"}; static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; y -= m < 3; int n=( y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7; return days[n]; }" }, { "code": null, "e": 1951, "s": 1949, "text": "0" }, { "code": null, "e": 1977, "s": 1951, "text": "ankitparashxr4 months ago" }, { "code": null, "e": 2386, "s": 1977, "text": "lass Solution { static String getDayOfWeek(int d, int m, int y) { String days[] ={\"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",}; //k is the day of the month. //m is the month number. //D is the last two digits of the year. //C is the first two digits of the year. if(m<3) { m+=12; y-=1; } int k = d;" }, { "code": null, "e": 2671, "s": 2386, "text": " int D = y%100; int C = y/100; int x =(C/4-2*C+D+D/4+13*(m+1)/5+k-1)%7; int val = x%7; if(val<0) { int num = val/7; num = num-1; int num2 = num*7; int num3 = val-num2; return days[num3]; } return days[x%7]; }};" }, { "code": null, "e": 2673, "s": 2671, "text": "0" }, { "code": null, "e": 2700, "s": 2673, "text": "bhavit mathur11 months ago" }, { "code": null, "e": 2714, "s": 2700, "text": "bhavit mathur" }, { "code": null, "e": 2757, "s": 2714, "text": "string getDayOfWeek(int d, int m, int y) {" }, { "code": null, "e": 2934, "s": 2757, "text": " static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; y -= m < 3; int x= ( y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;" }, { "code": null, "e": 3321, "s": 2934, "text": " if(x==0) { return \"Sunday\"; } if(x==1) { return \"Monday\"; } if(x==2) { return \"Tuesday\"; } if(x==3) { return \"Wednesday\"; } if(x==4) { return \"Thursday\"; } if(x==5) { return \"Friday\"; } if(x==6) { return \"Saturday\"; }" }, { "code": null, "e": 3327, "s": 3321, "text": " }" }, { "code": null, "e": 3329, "s": 3327, "text": "0" }, { "code": null, "e": 3352, "s": 3329, "text": "Raj Kumar11 months ago" }, { "code": null, "e": 3362, "s": 3352, "text": "Raj Kumar" }, { "code": null, "e": 3626, "s": 3362, "text": "TC : 0.42Map<integer ,=\"\" string=\"\"> map = new HashMap<>(); map.put(0,\"Sunday\"); map.put(1,\"Monday\"); map.put(2,\"Tuesday\"); map.put(3,\"Wednesday\"); map.put(4,\"Thursday\"); map.put(5,\"Friday\"); map.put(6,\"Saturday\");" }, { "code": null, "e": 3725, "s": 3626, "text": " //the Tomohiko Sakamoto Algorithm int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };" }, { "code": null, "e": 3814, "s": 3725, "text": " // if month is less than 3 reduce year by 1 if (m < 3) y -= 1;" }, { "code": null, "e": 3887, "s": 3814, "text": " int day = (y + (y/4) - (y/100) + (y/400) + (t[m - 1] + d)) % 7;" }, { "code": null, "e": 3931, "s": 3887, "text": " String dayOftheWeek= map.get(day);" }, { "code": null, "e": 3961, "s": 3931, "text": " return dayOftheWeek;" }, { "code": null, "e": 3963, "s": 3961, "text": "0" }, { "code": null, "e": 3986, "s": 3963, "text": "Bharat Gupta1 year ago" }, { "code": null, "e": 3999, "s": 3986, "text": "Bharat Gupta" }, { "code": null, "e": 4070, "s": 3999, "text": "Test cases don't match with constraints. Mine gave a WA for year 1435." }, { "code": null, "e": 4072, "s": 4070, "text": "0" }, { "code": null, "e": 4100, "s": 4072, "text": "Aman Kumar Mishra1 year ago" }, { "code": null, "e": 4118, "s": 4100, "text": "Aman Kumar Mishra" }, { "code": null, "e": 4240, "s": 4118, "text": "The test cases used are wrong. For 1 1 492 , it is showing correct answer is Tuesday but actually it should be Wednesday." }, { "code": null, "e": 4279, "s": 4240, "text": "Here is the correct code in java 1.8:-" }, { "code": null, "e": 5653, "s": 4279, "text": "static String getDayOfWeek(int d, int m, int y) { // code here Map<integer,integer> monthCode = new HashMap<integer,integer>(); monthCode.put(1,1); monthCode.put(2,4); monthCode.put(3,4); monthCode.put(4,0); monthCode.put(5,2); monthCode.put(6,5); monthCode.put(7,0); monthCode.put(8,3); monthCode.put(9,6); monthCode.put(10,1); monthCode.put(11,4); monthCode.put(12,6); Map<integer,string> dayCode = new HashMap<integer,string>(); dayCode.put(0,\"Saturday\"); dayCode.put(1,\"Sunday\"); dayCode.put(2,\"Monday\"); dayCode.put(3,\"Tuesday\"); dayCode.put(4,\"Wednesday\"); dayCode.put(5,\"Thursday\"); dayCode.put(6,\"Friday\"); int n = y; int count = 0; int sum = 0,r; while(count < 2) { r = n % 10; n = n / 10; sum = sum + (int)Math.pow(10,count)*r; count++; } int leap = sum / 4; sum = d + monthCode.get(m) + centuryCode(n) + sum + sum/4; int ans = sum % 7; return dayCode.get(ans); } static int centuryCode(int century) { int[] code = {6,4,2,0}; int x = 0, res = 0; for(int i = 0; i <= century; i++) { res = code[x%4]; x++; } return res; }" }, { "code": null, "e": 5655, "s": 5653, "text": "0" }, { "code": null, "e": 5677, "s": 5655, "text": "SUMITHRA S2 years ago" }, { "code": null, "e": 5688, "s": 5677, "text": "SUMITHRA S" }, { "code": null, "e": 5956, "s": 5688, "text": "import datetimedef dateday(l): week_days=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] day=datetime.date(l[2],l[1],l[0]).weekday() print(week_days[day])for i in range(int(input())): l=list(map(int,input().split())) dateday(l)" }, { "code": null, "e": 5958, "s": 5956, "text": "0" }, { "code": null, "e": 5982, "s": 5958, "text": "Riya kashyap2 years ago" }, { "code": null, "e": 5995, "s": 5982, "text": "Riya kashyap" }, { "code": null, "e": 6561, "s": 5995, "text": "solution in javaimport java.util.*;import java.lang.*;import java.io.*;import java.time.LocalDate;class GFG {public static void main (String[] args) { //code Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t--!=0) { int day = sc.nextInt(); int month = sc.nextInt(); int year = sc.nextInt(); LocalDate days = LocalDate.of(year,month,day); String s = days.getDayOfWeek().toString(); char y[] = s.toCharArray(); for(int i=1;i<y.length;i++) {=\"\" y[i]=\"(char)(y[i]+32);\" }=\"\" system.out.println(y);=\"\" }=\"\" }=\"\" }=\"\">" }, { "code": null, "e": 6563, "s": 6561, "text": "0" }, { "code": null, "e": 6590, "s": 6563, "text": "Shashwat Sharma2 years ago" }, { "code": null, "e": 6606, "s": 6590, "text": "Shashwat Sharma" }, { "code": null, "e": 6657, "s": 6606, "text": "0.01 sec...#include <iostream>using namespace std;" }, { "code": null, "e": 7545, "s": 6657, "text": "int main() {//codeint t; cin>>t;while(t-->0){ int day,month,year; cin>>day>>month>>year; if (month == 1) { month = 13; year--; } if (month == 2) { month = 14; year--; } int q = day; int m = month; int k = year % 100; int j = year / 100; int h = q + 13*(m + 1) / 5 + k + k / 4 + j / 4 + 5 * j; h = h % 7; switch (h) { case 0 : cout<<\"Saturday\"<<endl; break;=\"\" case=\"\" 1=\"\" :=\"\" cout<<\"sunday\"<<endl;=\"\" break;=\"\" case=\"\" 2=\"\" :=\"\" cout<<\"monday\"<<endl;=\"\" break;=\"\" case=\"\" 3=\"\" :=\"\" cout<<\"tuesday\"<<endl;=\"\" break;=\"\" case=\"\" 4=\"\" :=\"\" cout<<\"wednesday\"<<endl;=\"\" break;=\"\" case=\"\" 5=\"\" :=\"\" cout<<\"thursday\"<<endl;=\"\" break;=\"\" case=\"\" 6=\"\" :=\"\" cout<<\"friday\"<<endl;=\"\" break;=\"\" }=\"\" }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 7691, "s": 7545, "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": 7727, "s": 7691, "text": " Login to access your submissions. " }, { "code": null, "e": 7737, "s": 7727, "text": "\nProblem\n" }, { "code": null, "e": 7747, "s": 7737, "text": "\nContest\n" }, { "code": null, "e": 7810, "s": 7747, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7958, "s": 7810, "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": 8166, "s": 7958, "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": 8272, "s": 8166, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
SAS - Variables
In general variables in SAS represent the column names of the data tables it is analysing. But it can also be used for other purpose like using it as a counter in a programming loop. In the current chapter we will see the use of SAS variables as column names of SAS Data Set. SAS has three types of variables as below − This is the default variable type. These variables are used in mathematical expressions. INPUT VAR1 VAR2 VAR3; #Define numeric variables in the data set. In the above syntax, the INPUT statement shows the declaration of numeric variables. INPUT ID SALARY COMM_PERCENT; Character variables are used for values that are not used in Mathematical expressions. They are treated as text or strings. A variable becomes a character variable by adding a $ sing with a space at the end of the variable name. INPUT VAR1 $ VAR2 $ VAR3 $; #Define character variables in the data set. In the above syntax, the INPUT statement shows the declaration of character variables. INPUT FNAME $ LNAME $ ADDRESS $; These variables are treated only as dates and they need to be in valid date formats. A variable becomes a date variable by adding a date format with a space at the end of the variable name. INPUT VAR1 DATE11. VAR2 MMDDYY10. ; #Define date variables in the data set. In the above syntax, the INPUT statement shows the declaration of date variables. INPUT DOB DATE11. START_DATE MMDDYY10. ; The above variables are used in SAS program as shown in below examples. The below code shows how the three types of variables are declared and used in a SAS Program DATA TEMP; INPUT ID NAME $ SALARY DEPT $ DOJ DATE9. ; FORMAT DOJ DATE9. ; DATALINES; 1 Rick 623.3 IT 02APR2001 2 Dan 515.2 OPS 11JUL2012 3 Michelle 611 IT 21OCT2000 4 Ryan 729 HR 30JUL2012 5 Gary 843.25 FIN 06AUG2000 6 Tusar 578 IT 01MAR2009 7 Pranab 632.8 OPS 16AUG1998 8 Rasmi 722.5 FIN 13SEP2014 ; PROC PRINT DATA = TEMP; RUN; In the above example all the character variables are declared followed by a $ sign and the date variables are declared followed by a date format. The output of the above program is as below. The variables are very useful in analysing the data. They are used in expressions in which the statistical analysis is applied. Let’s see an example of analysing the built-in Data Set named CARS which is present under Libraries → My Libraries → SASHELP. Double click on it to explore the variables and their data types. Next we can produce a summary statistics of some of these variables using the Tasks options in SAS studio. Go to Tasks -> Statistics -> Summary Statistics and double click it to open the window as shown below. Choose Data Set SASHELP.CARS and select the three variables - MPG_CITY, MPG_Highway and Weight under the Analysis Variables. Hold the Ctrl key while selecting the variables by clicking. Click run. Click on the results tab after the above steps. It shows the statistical summary of the three variables chosen. The last column indicates number of observations (records) used in the analysis. 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 35 Lectures 2.5 hours Ermin Dedic 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 2859, "s": 2583, "text": "In general variables in SAS represent the column names of the data tables it is analysing. But it can also be used for other purpose like using it as a counter in a programming loop. In the current chapter we will see the use of SAS variables as column names of SAS Data Set." }, { "code": null, "e": 2903, "s": 2859, "text": "SAS has three types of variables as below −" }, { "code": null, "e": 2993, "s": 2903, "text": "This is the default variable type. These variables are used in mathematical expressions." }, { "code": null, "e": 3061, "s": 2993, "text": "INPUT VAR1 VAR2 VAR3; \t\t#Define numeric variables in the data set.\n" }, { "code": null, "e": 3146, "s": 3061, "text": "In the above syntax, the INPUT statement shows the declaration of numeric variables." }, { "code": null, "e": 3177, "s": 3146, "text": "INPUT ID SALARY COMM_PERCENT;\n" }, { "code": null, "e": 3407, "s": 3177, "text": " Character variables are used for values that are not used in Mathematical expressions. They are treated as text or strings. A variable becomes a character variable by adding a $ sing with a space at the end of the variable name." }, { "code": null, "e": 3482, "s": 3407, "text": "INPUT VAR1 $ VAR2 $ VAR3 $; \t#Define character variables in the data set.\n" }, { "code": null, "e": 3569, "s": 3482, "text": "In the above syntax, the INPUT statement shows the declaration of character variables." }, { "code": null, "e": 3603, "s": 3569, "text": "INPUT FNAME $ LNAME $ ADDRESS $;\n" }, { "code": null, "e": 3793, "s": 3603, "text": "These variables are treated only as dates and they need to be in valid date formats. A variable becomes a date variable by adding a date format with a space at the end of the variable name." }, { "code": null, "e": 3870, "s": 3793, "text": "INPUT VAR1 DATE11. VAR2 MMDDYY10. ; #Define date variables in the data set.\n" }, { "code": null, "e": 3952, "s": 3870, "text": "In the above syntax, the INPUT statement shows the declaration of date variables." }, { "code": null, "e": 3994, "s": 3952, "text": "INPUT DOB DATE11. START_DATE MMDDYY10. ;\n" }, { "code": null, "e": 4066, "s": 3994, "text": "The above variables are used in SAS program as shown in below examples." }, { "code": null, "e": 4159, "s": 4066, "text": "The below code shows how the three types of variables are declared and used in a SAS Program" }, { "code": null, "e": 4490, "s": 4159, "text": "DATA TEMP;\nINPUT ID NAME $ SALARY DEPT $ DOJ DATE9. ;\nFORMAT DOJ DATE9. ;\nDATALINES;\n1 Rick 623.3 IT 02APR2001\n2 Dan 515.2 OPS 11JUL2012\n3 Michelle 611 IT 21OCT2000\n4 Ryan 729 HR 30JUL2012\n5 Gary 843.25 FIN 06AUG2000\n6 Tusar 578 IT 01MAR2009\n7 Pranab 632.8 OPS 16AUG1998\n8 Rasmi 722.5 FIN 13SEP2014\n;\nPROC PRINT DATA = TEMP;\nRUN;\n" }, { "code": null, "e": 4681, "s": 4490, "text": "In the above example all the character variables are declared followed by a $ sign and the date variables are declared followed by a date format. The output of the above program is as below." }, { "code": null, "e": 5001, "s": 4681, "text": "The variables are very useful in analysing the data. They are used in expressions in which the statistical analysis is applied. Let’s see an example of analysing the built-in Data Set named CARS which is present under Libraries → My Libraries → SASHELP. Double click on it to explore the variables and their data types." }, { "code": null, "e": 5408, "s": 5001, "text": "Next we can produce a summary statistics of some of these variables using the Tasks options in SAS studio. Go to Tasks -> Statistics -> Summary Statistics and double click it to open the window as shown below. Choose Data Set SASHELP.CARS and select the three variables - MPG_CITY, MPG_Highway and Weight under the Analysis Variables. Hold the Ctrl key while selecting the variables by clicking. Click run." }, { "code": null, "e": 5601, "s": 5408, "text": "Click on the results tab after the above steps. It shows the statistical summary of the three variables chosen. The last column indicates number of observations (records) used in the analysis." }, { "code": null, "e": 5636, "s": 5601, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5653, "s": 5636, "text": " Code And Create" }, { "code": null, "e": 5688, "s": 5653, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 5701, "s": 5688, "text": " Juan Galvan" }, { "code": null, "e": 5738, "s": 5701, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 5758, "s": 5738, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 5793, "s": 5758, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5806, "s": 5793, "text": " Ermin Dedic" }, { "code": null, "e": 5843, "s": 5806, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 5859, "s": 5843, "text": " Muslim Helalee" }, { "code": null, "e": 5866, "s": 5859, "text": " Print" }, { "code": null, "e": 5877, "s": 5866, "text": " Add Notes" } ]
Conversion Functions in R Programming - GeeksforGeeks
01 Jun, 2020 Sometimes to analyze data using R, we need to convert data into another data type. As we know R has the following data types Numeric, Integer, Logical, Character, etc. similarly R has various conversion functions that are used to convert the data type. In R, Conversion Function are of two types: Conversion Functions for Data Types Conversion Functions for Data Structures There are various conversion functions available for Data Types. These are: as.numeric()Decimal value known numeric values in R. It is the default data type for real numbers in R. In R as.numeric() converts any values into numeric values.Syntax:// Conversion into numeric data type as.numeric(x) Example:# A simple R program to convert # character data type into numeric data typex<-c('1', '2', '3') # Print xprint(x) # Print the type of xprint(typeof(x)) # Conversion into numeric data typey<-as.numeric(x) # print the type of yprint(typeof(y))Output:[1] "1" "2" "3" [1] "character" [1] "double" Decimal value known numeric values in R. It is the default data type for real numbers in R. In R as.numeric() converts any values into numeric values.Syntax: // Conversion into numeric data type as.numeric(x) Example: # A simple R program to convert # character data type into numeric data typex<-c('1', '2', '3') # Print xprint(x) # Print the type of xprint(typeof(x)) # Conversion into numeric data typey<-as.numeric(x) # print the type of yprint(typeof(y)) Output: [1] "1" "2" "3" [1] "character" [1] "double" as.integer()In R, Integer data type is a collection of all integers. In order to create an integer variable in R and convert any data type in to Integer we use as.integer() function.Syntax:// Conversion of any data type into Integer data type as.integer(x) Example:# A simple R program to convert# numeric data type into integer data typex<-c(1.3, 5.6, 55.6) # Print xprint(x) # Print type of xprint(typeof(x)) # Conversion into integer data typey<-as.integer(x) # Print yprint(y) # Print type of yprint(typeof(y))Output:[1] 1.3 5.6 55.6 [1] "double" [1] 1 5 55 [1] "integer" // Conversion of any data type into Integer data type as.integer(x) Example: # A simple R program to convert# numeric data type into integer data typex<-c(1.3, 5.6, 55.6) # Print xprint(x) # Print type of xprint(typeof(x)) # Conversion into integer data typey<-as.integer(x) # Print yprint(y) # Print type of yprint(typeof(y)) Output: [1] 1.3 5.6 55.6 [1] "double" [1] 1 5 55 [1] "integer" as.character()In R, character data is used to store character value and string. To create an character variable in R, we invoke the as.character() function and also if we want to convert any data type in to character we use as.character() function.Syntax:// Conversion of any data type into character data type as.character(x) Example:x<-c(1.3, 5.6, 55.6) # Print xprint(x) # Print type of xprint(typeof(x)) # Conversion into character data typey<-as.character(x) # Print yprint(y) # Print type of yprint(typeof(y))Output:[1] 1.3 5.6 55.6 [1] "double" [1] "1.3" "5.6" "55.6" [1] "character" // Conversion of any data type into character data type as.character(x) Example: x<-c(1.3, 5.6, 55.6) # Print xprint(x) # Print type of xprint(typeof(x)) # Conversion into character data typey<-as.character(x) # Print yprint(y) # Print type of yprint(typeof(y)) Output: [1] 1.3 5.6 55.6 [1] "double" [1] "1.3" "5.6" "55.6" [1] "character" as.logical()Logical value is created to compare variables which return either true or false.To compare variables and to convert any value in to true or false, R uses as.logical() function.Syntax:// Conversion of any data type into logical data type as.logical(x) Example:x = 3y = 8 # Conversion in to logical valueresult<-as.logical(x>y) # Print resultprint(result)Output:[1] FALSE // Conversion of any data type into logical data type as.logical(x) Example: x = 3y = 8 # Conversion in to logical valueresult<-as.logical(x>y) # Print resultprint(result) Output: [1] FALSE as.date()In R as.date() function is used to convert string into date format.Syntax:// Print string into date format as.date(variable, "%m/%d/%y") Example:dates <- c("02/27/92", "02/27/92", "01/14/92", "02/28/92", "02/01/92") # Conversion into date formatresult<-as.Date(dates, "%m/%d/%y") # Print resultprint(result)Output:[1] "1992-02-27" "1992-02-27" "1992-01-14" "1992-02-28" "1992-02-01" Syntax: // Print string into date format as.date(variable, "%m/%d/%y") Example: dates <- c("02/27/92", "02/27/92", "01/14/92", "02/28/92", "02/01/92") # Conversion into date formatresult<-as.Date(dates, "%m/%d/%y") # Print resultprint(result) Output: [1] "1992-02-27" "1992-02-27" "1992-01-14" "1992-02-28" "1992-02-01" There are various conversion functions available for Data Structure. These are: as.data.frame()Data Frame is used to store data tables. Which is list of vectors of equal length. In R, sometimes to analyse data we need to convert list of vector into data.frame. So for this R uses as.data.frame() function to convert list of vector into data frame.Syntax:// Conversion of any data structure into data frame as.data.frame(x) Example:x<- list( c('a', 'b', 'c'),c('e', 'f', 'g'), c('h', 'i', 'j')) # Print xprint(x) # Conversion in to data framey<-as.data.frame(x) # Print yprint(y)Output:[[1]] [1] "a" "b" "c" [[2]] [1] "e" "f" "g" [[3]] [1] "h" "i" "j" c..a....b....c.. c..e....f....g.. c..h....i....j.. 1 a e h 2 b f i 3 c g j // Conversion of any data structure into data frame as.data.frame(x) Example: x<- list( c('a', 'b', 'c'),c('e', 'f', 'g'), c('h', 'i', 'j')) # Print xprint(x) # Conversion in to data framey<-as.data.frame(x) # Print yprint(y) Output: [[1]] [1] "a" "b" "c" [[2]] [1] "e" "f" "g" [[3]] [1] "h" "i" "j" c..a....b....c.. c..e....f....g.. c..h....i....j.. 1 a e h 2 b f i 3 c g j as.vector()R has a function as.vector() which is used to convert a distributed matrix into a non-distributed vector. Vector generates a vector of the given length and mode.Syntax:// Conversion of any data structure into vector as.vector(x) Example:x<-c(a=1, b=2) # Print xprint(x) # Conversion into vectory<-as.vector(x) # Print yprint(y)Output:a b 1 2 [1] 1 2 // Conversion of any data structure into vector as.vector(x) Example: x<-c(a=1, b=2) # Print xprint(x) # Conversion into vectory<-as.vector(x) # Print yprint(y) Output: a b 1 2 [1] 1 2 as.matrix()In R, there is a function as.matrix() which is used to convert a data.table into a matrix, optionally using one of the columns in the data.table as the matrix row names.Syntax:// Conversion into matrix as.matrix(x) Example:# Importing librarylibrary(data.table)x <- data.table(A = letters[1:5], X = 1:5, Y = 6:10) # Print xprint(x) # Conversion into matrixz<-as.matrix(x) # Print zprint(z)Output: A X Y 1: a 1 6 2: b 2 7 3: c 3 8 4: d 4 9 5: e 5 10 A X Y [1,] "a" "1" " 6" [2,] "b" "2" " 7" [3,] "c" "3" " 8" [4,] "d" "4" " 9" [5,] "e" "5" "10" // Conversion into matrix as.matrix(x) Example: # Importing librarylibrary(data.table)x <- data.table(A = letters[1:5], X = 1:5, Y = 6:10) # Print xprint(x) # Conversion into matrixz<-as.matrix(x) # Print zprint(z) Output: A X Y 1: a 1 6 2: b 2 7 3: c 3 8 4: d 4 9 5: e 5 10 A X Y [1,] "a" "1" " 6" [2,] "b" "2" " 7" [3,] "c" "3" " 8" [4,] "d" "4" " 9" [5,] "e" "5" "10" R-dataStructures R-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Adding elements in a vector in R programming - append() method Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming How to Change Axis Scales in R Plots? Group by function in R using Dplyr
[ { "code": null, "e": 29044, "s": 29016, "text": "\n01 Jun, 2020" }, { "code": null, "e": 29297, "s": 29044, "text": "Sometimes to analyze data using R, we need to convert data into another data type. As we know R has the following data types Numeric, Integer, Logical, Character, etc. similarly R has various conversion functions that are used to convert the data type." }, { "code": null, "e": 29341, "s": 29297, "text": "In R, Conversion Function are of two types:" }, { "code": null, "e": 29377, "s": 29341, "text": "Conversion Functions for Data Types" }, { "code": null, "e": 29418, "s": 29377, "text": "Conversion Functions for Data Structures" }, { "code": null, "e": 29494, "s": 29418, "text": "There are various conversion functions available for Data Types. These are:" }, { "code": null, "e": 30020, "s": 29494, "text": "as.numeric()Decimal value known numeric values in R. It is the default data type for real numbers in R. In R as.numeric() converts any values into numeric values.Syntax:// Conversion into numeric data type\nas.numeric(x)\nExample:# A simple R program to convert # character data type into numeric data typex<-c('1', '2', '3') # Print xprint(x) # Print the type of xprint(typeof(x)) # Conversion into numeric data typey<-as.numeric(x) # print the type of yprint(typeof(y))Output:[1] \"1\" \"2\" \"3\"\n[1] \"character\"\n[1] \"double\"\n" }, { "code": null, "e": 30178, "s": 30020, "text": "Decimal value known numeric values in R. It is the default data type for real numbers in R. In R as.numeric() converts any values into numeric values.Syntax:" }, { "code": null, "e": 30230, "s": 30178, "text": "// Conversion into numeric data type\nas.numeric(x)\n" }, { "code": null, "e": 30239, "s": 30230, "text": "Example:" }, { "code": "# A simple R program to convert # character data type into numeric data typex<-c('1', '2', '3') # Print xprint(x) # Print the type of xprint(typeof(x)) # Conversion into numeric data typey<-as.numeric(x) # print the type of yprint(typeof(y))", "e": 30485, "s": 30239, "text": null }, { "code": null, "e": 30493, "s": 30485, "text": "Output:" }, { "code": null, "e": 30539, "s": 30493, "text": "[1] \"1\" \"2\" \"3\"\n[1] \"character\"\n[1] \"double\"\n" }, { "code": null, "e": 31125, "s": 30539, "text": "as.integer()In R, Integer data type is a collection of all integers. In order to create an integer variable in R and convert any data type in to Integer we use as.integer() function.Syntax:// Conversion of any data type into Integer data type\nas.integer(x)\nExample:# A simple R program to convert# numeric data type into integer data typex<-c(1.3, 5.6, 55.6) # Print xprint(x) # Print type of xprint(typeof(x)) # Conversion into integer data typey<-as.integer(x) # Print yprint(y) # Print type of yprint(typeof(y))Output:[1] 1.3 5.6 55.6\n[1] \"double\"\n[1] 1 5 55\n[1] \"integer\"\n" }, { "code": null, "e": 31194, "s": 31125, "text": "// Conversion of any data type into Integer data type\nas.integer(x)\n" }, { "code": null, "e": 31203, "s": 31194, "text": "Example:" }, { "code": "# A simple R program to convert# numeric data type into integer data typex<-c(1.3, 5.6, 55.6) # Print xprint(x) # Print type of xprint(typeof(x)) # Conversion into integer data typey<-as.integer(x) # Print yprint(y) # Print type of yprint(typeof(y))", "e": 31458, "s": 31203, "text": null }, { "code": null, "e": 31466, "s": 31458, "text": "Output:" }, { "code": null, "e": 31526, "s": 31466, "text": "[1] 1.3 5.6 55.6\n[1] \"double\"\n[1] 1 5 55\n[1] \"integer\"\n" }, { "code": null, "e": 32127, "s": 31526, "text": "as.character()In R, character data is used to store character value and string. To create an character variable in R, we invoke the as.character() function and also if we want to convert any data type in to character we use as.character() function.Syntax:// Conversion of any data type into character data type\nas.character(x)\nExample:x<-c(1.3, 5.6, 55.6) # Print xprint(x) # Print type of xprint(typeof(x)) # Conversion into character data typey<-as.character(x) # Print yprint(y) # Print type of yprint(typeof(y))Output:[1] 1.3 5.6 55.6\n[1] \"double\"\n[1] \"1.3\" \"5.6\" \"55.6\"\n[1] \"character\"\n" }, { "code": null, "e": 32200, "s": 32127, "text": "// Conversion of any data type into character data type\nas.character(x)\n" }, { "code": null, "e": 32209, "s": 32200, "text": "Example:" }, { "code": "x<-c(1.3, 5.6, 55.6) # Print xprint(x) # Print type of xprint(typeof(x)) # Conversion into character data typey<-as.character(x) # Print yprint(y) # Print type of yprint(typeof(y))", "e": 32395, "s": 32209, "text": null }, { "code": null, "e": 32403, "s": 32395, "text": "Output:" }, { "code": null, "e": 32477, "s": 32403, "text": "[1] 1.3 5.6 55.6\n[1] \"double\"\n[1] \"1.3\" \"5.6\" \"55.6\"\n[1] \"character\"\n" }, { "code": null, "e": 32862, "s": 32477, "text": "as.logical()Logical value is created to compare variables which return either true or false.To compare variables and to convert any value in to true or false, R uses as.logical() function.Syntax:// Conversion of any data type into logical data type\nas.logical(x)\nExample:x = 3y = 8 # Conversion in to logical valueresult<-as.logical(x>y) # Print resultprint(result)Output:[1] FALSE\n" }, { "code": null, "e": 32931, "s": 32862, "text": "// Conversion of any data type into logical data type\nas.logical(x)\n" }, { "code": null, "e": 32940, "s": 32931, "text": "Example:" }, { "code": "x = 3y = 8 # Conversion in to logical valueresult<-as.logical(x>y) # Print resultprint(result)", "e": 33037, "s": 32940, "text": null }, { "code": null, "e": 33045, "s": 33037, "text": "Output:" }, { "code": null, "e": 33056, "s": 33045, "text": "[1] FALSE\n" }, { "code": null, "e": 33473, "s": 33056, "text": "as.date()In R as.date() function is used to convert string into date format.Syntax:// Print string into date format\nas.date(variable, \"%m/%d/%y\")\nExample:dates <- c(\"02/27/92\", \"02/27/92\", \"01/14/92\", \"02/28/92\", \"02/01/92\") # Conversion into date formatresult<-as.Date(dates, \"%m/%d/%y\") # Print resultprint(result)Output:[1] \"1992-02-27\" \"1992-02-27\" \"1992-01-14\" \"1992-02-28\" \"1992-02-01\"\n" }, { "code": null, "e": 33481, "s": 33473, "text": "Syntax:" }, { "code": null, "e": 33545, "s": 33481, "text": "// Print string into date format\nas.date(variable, \"%m/%d/%y\")\n" }, { "code": null, "e": 33554, "s": 33545, "text": "Example:" }, { "code": "dates <- c(\"02/27/92\", \"02/27/92\", \"01/14/92\", \"02/28/92\", \"02/01/92\") # Conversion into date formatresult<-as.Date(dates, \"%m/%d/%y\") # Print resultprint(result)", "e": 33741, "s": 33554, "text": null }, { "code": null, "e": 33749, "s": 33741, "text": "Output:" }, { "code": null, "e": 33819, "s": 33749, "text": "[1] \"1992-02-27\" \"1992-02-27\" \"1992-01-14\" \"1992-02-28\" \"1992-02-01\"\n" }, { "code": null, "e": 33899, "s": 33819, "text": "There are various conversion functions available for Data Structure. These are:" }, { "code": null, "e": 34689, "s": 33899, "text": "as.data.frame()Data Frame is used to store data tables. Which is list of vectors of equal length. In R, sometimes to analyse data we need to convert list of vector into data.frame. So for this R uses as.data.frame() function to convert list of vector into data frame.Syntax:// Conversion of any data structure into data frame\nas.data.frame(x)\nExample:x<- list( c('a', 'b', 'c'),c('e', 'f', 'g'), c('h', 'i', 'j')) # Print xprint(x) # Conversion in to data framey<-as.data.frame(x) # Print yprint(y)Output:[[1]]\n[1] \"a\" \"b\" \"c\"\n\n[[2]]\n[1] \"e\" \"f\" \"g\"\n\n[[3]]\n[1] \"h\" \"i\" \"j\"\n\n c..a....b....c.. c..e....f....g.. c..h....i....j..\n1 a e h\n2 b f i\n3 c g j\n" }, { "code": null, "e": 34759, "s": 34689, "text": "// Conversion of any data structure into data frame\nas.data.frame(x)\n" }, { "code": null, "e": 34768, "s": 34759, "text": "Example:" }, { "code": "x<- list( c('a', 'b', 'c'),c('e', 'f', 'g'), c('h', 'i', 'j')) # Print xprint(x) # Conversion in to data framey<-as.data.frame(x) # Print yprint(y)", "e": 34919, "s": 34768, "text": null }, { "code": null, "e": 34927, "s": 34919, "text": "Output:" }, { "code": null, "e": 35209, "s": 34927, "text": "[[1]]\n[1] \"a\" \"b\" \"c\"\n\n[[2]]\n[1] \"e\" \"f\" \"g\"\n\n[[3]]\n[1] \"h\" \"i\" \"j\"\n\n c..a....b....c.. c..e....f....g.. c..h....i....j..\n1 a e h\n2 b f i\n3 c g j\n" }, { "code": null, "e": 35576, "s": 35209, "text": "as.vector()R has a function as.vector() which is used to convert a distributed matrix into a non-distributed vector. Vector generates a vector of the given length and mode.Syntax:// Conversion of any data structure into vector\nas.vector(x)\nExample:x<-c(a=1, b=2) # Print xprint(x) # Conversion into vectory<-as.vector(x) # Print yprint(y)Output:a b \n1 2 \n[1] 1 2\n" }, { "code": null, "e": 35638, "s": 35576, "text": "// Conversion of any data structure into vector\nas.vector(x)\n" }, { "code": null, "e": 35647, "s": 35638, "text": "Example:" }, { "code": "x<-c(a=1, b=2) # Print xprint(x) # Conversion into vectory<-as.vector(x) # Print yprint(y)", "e": 35741, "s": 35647, "text": null }, { "code": null, "e": 35749, "s": 35741, "text": "Output:" }, { "code": null, "e": 35768, "s": 35749, "text": "a b \n1 2 \n[1] 1 2\n" }, { "code": null, "e": 36347, "s": 35768, "text": "as.matrix()In R, there is a function as.matrix() which is used to convert a data.table into a matrix, optionally using one of the columns in the data.table as the matrix row names.Syntax:// Conversion into matrix\nas.matrix(x)\nExample:# Importing librarylibrary(data.table)x <- data.table(A = letters[1:5], X = 1:5, Y = 6:10) # Print xprint(x) # Conversion into matrixz<-as.matrix(x) # Print zprint(z)Output: A X Y\n1: a 1 6\n2: b 2 7\n3: c 3 8\n4: d 4 9\n5: e 5 10\n A X Y \n[1,] \"a\" \"1\" \" 6\"\n[2,] \"b\" \"2\" \" 7\"\n[3,] \"c\" \"3\" \" 8\"\n[4,] \"d\" \"4\" \" 9\"\n[5,] \"e\" \"5\" \"10\"\n" }, { "code": null, "e": 36387, "s": 36347, "text": "// Conversion into matrix\nas.matrix(x)\n" }, { "code": null, "e": 36396, "s": 36387, "text": "Example:" }, { "code": "# Importing librarylibrary(data.table)x <- data.table(A = letters[1:5], X = 1:5, Y = 6:10) # Print xprint(x) # Conversion into matrixz<-as.matrix(x) # Print zprint(z)", "e": 36566, "s": 36396, "text": null }, { "code": null, "e": 36574, "s": 36566, "text": "Output:" }, { "code": null, "e": 36743, "s": 36574, "text": " A X Y\n1: a 1 6\n2: b 2 7\n3: c 3 8\n4: d 4 9\n5: e 5 10\n A X Y \n[1,] \"a\" \"1\" \" 6\"\n[2,] \"b\" \"2\" \" 7\"\n[3,] \"c\" \"3\" \" 8\"\n[4,] \"d\" \"4\" \" 9\"\n[5,] \"e\" \"5\" \"10\"\n" }, { "code": null, "e": 36760, "s": 36743, "text": "R-dataStructures" }, { "code": null, "e": 36772, "s": 36760, "text": "R-Functions" }, { "code": null, "e": 36783, "s": 36772, "text": "R Language" }, { "code": null, "e": 36881, "s": 36783, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36926, "s": 36881, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 36984, "s": 36926, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 37036, "s": 36984, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 37099, "s": 37036, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 37131, "s": 37099, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 37183, "s": 37131, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 37227, "s": 37183, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 37292, "s": 37227, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 37330, "s": 37292, "text": "How to Change Axis Scales in R Plots?" } ]
Queue Reversal | Practice | GeeksforGeeks
Given a Queue Q containing N elements. The task is to reverse the Queue. Your task is to complete the function rev(), that reverses the N elements of the queue. Example 1: Input: 6 4 3 1 10 2 6 Output: 6 2 10 1 3 4 Explanation: After reversing the given elements of the queue , the resultant queue will be 6 2 10 1 3 4. Example 2: Input: 4 4 3 2 1 Output: 1 2 3 4 Explanation: After reversing the given elements of the queue , the resultant queue will be 1 2 3 4. Your Task: You only need to complete the function rev that takes a queue as parameter and returns the reversed queue. The printing is done automatically by the driver code. Expected Time Complexity : O(n) Expected Auxilliary Space : O(n) Constraints: 1 ≤ N ≤ 105 1 ≤ elements of Queue ≤ 105 0 hrithikjain98893 days ago Total Time Taken: 0.17/1.31 queue<int> rev(queue<int> q){ // add code here. stack<int> s; while(q.size()!=0) { s.push(q.front()); q.pop(); } while(s.size()!=0) { q.push(s.top()); s.pop(); } return q;} 0 gurankitbehal781145 days ago queue<int> rev(queue<int> q){queue<int>t;int s=q.size();vector<int>vect;int x=0; for(int i=0;i<=s;i++){ x=q.front(); vect.push_back(x); q.pop(); } int i=s-1; while(i!=-1){ t.push(vect[i]); i--; } return t;} 0 saksham_bhati5 days ago void solve(queue<int>& q) { // base case if(q.empty()) return; int ele = q.front(); q.pop(); solve(q); q.push(ele); } queue<int> rev(queue<int> q) { solve(q); return q; } 0 lovedeep79051 week ago //Reverse queue using recursion class GfG{ //Function to reverse the queue.static int size=0; public Queue<Integer> rev(Queue<Integer> q){ size=q.size(); if(q.size()==0){ return q; } int temp=q.remove(); rev(q); insert(q,temp); return q; } static void insert(Queue<Integer> q,int temp){ if(q.isEmpty() || q.size()!=size){ q.add(temp); return; } }} -1 harshscode2 weeks ago stack<int> s; while(!q.empty()) { s.push(q.front()); q.pop(); } while(!s.empty()) { q.push(s.top()); s.pop(); } return q; 0 sakshisuman982 weeks ago queue<int> rev(queue<int> q){ stack<int>s; while(!q.empty()) { int x=q.front(); q.pop(); s.push(x); } while(!s.empty()) { int y=s.top(); s.pop(); q.push(y); } return q; } 0 f2020170712 weeks ago struct Queue* rev(struct Queue* Q){ if(Q->size == 1) return Q; int last = front(Q); dequeue(Q); struct Queue* rev_upto_last = rev(Q); enqueue(rev_upto_last,last); return rev_upto_last; //code here} 0 amank07533 weeks ago Why is this not working ?? queue<int> rev(queue<int> q){ // add code here. if(q.size()==1) return q; int t=q.front(); q.pop(); rev(q); q.push(t); return q;} 0 harshilrpanchal19981 month ago public Queue<Integer> rev(Queue<Integer> q){ //add code here. Stack<Integer> stack = new Stack<>(); while(!q.isEmpty()){ stack.add(q.peek()); q.remove(); } while(!stack.isEmpty()){ q.add(stack.peek()); stack.pop(); } return q; } 0 monish00011 month ago queue<int> rev(queue<int> q) { // add code here. //code here queue<int> ans; stack<int> st; while(!q.empty()){ st.push(q.front()); q.pop(); } while(!st.empty()){ ans.push(st.top()); st.pop(); } return ans; } 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": 399, "s": 238, "text": "Given a Queue Q containing N elements. The task is to reverse the Queue. Your task is to complete the function rev(), that reverses the N elements of the queue." }, { "code": null, "e": 410, "s": 399, "text": "Example 1:" }, { "code": null, "e": 563, "s": 410, "text": "Input:\n6\n4 3 1 10 2 6\n\nOutput: \n6 2 10 1 3 4\n\nExplanation: \nAfter reversing the given\nelements of the queue , the resultant\nqueue will be 6 2 10 1 3 4.\n" }, { "code": null, "e": 574, "s": 563, "text": "Example 2:" }, { "code": null, "e": 712, "s": 574, "text": "Input:\n4\n4 3 2 1 \n\nOutput: \n1 2 3 4\n\nExplanation: \nAfter reversing the given\nelements of the queue , the resultant\nqueue will be 1 2 3 4." }, { "code": null, "e": 886, "s": 712, "text": "Your Task:\n You only need to complete the function rev that takes a queue as parameter and returns the reversed queue. The printing is done automatically by the driver code." }, { "code": null, "e": 951, "s": 886, "text": "Expected Time Complexity : O(n)\nExpected Auxilliary Space : O(n)" }, { "code": null, "e": 1004, "s": 951, "text": "Constraints:\n1 ≤ N ≤ 105\n1 ≤ elements of Queue ≤ 105" }, { "code": null, "e": 1006, "s": 1004, "text": "0" }, { "code": null, "e": 1032, "s": 1006, "text": "hrithikjain98893 days ago" }, { "code": null, "e": 1050, "s": 1032, "text": "Total Time Taken:" }, { "code": null, "e": 1060, "s": 1050, "text": "0.17/1.31" }, { "code": null, "e": 1275, "s": 1060, "text": "queue<int> rev(queue<int> q){ // add code here. stack<int> s; while(q.size()!=0) { s.push(q.front()); q.pop(); } while(s.size()!=0) { q.push(s.top()); s.pop(); } return q;}" }, { "code": null, "e": 1277, "s": 1275, "text": "0" }, { "code": null, "e": 1306, "s": 1277, "text": "gurankitbehal781145 days ago" }, { "code": null, "e": 1546, "s": 1306, "text": "queue<int> rev(queue<int> q){queue<int>t;int s=q.size();vector<int>vect;int x=0; for(int i=0;i<=s;i++){ x=q.front(); vect.push_back(x); q.pop(); } int i=s-1; while(i!=-1){ t.push(vect[i]); i--; } return t;}" }, { "code": null, "e": 1548, "s": 1546, "text": "0" }, { "code": null, "e": 1572, "s": 1548, "text": "saksham_bhati5 days ago" }, { "code": null, "e": 1812, "s": 1572, "text": "void solve(queue<int>& q)\n{\n // base case\n if(q.empty())\n return;\n \n int ele = q.front();\n q.pop();\n \n solve(q);\n \n q.push(ele);\n}\n\nqueue<int> rev(queue<int> q)\n{\n \n solve(q);\n \n return q;\n}" }, { "code": null, "e": 1814, "s": 1812, "text": "0" }, { "code": null, "e": 1837, "s": 1814, "text": "lovedeep79051 week ago" }, { "code": null, "e": 1869, "s": 1837, "text": "//Reverse queue using recursion" }, { "code": null, "e": 2311, "s": 1871, "text": "class GfG{ //Function to reverse the queue.static int size=0; public Queue<Integer> rev(Queue<Integer> q){ size=q.size(); if(q.size()==0){ return q; } int temp=q.remove(); rev(q); insert(q,temp); return q; } static void insert(Queue<Integer> q,int temp){ if(q.isEmpty() || q.size()!=size){ q.add(temp); return; } }}" }, { "code": null, "e": 2316, "s": 2313, "text": "-1" }, { "code": null, "e": 2338, "s": 2316, "text": "harshscode2 weeks ago" }, { "code": null, "e": 2501, "s": 2338, "text": " stack<int> s; while(!q.empty()) { s.push(q.front()); q.pop(); } while(!s.empty()) { q.push(s.top()); s.pop(); } return q;" }, { "code": null, "e": 2503, "s": 2501, "text": "0" }, { "code": null, "e": 2528, "s": 2503, "text": "sakshisuman982 weeks ago" }, { "code": null, "e": 2760, "s": 2528, "text": "queue<int> rev(queue<int> q){ stack<int>s; while(!q.empty()) { int x=q.front(); q.pop(); s.push(x); } while(!s.empty()) { int y=s.top(); s.pop(); q.push(y); } return q; }" }, { "code": null, "e": 2764, "s": 2762, "text": "0" }, { "code": null, "e": 2786, "s": 2764, "text": "f2020170712 weeks ago" }, { "code": null, "e": 3008, "s": 2786, "text": "struct Queue* rev(struct Queue* Q){ if(Q->size == 1) return Q; int last = front(Q); dequeue(Q); struct Queue* rev_upto_last = rev(Q); enqueue(rev_upto_last,last); return rev_upto_last; //code here}" }, { "code": null, "e": 3010, "s": 3008, "text": "0" }, { "code": null, "e": 3031, "s": 3010, "text": "amank07533 weeks ago" }, { "code": null, "e": 3058, "s": 3031, "text": "Why is this not working ??" }, { "code": null, "e": 3213, "s": 3058, "text": "queue<int> rev(queue<int> q){ // add code here. if(q.size()==1) return q; int t=q.front(); q.pop(); rev(q); q.push(t); return q;}" }, { "code": null, "e": 3215, "s": 3213, "text": "0" }, { "code": null, "e": 3246, "s": 3215, "text": "harshilrpanchal19981 month ago" }, { "code": null, "e": 3581, "s": 3246, "text": " public Queue<Integer> rev(Queue<Integer> q){ //add code here. Stack<Integer> stack = new Stack<>(); while(!q.isEmpty()){ stack.add(q.peek()); q.remove(); } while(!stack.isEmpty()){ q.add(stack.peek()); stack.pop(); } return q; }" }, { "code": null, "e": 3583, "s": 3581, "text": "0" }, { "code": null, "e": 3605, "s": 3583, "text": "monish00011 month ago" }, { "code": null, "e": 3882, "s": 3605, "text": "queue<int> rev(queue<int> q)\n{\n // add code here.\n //code here\n queue<int> ans;\n stack<int> st;\n while(!q.empty()){\n st.push(q.front());\n q.pop();\n }\n while(!st.empty()){\n ans.push(st.top());\n st.pop();\n }\n return ans;\n}" }, { "code": null, "e": 4028, "s": 3882, "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": 4064, "s": 4028, "text": " Login to access your submissions. " }, { "code": null, "e": 4074, "s": 4064, "text": "\nProblem\n" }, { "code": null, "e": 4084, "s": 4074, "text": "\nContest\n" }, { "code": null, "e": 4147, "s": 4084, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4295, "s": 4147, "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": 4503, "s": 4295, "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": 4609, "s": 4503, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Write a function that counts the number of times a given int occurs in a Linked List - GeeksforGeeks
05 Apr, 2022 Given a singly linked list and a key, count the number of occurrences of the given key in the linked list. For example, if the given linked list is 1->2->1->2->1->3->1 and the given key is 1, then the output should be 4. Method 1- Without Recursion Algorithm: 1. Initialize count as zero. 2. Loop through each element of linked list: a) If element data is equal to the passed number then increment the count. 3. Return count. Implementation: C++ C Java Python3 C# Javascript // C++ program to count occurrences in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; /* Given a reference (pointer to pointer) to the headof a list and an int, push a new node on the frontof the 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;} /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/int count(Node* head, int search_for){ Node* current = head; int count = 0; while (current != NULL) { if (current->data == search_for) count++; current = current->next; } return count;} /* Driver program to test count function*/int main(){ /* Start with the empty list */ Node* head = NULL; /* Use push() to construct below list 1->2->1->3->1 */ push(&head, 1); push(&head, 3); push(&head, 1); push(&head, 2); push(&head, 1); /* Check the count function */ cout << "count of 1 is " << count(head, 1); return 0;} // This is code is contributed by rathbhupendra // C program to count occurrences in a linked list#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the 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;} /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/int count(struct Node* head, int search_for){ struct Node* current = head; int count = 0; while (current != NULL) { if (current->data == search_for) count++; current = current->next; } return count;} /* Driver program to test count function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct below list 1->2->1->3->1 */ push(&head, 1); push(&head, 3); push(&head, 1); push(&head, 2); push(&head, 1); /* Check the count function */ printf("count of 1 is %d", count(head, 1)); return 0;} // Java program to count occurrences in a linked listclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ int count(int search_for) { Node current = head; int count = 0; while (current != null) { if (current.data == search_for) count++; current = current.next; } return count; } /* Driver function to test the above methods */ public static void main(String args[]) { LinkedList llist = new LinkedList(); /* Use push() to construct below list 1->2->1->3->1 */ llist.push(1); llist.push(2); llist.push(1); llist.push(3); llist.push(1); /*Checking count function*/ System.out.println("Count of 1 is " + llist.count(1)); }}// This code is contributed by Rajat Mishra # Python program to count the number of time a given# int occurs in a linked list # Node classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Counts the no . of occurrences of a node # (search_for) in a linked list (head) def count(self, search_for): current = self.head count = 0 while(current is not None): if current.data == search_for: count += 1 current = current.next return count # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the linked LinkedList def printList(self): temp = self.head while(temp): print (temp.data) temp = temp.next # Driver programllist = LinkedList()llist.push(1)llist.push(3)llist.push(1)llist.push(2)llist.push(1) # Check for the count functionprint ("count of 1 is % d" %(llist.count(1))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to count occurrences in a linked listusing System;class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ int count(int search_for) { Node current = head; int count = 0; while (current != null) { if (current.data == search_for) count++; current = current.next; } return count; } /* Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); /* Use push() to construct below list 1->2->1->3->1 */ llist.push(1); llist.push(2); llist.push(1); llist.push(3); llist.push(1); /*Checking count function*/ Console.WriteLine("Count of 1 is " + llist.count(1)); }} // This code is contributed by Arnab Kundu <script>// javascript program to count occurrences in a linked listvar head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* * Counts the no. of occurrences of a node (search_for) in a linked list (head) */ function count(search_for) { current = head; var count = 0; while (current != null) { if (current.data == search_for) count++; current = current.next; } return count; } /* Driver function to test the above methods */ /* * Use push() to construct below list 1->2->1->3->1 */ push(1); push(2); push(1); push(3); push(1); /* Checking count function */ document.write("Count of 1 is " + count(1)); // This code contributed by gauravrajput1</script> Output: count of 1 is 3 Time Complexity: O(n) Auxiliary Space: O(1) Method 2- With Recursion This method is contributed by MY_DOOM. Algorithm: Algorithm count(head, key); if head is NULL return frequency if(head->data==key) increase frequency by 1 count(head->next, key) Implementation: C++ Java Python3 C# Javascript // C++ program to count occurrences in// a linked list using recursion#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;};// global variable for counting frequency of// given element kint frequency = 0; /* Given a reference (pointer to pointer) to the headof a list and an int, push a new node on the frontof the 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;} /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/int count(struct Node* head, int key){ if (head == NULL) return frequency; if (head->data == key) frequency++; return count(head->next, key);} /* Driver program to test count function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct below list 1->2->1->3->1 */ push(&head, 1); push(&head, 3); push(&head, 1); push(&head, 2); push(&head, 1); /* Check the count function */ cout << "count of 1 is " << count(head, 1); return 0;} // Java program to count occurrences in// a linked list using recursionimport java.io.*;import java.util.*; // Represents node of a linkedlistclass Node { int data; Node next; Node(int val) { data = val; next = null; }} class GFG { // global variable for counting frequency of // given element k static int frequency = 0; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ static Node push(Node head, int new_data) { // allocate node Node new_node = new Node(new_data); // link the old list off the new node new_node.next = head; // move the head to point to the new node head = new_node; return head; } /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ static int count(Node head, int key) { if (head == null) return frequency; if (head.data == key) frequency++; return count(head.next, key); } // Driver Code public static void main(String args[]) { // Start with the empty list Node head = null; /* Use push() to construct below list 1->2->1->3->1 */ head = push(head, 1); head = push(head, 3); head = push(head, 1); head = push(head, 2); head = push(head, 1); /* Check the count function */ System.out.print("count of 1 is " + count(head, 1)); }} // This code is contributed by rachana soma # Python program to count the number of# time a given int occurs in a linked list# Node classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None self.counter = 0 # Counts the no . of occurrences of a node # (seach_for) in a linked list (head) def count(self, li, key): # Base case if(not li): return self.counter # If key is present in # current node, return true if(li.data == key): self.counter = self.counter + 1 # Recur for remaining list return self.count(li.next, key) # Function to insert a new node # at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the # linked LinkedList def printList(self): temp = self.head while(temp): print (temp.data) temp = temp.next # Driver Codellist = LinkedList()llist.push(1)llist.push(3)llist.push(1)llist.push(2)llist.push(1) # Check for the count functionprint ("count of 1 is", llist.count(llist.head, 1)) # This code is contributed by# Gaurav Kumar Raghav // C# program to count occurrences in// a linked list using recursionusing System; // Represents node of a linkedlistpublic class Node { public int data; public Node next; public Node(int val) { data = val; next = null; }} class GFG { // global variable for counting frequency of // given element k static int frequency = 0; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ static Node push(Node head, int new_data) { // allocate node Node new_node = new Node(new_data); // link the old list off the new node new_node.next = head; // move the head to point to the new node head = new_node; return head; } /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ static int count(Node head, int key) { if (head == null) return frequency; if (head.data == key) frequency++; return count(head.next, key); } // Driver Code public static void Main(String[] args) { // Start with the empty list Node head = null; /* Use push() to construct below list 1->2->1->3->1 */ head = push(head, 1); head = push(head, 3); head = push(head, 1); head = push(head, 2); head = push(head, 1); /* Check the count function */ Console.Write("count of 1 is " + count(head, 1)); }} /* This code contributed by PrinciRaj1992 */ <script> // Javascript program to count occurrences in// a linked list using recursion // Represents node of a linkedlistclass Node{ constructor(val) { this.data = val; this.next = null; }} // Global variable for counting// frequency of given element klet frequency = 0; /* Given a reference (pointer to pointer)to the head of a list and an int, push anew node on the front of the list. */function push(head, new_data){ // Allocate node let new_node = new Node(new_data); // Link the old list off the new node new_node.next = head; // Move the head to point to the new node head = new_node; return head;} /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/function count(head, key){ if (head == null) return frequency; if (head.data == key) frequency++; return count(head.next, key);} // Driver code // Start with the empty listlet head = null; /* Use push() to construct below list 1->2->1->3->1 */head = push(head, 1);head = push(head, 3);head = push(head, 1);head = push(head, 2);head = push(head, 1); /* Check the count function */document.write("count of 1 is " + count(head, 1)); // This code is contributed by divyeshrabadiya07 </script> Output: count of 1 is 3 Below method can be used to avoid Global variable ‘frequency'(counter in case of Python 3 Code). C++ Java C# Python3 Javascript // method can be used to avoid// Global variable 'frequency' /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/int count(struct Node* head, int key){ if (head == NULL) return 0; if (head->data == key) return 1 + count(head->next, key); return count(head->next, key);} // method can be used to avoid// Global variable 'frequency' /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/int count(Node head, int key){ if (head == null) return 0; if (head.data == key) return 1 + count(head.next, key); return count(head.next, key);} // This code is contributed by rachana soma // method can be used to avoid// Global variable 'frequency'using System; /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/static int count(Node head, int key){ if (head == null) return 0; if (head.data == key) return 1 + count(head.next, key); return count(head.next, key);} // This code is contributed by SHUBHAMSINGH10 def count(self, temp, key): # during the initial call, temp # has the value of head # Base case if temp is None: return 0 # if a match is found, we # increment the counter if temp.data == key: return 1 + count(temp.next, key) return count(temp.next, key) # to call count, use# linked_list_name.count(head, key) <script> // method can be used to afunction// Global variable 'frequency' /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/function count(head , key){ if (head == null) return 0; if (head.data == key) return 1 + count(head.next, key); return count(head.next, key);} // This code is contributed by todaysgaurav </script> The above method implements head recursion. Below given is the tail recursive implementation for the same. Thanks to Puneet Jain for suggesting this approach : int count(struct Node* head, int key) { if(head == NULL) return 0; int frequency = count(head->next, key); if(head->data == key) return 1 + frequency; // else return frequency; } Time Complexity: O(n) https://www.youtube.com/watch?v=-g3KauAWofwPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Puneet Jain 1 Shreyash Sharma 3 SivaPrakashReddyKomma andrew1234 gaurav_kumar_raghav dkp1903 rathbhupendra rachana soma princiraj1992 SHUBHAMSINGH10 nidhi_biet GauravRajput1 todaysgaurav anikaseth98 divyeshrabadiya07 khushboogoyal499 amartyaghoshgfg simranarora5sos Linked Lists Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Delete a 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": 24232, "s": 24204, "text": "\n05 Apr, 2022" }, { "code": null, "e": 24453, "s": 24232, "text": "Given a singly linked list and a key, count the number of occurrences of the given key in the linked list. For example, if the given linked list is 1->2->1->2->1->3->1 and the given key is 1, then the output should be 4." }, { "code": null, "e": 24482, "s": 24453, "text": "Method 1- Without Recursion " }, { "code": null, "e": 24495, "s": 24482, "text": "Algorithm: " }, { "code": null, "e": 24675, "s": 24495, "text": "1. Initialize count as zero.\n2. Loop through each element of linked list:\n a) If element data is equal to the passed number then\n increment the count.\n3. Return count. " }, { "code": null, "e": 24693, "s": 24675, "text": "Implementation: " }, { "code": null, "e": 24697, "s": 24693, "text": "C++" }, { "code": null, "e": 24699, "s": 24697, "text": "C" }, { "code": null, "e": 24704, "s": 24699, "text": "Java" }, { "code": null, "e": 24712, "s": 24704, "text": "Python3" }, { "code": null, "e": 24715, "s": 24712, "text": "C#" }, { "code": null, "e": 24726, "s": 24715, "text": "Javascript" }, { "code": "// C++ program to count occurrences in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; /* Given a reference (pointer to pointer) to the headof a list and an int, push a new node on the frontof the 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;} /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/int count(Node* head, int search_for){ Node* current = head; int count = 0; while (current != NULL) { if (current->data == search_for) count++; current = current->next; } return count;} /* Driver program to test count function*/int main(){ /* Start with the empty list */ Node* head = NULL; /* Use push() to construct below list 1->2->1->3->1 */ push(&head, 1); push(&head, 3); push(&head, 1); push(&head, 2); push(&head, 1); /* Check the count function */ cout << \"count of 1 is \" << count(head, 1); return 0;} // This is code is contributed by rathbhupendra", "e": 26037, "s": 24726, "text": null }, { "code": "// C program to count occurrences in a linked list#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the 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;} /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/int count(struct Node* head, int search_for){ struct Node* current = head; int count = 0; while (current != NULL) { if (current->data == search_for) count++; current = current->next; } return count;} /* Driver program to test count function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct below list 1->2->1->3->1 */ push(&head, 1); push(&head, 3); push(&head, 1); push(&head, 2); push(&head, 1); /* Check the count function */ printf(\"count of 1 is %d\", count(head, 1)); return 0;}", "e": 27368, "s": 26037, "text": null }, { "code": "// Java program to count occurrences in a linked listclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ int count(int search_for) { Node current = head; int count = 0; while (current != null) { if (current.data == search_for) count++; current = current.next; } return count; } /* Driver function to test the above methods */ public static void main(String args[]) { LinkedList llist = new LinkedList(); /* Use push() to construct below list 1->2->1->3->1 */ llist.push(1); llist.push(2); llist.push(1); llist.push(3); llist.push(1); /*Checking count function*/ System.out.println(\"Count of 1 is \" + llist.count(1)); }}// This code is contributed by Rajat Mishra", "e": 28812, "s": 27368, "text": null }, { "code": "# Python program to count the number of time a given# int occurs in a linked list # Node classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Counts the no . of occurrences of a node # (search_for) in a linked list (head) def count(self, search_for): current = self.head count = 0 while(current is not None): if current.data == search_for: count += 1 current = current.next return count # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the linked LinkedList def printList(self): temp = self.head while(temp): print (temp.data) temp = temp.next # Driver programllist = LinkedList()llist.push(1)llist.push(3)llist.push(1)llist.push(2)llist.push(1) # Check for the count functionprint (\"count of 1 is % d\" %(llist.count(1))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 30061, "s": 28812, "text": null }, { "code": "// C# program to count occurrences in a linked listusing System;class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ int count(int search_for) { Node current = head; int count = 0; while (current != null) { if (current.data == search_for) count++; current = current.next; } return count; } /* Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); /* Use push() to construct below list 1->2->1->3->1 */ llist.push(1); llist.push(2); llist.push(1); llist.push(3); llist.push(1); /*Checking count function*/ Console.WriteLine(\"Count of 1 is \" + llist.count(1)); }} // This code is contributed by Arnab Kundu", "e": 31508, "s": 30061, "text": null }, { "code": "<script>// javascript program to count occurrences in a linked listvar head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* * Counts the no. of occurrences of a node (search_for) in a linked list (head) */ function count(search_for) { current = head; var count = 0; while (current != null) { if (current.data == search_for) count++; current = current.next; } return count; } /* Driver function to test the above methods */ /* * Use push() to construct below list 1->2->1->3->1 */ push(1); push(2); push(1); push(3); push(1); /* Checking count function */ document.write(\"Count of 1 is \" + count(1)); // This code contributed by gauravrajput1</script>", "e": 32831, "s": 31508, "text": null }, { "code": null, "e": 32840, "s": 32831, "text": "Output: " }, { "code": null, "e": 32856, "s": 32840, "text": "count of 1 is 3" }, { "code": null, "e": 32900, "s": 32856, "text": "Time Complexity: O(n) Auxiliary Space: O(1)" }, { "code": null, "e": 32965, "s": 32900, "text": "Method 2- With Recursion This method is contributed by MY_DOOM. " }, { "code": null, "e": 32977, "s": 32965, "text": "Algorithm: " }, { "code": null, "e": 33105, "s": 32977, "text": "Algorithm\ncount(head, key);\nif head is NULL\nreturn frequency\nif(head->data==key)\nincrease frequency by 1\ncount(head->next, key)" }, { "code": null, "e": 33123, "s": 33105, "text": "Implementation: " }, { "code": null, "e": 33127, "s": 33123, "text": "C++" }, { "code": null, "e": 33132, "s": 33127, "text": "Java" }, { "code": null, "e": 33140, "s": 33132, "text": "Python3" }, { "code": null, "e": 33143, "s": 33140, "text": "C#" }, { "code": null, "e": 33154, "s": 33143, "text": "Javascript" }, { "code": "// C++ program to count occurrences in// a linked list using recursion#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;};// global variable for counting frequency of// given element kint frequency = 0; /* Given a reference (pointer to pointer) to the headof a list and an int, push a new node on the frontof the 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;} /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/int count(struct Node* head, int key){ if (head == NULL) return frequency; if (head->data == key) frequency++; return count(head->next, key);} /* Driver program to test count function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct below list 1->2->1->3->1 */ push(&head, 1); push(&head, 3); push(&head, 1); push(&head, 2); push(&head, 1); /* Check the count function */ cout << \"count of 1 is \" << count(head, 1); return 0;}", "e": 34510, "s": 33154, "text": null }, { "code": "// Java program to count occurrences in// a linked list using recursionimport java.io.*;import java.util.*; // Represents node of a linkedlistclass Node { int data; Node next; Node(int val) { data = val; next = null; }} class GFG { // global variable for counting frequency of // given element k static int frequency = 0; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ static Node push(Node head, int new_data) { // allocate node Node new_node = new Node(new_data); // link the old list off the new node new_node.next = head; // move the head to point to the new node head = new_node; return head; } /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ static int count(Node head, int key) { if (head == null) return frequency; if (head.data == key) frequency++; return count(head.next, key); } // Driver Code public static void main(String args[]) { // Start with the empty list Node head = null; /* Use push() to construct below list 1->2->1->3->1 */ head = push(head, 1); head = push(head, 3); head = push(head, 1); head = push(head, 2); head = push(head, 1); /* Check the count function */ System.out.print(\"count of 1 is \" + count(head, 1)); }} // This code is contributed by rachana soma", "e": 36069, "s": 34510, "text": null }, { "code": "# Python program to count the number of# time a given int occurs in a linked list# Node classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None self.counter = 0 # Counts the no . of occurrences of a node # (seach_for) in a linked list (head) def count(self, li, key): # Base case if(not li): return self.counter # If key is present in # current node, return true if(li.data == key): self.counter = self.counter + 1 # Recur for remaining list return self.count(li.next, key) # Function to insert a new node # at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the # linked LinkedList def printList(self): temp = self.head while(temp): print (temp.data) temp = temp.next # Driver Codellist = LinkedList()llist.push(1)llist.push(3)llist.push(1)llist.push(2)llist.push(1) # Check for the count functionprint (\"count of 1 is\", llist.count(llist.head, 1)) # This code is contributed by# Gaurav Kumar Raghav", "e": 37460, "s": 36069, "text": null }, { "code": "// C# program to count occurrences in// a linked list using recursionusing System; // Represents node of a linkedlistpublic class Node { public int data; public Node next; public Node(int val) { data = val; next = null; }} class GFG { // global variable for counting frequency of // given element k static int frequency = 0; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ static Node push(Node head, int new_data) { // allocate node Node new_node = new Node(new_data); // link the old list off the new node new_node.next = head; // move the head to point to the new node head = new_node; return head; } /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ static int count(Node head, int key) { if (head == null) return frequency; if (head.data == key) frequency++; return count(head.next, key); } // Driver Code public static void Main(String[] args) { // Start with the empty list Node head = null; /* Use push() to construct below list 1->2->1->3->1 */ head = push(head, 1); head = push(head, 3); head = push(head, 1); head = push(head, 2); head = push(head, 1); /* Check the count function */ Console.Write(\"count of 1 is \" + count(head, 1)); }} /* This code contributed by PrinciRaj1992 */", "e": 39020, "s": 37460, "text": null }, { "code": "<script> // Javascript program to count occurrences in// a linked list using recursion // Represents node of a linkedlistclass Node{ constructor(val) { this.data = val; this.next = null; }} // Global variable for counting// frequency of given element klet frequency = 0; /* Given a reference (pointer to pointer)to the head of a list and an int, push anew node on the front of the list. */function push(head, new_data){ // Allocate node let new_node = new Node(new_data); // Link the old list off the new node new_node.next = head; // Move the head to point to the new node head = new_node; return head;} /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/function count(head, key){ if (head == null) return frequency; if (head.data == key) frequency++; return count(head.next, key);} // Driver code // Start with the empty listlet head = null; /* Use push() to construct below list 1->2->1->3->1 */head = push(head, 1);head = push(head, 3);head = push(head, 1);head = push(head, 2);head = push(head, 1); /* Check the count function */document.write(\"count of 1 is \" + count(head, 1)); // This code is contributed by divyeshrabadiya07 </script>", "e": 40312, "s": 39020, "text": null }, { "code": null, "e": 40321, "s": 40312, "text": "Output: " }, { "code": null, "e": 40337, "s": 40321, "text": "count of 1 is 3" }, { "code": null, "e": 40435, "s": 40337, "text": "Below method can be used to avoid Global variable ‘frequency'(counter in case of Python 3 Code). " }, { "code": null, "e": 40439, "s": 40435, "text": "C++" }, { "code": null, "e": 40444, "s": 40439, "text": "Java" }, { "code": null, "e": 40447, "s": 40444, "text": "C#" }, { "code": null, "e": 40455, "s": 40447, "text": "Python3" }, { "code": null, "e": 40466, "s": 40455, "text": "Javascript" }, { "code": "// method can be used to avoid// Global variable 'frequency' /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/int count(struct Node* head, int key){ if (head == NULL) return 0; if (head->data == key) return 1 + count(head->next, key); return count(head->next, key);}", "e": 40787, "s": 40466, "text": null }, { "code": "// method can be used to avoid// Global variable 'frequency' /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/int count(Node head, int key){ if (head == null) return 0; if (head.data == key) return 1 + count(head.next, key); return count(head.next, key);} // This code is contributed by rachana soma", "e": 41141, "s": 40787, "text": null }, { "code": "// method can be used to avoid// Global variable 'frequency'using System; /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/static int count(Node head, int key){ if (head == null) return 0; if (head.data == key) return 1 + count(head.next, key); return count(head.next, key);} // This code is contributed by SHUBHAMSINGH10", "e": 41517, "s": 41141, "text": null }, { "code": "def count(self, temp, key): # during the initial call, temp # has the value of head # Base case if temp is None: return 0 # if a match is found, we # increment the counter if temp.data == key: return 1 + count(temp.next, key) return count(temp.next, key) # to call count, use# linked_list_name.count(head, key)", "e": 41889, "s": 41517, "text": null }, { "code": "<script> // method can be used to afunction// Global variable 'frequency' /* Counts the no. of occurrences of a node(search_for) in a linked list (head)*/function count(head , key){ if (head == null) return 0; if (head.data == key) return 1 + count(head.next, key); return count(head.next, key);} // This code is contributed by todaysgaurav </script>", "e": 42263, "s": 41889, "text": null }, { "code": null, "e": 42425, "s": 42263, "text": "The above method implements head recursion. Below given is the tail recursive implementation for the same. Thanks to Puneet Jain for suggesting this approach : " }, { "code": null, "e": 42650, "s": 42425, "text": "int count(struct Node* head, int key)\n{\n if(head == NULL)\n return 0;\n \n int frequency = count(head->next, key);\n if(head->data == key)\n return 1 + frequency;\n \n // else \n return frequency;\n}" }, { "code": null, "e": 42672, "s": 42650, "text": "Time Complexity: O(n)" }, { "code": null, "e": 42840, "s": 42672, "text": "https://www.youtube.com/watch?v=-g3KauAWofwPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 42854, "s": 42840, "text": "Puneet Jain 1" }, { "code": null, "e": 42872, "s": 42854, "text": "Shreyash Sharma 3" }, { "code": null, "e": 42894, "s": 42872, "text": "SivaPrakashReddyKomma" }, { "code": null, "e": 42905, "s": 42894, "text": "andrew1234" }, { "code": null, "e": 42925, "s": 42905, "text": "gaurav_kumar_raghav" }, { "code": null, "e": 42933, "s": 42925, "text": "dkp1903" }, { "code": null, "e": 42947, "s": 42933, "text": "rathbhupendra" }, { "code": null, "e": 42960, "s": 42947, "text": "rachana soma" }, { "code": null, "e": 42974, "s": 42960, "text": "princiraj1992" }, { "code": null, "e": 42989, "s": 42974, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 43000, "s": 42989, "text": "nidhi_biet" }, { "code": null, "e": 43014, "s": 43000, "text": "GauravRajput1" }, { "code": null, "e": 43027, "s": 43014, "text": "todaysgaurav" }, { "code": null, "e": 43039, "s": 43027, "text": "anikaseth98" }, { "code": null, "e": 43057, "s": 43039, "text": "divyeshrabadiya07" }, { "code": null, "e": 43074, "s": 43057, "text": "khushboogoyal499" }, { "code": null, "e": 43090, "s": 43074, "text": "amartyaghoshgfg" }, { "code": null, "e": 43106, "s": 43090, "text": "simranarora5sos" }, { "code": null, "e": 43119, "s": 43106, "text": "Linked Lists" }, { "code": null, "e": 43131, "s": 43119, "text": "Linked List" }, { "code": null, "e": 43143, "s": 43131, "text": "Linked List" }, { "code": null, "e": 43241, "s": 43143, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43250, "s": 43241, "text": "Comments" }, { "code": null, "e": 43263, "s": 43250, "text": "Old Comments" }, { "code": null, "e": 43309, "s": 43263, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 43344, "s": 43309, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 43387, "s": 43344, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 43434, "s": 43387, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 43495, "s": 43434, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 43539, "s": 43495, "text": "Remove duplicates from a sorted linked list" }, { "code": null, "e": 43594, "s": 43539, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 43650, "s": 43594, "text": "Function to check if a singly linked list is palindrome" }, { "code": null, "e": 43711, "s": 43650, "text": "Search an element in a Linked List (Iterative and Recursive)" } ]
PySpark ML and XGBoost full integration tested on the Kaggle Titanic dataset | by Bogdan Cojocar | Towards Data Science
In this tutorial we will discuss about integrating PySpark and XGBoost using a standard machine learing pipeline. We will use data from the Titanic: Machine learning from disaster one of the many Kaggle competitions. Before getting started please know that you should be familiar with Apache Spark and Xgboost and Python. The code used in this tutorial is available in a Jupyther notebook on github. The python code will need two scala jars dependencies in order to work. You can download them directly from maven: xgboost4j xgboost4j-spark If you wish to build them yourself you can find out how to do it from one of my previous tutorials. You can download the PySpark XGBoost code from here. This is the interface between the part that we will write and the XGBoost scala implementation. We will see how to integrate it in the code later in the tutorial. We will start a new notebook in order to be able to write our code: jupyter notebook Before starting Spark we need to add the jars we previously downloaded. We can do this using the --jars flag: import osos.environ['PYSPARK_SUBMIT_ARGS'] = '--jars xgboost4j-spark-0.72.jar,xgboost4j-0.72.jar pyspark-shell' Easiest way to make PySpark available is using the findspark package: import findsparkfindspark.init() We are now ready to start the spark session. We are creating a spark app that will run locally and will use as many threads as there are cores using local[*] : spark = SparkSession\ .builder\ .appName("PySpark XGBOOST Titanic")\ .master("local[*]")\ .getOrCreate() As we have now the spark session, we can add the wrapper code we previously dowloaded: spark.sparkContext.addPyFile("YOUR_PATH/sparkxgb.zip") Next we define a schema of the data we read from the csv. This is usually a better practice than letting spark to infer the schema because it consumes less resources and we have total control over the fields. schema = StructType( [StructField("PassengerId", DoubleType()), StructField("Survival", DoubleType()), StructField("Pclass", DoubleType()), StructField("Name", StringType()), StructField("Sex", StringType()), StructField("Age", DoubleType()), StructField("SibSp", DoubleType()), StructField("Parch", DoubleType()), StructField("Ticket", StringType()), StructField("Fare", DoubleType()), StructField("Cabin", StringType()), StructField("Embarked", StringType()) ]) We read the csv into a DataFrame, making sure we mention we have a header and we also replace null values with 0: df_raw = spark\ .read\ .option("header", "true")\ .schema(schema)\ .csv("YOUR_PATH/train.csv")df = df_raw.na.fill(0) Before walking through the code on this step let’s go briefly through some Spark ML concepts. They introduce the concept of ML pipelines, which is a set of high level APIs build on top of the DataFrameswhich make it easier to combine multiple algorithms into a single process. The main elements of a pipeline are the Transformer and the Estimator. The first can represent an algorithm that can transform a DataFrame into another DataFrame, and the latter is an algorithm that can fit on a DataFrame to produce a Transformer . In order to convert the nominal values into numeric ones we need to define aTransformer for each column: sexIndexer = StringIndexer()\ .setInputCol("Sex")\ .setOutputCol("SexIndex")\ .setHandleInvalid("keep") cabinIndexer = StringIndexer()\ .setInputCol("Cabin")\ .setOutputCol("CabinIndex")\ .setHandleInvalid("keep") embarkedIndexer = StringIndexer()\ .setInputCol("Embarked")\ .setOutputCol("EmbarkedIndex")\ .setHandleInvalid("keep") We are using the StringIndexer to transform the values. For each Transformer we are defining the input column and the output column that will contain the modified value. We will use another Transformer to assemble the columns used in the classification by the XGBoost Estimatorinto a vector: vectorAssembler = VectorAssembler()\ .setInputCols(["Pclass", "SexIndex", "Age", "SibSp", "Parch", "Fare", "CabinIndex", "EmbarkedIndex"])\ .setOutputCol("features") In this step we are defining the Estimator that will produce the model. Most of the parameters used here are default: xgboost = XGBoostEstimator( featuresCol="features", labelCol="Survival", predictionCol="prediction") We only define the feature, label (have to match out columns from the DataFrame ) and the new prediction column that contains the output of the classifier. After we created all the individual steps we can define the actual pipeline and the order of the operations: pipeline = Pipeline().setStages([sexIndexer, cabinIndexer, embarkedIndexer, vectorAssembler, xgboost]) The input DataFrame will be transformed multiple times and in the end will produce the model trained with our data. We first split the data into train and test, then we fit the model with the train data and finally we see what predictions we have obtained for each passenger: trainDF, testDF = df.randomSplit([0.8, 0.2], seed=24)model = pipeline.fit(trainDF)model.transform(testDF).select(col("PassengerId"), col("prediction")).show()
[ { "code": null, "e": 285, "s": 171, "text": "In this tutorial we will discuss about integrating PySpark and XGBoost using a standard machine learing pipeline." }, { "code": null, "e": 388, "s": 285, "text": "We will use data from the Titanic: Machine learning from disaster one of the many Kaggle competitions." }, { "code": null, "e": 493, "s": 388, "text": "Before getting started please know that you should be familiar with Apache Spark and Xgboost and Python." }, { "code": null, "e": 571, "s": 493, "text": "The code used in this tutorial is available in a Jupyther notebook on github." }, { "code": null, "e": 686, "s": 571, "text": "The python code will need two scala jars dependencies in order to work. You can download them directly from maven:" }, { "code": null, "e": 696, "s": 686, "text": "xgboost4j" }, { "code": null, "e": 712, "s": 696, "text": "xgboost4j-spark" }, { "code": null, "e": 812, "s": 712, "text": "If you wish to build them yourself you can find out how to do it from one of my previous tutorials." }, { "code": null, "e": 1028, "s": 812, "text": "You can download the PySpark XGBoost code from here. This is the interface between the part that we will write and the XGBoost scala implementation. We will see how to integrate it in the code later in the tutorial." }, { "code": null, "e": 1096, "s": 1028, "text": "We will start a new notebook in order to be able to write our code:" }, { "code": null, "e": 1114, "s": 1096, "text": "jupyter notebook " }, { "code": null, "e": 1224, "s": 1114, "text": "Before starting Spark we need to add the jars we previously downloaded. We can do this using the --jars flag:" }, { "code": null, "e": 1336, "s": 1224, "text": "import osos.environ['PYSPARK_SUBMIT_ARGS'] = '--jars xgboost4j-spark-0.72.jar,xgboost4j-0.72.jar pyspark-shell'" }, { "code": null, "e": 1406, "s": 1336, "text": "Easiest way to make PySpark available is using the findspark package:" }, { "code": null, "e": 1439, "s": 1406, "text": "import findsparkfindspark.init()" }, { "code": null, "e": 1599, "s": 1439, "text": "We are now ready to start the spark session. We are creating a spark app that will run locally and will use as many threads as there are cores using local[*] :" }, { "code": null, "e": 1732, "s": 1599, "text": "spark = SparkSession\\ .builder\\ .appName(\"PySpark XGBOOST Titanic\")\\ .master(\"local[*]\")\\ .getOrCreate()" }, { "code": null, "e": 1819, "s": 1732, "text": "As we have now the spark session, we can add the wrapper code we previously dowloaded:" }, { "code": null, "e": 1874, "s": 1819, "text": "spark.sparkContext.addPyFile(\"YOUR_PATH/sparkxgb.zip\")" }, { "code": null, "e": 2083, "s": 1874, "text": "Next we define a schema of the data we read from the csv. This is usually a better practice than letting spark to infer the schema because it consumes less resources and we have total control over the fields." }, { "code": null, "e": 2582, "s": 2083, "text": "schema = StructType( [StructField(\"PassengerId\", DoubleType()), StructField(\"Survival\", DoubleType()), StructField(\"Pclass\", DoubleType()), StructField(\"Name\", StringType()), StructField(\"Sex\", StringType()), StructField(\"Age\", DoubleType()), StructField(\"SibSp\", DoubleType()), StructField(\"Parch\", DoubleType()), StructField(\"Ticket\", StringType()), StructField(\"Fare\", DoubleType()), StructField(\"Cabin\", StringType()), StructField(\"Embarked\", StringType()) ])" }, { "code": null, "e": 2696, "s": 2582, "text": "We read the csv into a DataFrame, making sure we mention we have a header and we also replace null values with 0:" }, { "code": null, "e": 2817, "s": 2696, "text": "df_raw = spark\\ .read\\ .option(\"header\", \"true\")\\ .schema(schema)\\ .csv(\"YOUR_PATH/train.csv\")df = df_raw.na.fill(0)" }, { "code": null, "e": 3343, "s": 2817, "text": "Before walking through the code on this step let’s go briefly through some Spark ML concepts. They introduce the concept of ML pipelines, which is a set of high level APIs build on top of the DataFrameswhich make it easier to combine multiple algorithms into a single process. The main elements of a pipeline are the Transformer and the Estimator. The first can represent an algorithm that can transform a DataFrame into another DataFrame, and the latter is an algorithm that can fit on a DataFrame to produce a Transformer ." }, { "code": null, "e": 3448, "s": 3343, "text": "In order to convert the nominal values into numeric ones we need to define aTransformer for each column:" }, { "code": null, "e": 3796, "s": 3448, "text": "sexIndexer = StringIndexer()\\ .setInputCol(\"Sex\")\\ .setOutputCol(\"SexIndex\")\\ .setHandleInvalid(\"keep\") cabinIndexer = StringIndexer()\\ .setInputCol(\"Cabin\")\\ .setOutputCol(\"CabinIndex\")\\ .setHandleInvalid(\"keep\") embarkedIndexer = StringIndexer()\\ .setInputCol(\"Embarked\")\\ .setOutputCol(\"EmbarkedIndex\")\\ .setHandleInvalid(\"keep\")" }, { "code": null, "e": 3966, "s": 3796, "text": "We are using the StringIndexer to transform the values. For each Transformer we are defining the input column and the output column that will contain the modified value." }, { "code": null, "e": 4088, "s": 3966, "text": "We will use another Transformer to assemble the columns used in the classification by the XGBoost Estimatorinto a vector:" }, { "code": null, "e": 4256, "s": 4088, "text": "vectorAssembler = VectorAssembler()\\ .setInputCols([\"Pclass\", \"SexIndex\", \"Age\", \"SibSp\", \"Parch\", \"Fare\", \"CabinIndex\", \"EmbarkedIndex\"])\\ .setOutputCol(\"features\")" }, { "code": null, "e": 4374, "s": 4256, "text": "In this step we are defining the Estimator that will produce the model. Most of the parameters used here are default:" }, { "code": null, "e": 4486, "s": 4374, "text": "xgboost = XGBoostEstimator( featuresCol=\"features\", labelCol=\"Survival\", predictionCol=\"prediction\")" }, { "code": null, "e": 4642, "s": 4486, "text": "We only define the feature, label (have to match out columns from the DataFrame ) and the new prediction column that contains the output of the classifier." }, { "code": null, "e": 4751, "s": 4642, "text": "After we created all the individual steps we can define the actual pipeline and the order of the operations:" }, { "code": null, "e": 4854, "s": 4751, "text": "pipeline = Pipeline().setStages([sexIndexer, cabinIndexer, embarkedIndexer, vectorAssembler, xgboost])" }, { "code": null, "e": 4970, "s": 4854, "text": "The input DataFrame will be transformed multiple times and in the end will produce the model trained with our data." }, { "code": null, "e": 5130, "s": 4970, "text": "We first split the data into train and test, then we fit the model with the train data and finally we see what predictions we have obtained for each passenger:" } ]
How to display a 3D plot of a 3D array isosurface in matplotlib mplot3D or similar?
Let's take an example to see how to display a 3D plot of a 3D array isosurface in matplotlib − import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.arange(-5, 5, 0.25) y = np.arange(-5, 5, 0.25) x, y = np.meshgrid(x, y) h = x ** 2 + y ** 2 fig = plt.figure() ax = Axes3D(fig) ax.plot_surface(x, y, h, rstride=1, cstride=1, cmap=plt.cm.rainbow, linewidth=0, antialiased=False) plt.show()
[ { "code": null, "e": 1157, "s": 1062, "text": "Let's take an example to see how to display a 3D plot of a 3D array isosurface in matplotlib −" }, { "code": null, "e": 1581, "s": 1157, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.arange(-5, 5, 0.25)\ny = np.arange(-5, 5, 0.25)\nx, y = np.meshgrid(x, y)\nh = x ** 2 + y ** 2\nfig = plt.figure()\nax = Axes3D(fig)\nax.plot_surface(x, y, h, rstride=1, cstride=1, cmap=plt.cm.rainbow, linewidth=0, antialiased=False)\nplt.show()" } ]
MySQL get hash value for each row?
Get hash value of each row using MD5() function from MySQL. The syntax is as follows − SELECT MD5(CONCAT(yourColumnName1,yourColumnName2,yourColumnName3,.......N)) as anyVariableName FROM yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table getHashValueForEachRow -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(20), -> Age int, -> Marks int, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.25 sec) Insert records in the table using insert command. The query is as follows − mysql> insert into getHashValueForEachRow(Name,Age,Marks) values('Larry',24,89); Query OK, 1 row affected (0.22 sec) mysql> insert into getHashValueForEachRow(Name,Age,Marks) values('David',26,98); Query OK, 1 row affected (0.24 sec) mysql> insert into getHashValueForEachRow(Name,Age,Marks) values('Bob',21,67); Query OK, 1 row affected (0.20 sec) mysql> insert into getHashValueForEachRow(Name,Age,Marks) values('Sam',22,56); Query OK, 1 row affected (0.22 sec) mysql> insert into getHashValueForEachRow(Name,Age,Marks) values('Mike',25,80); Query OK, 1 row affected (0.72 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from getHashValueForEachRow; The following is the output − +----+-------+------+-------+ | Id | Name | Age | Marks | +----+-------+------+-------+ | 1 | Larry | 24 | 89 | | 2 | David | 26 | 98 | | 3 | Bob | 21 | 67 | | 4 | Sam | 22 | 56 | | 5 | Mike 25 | 80 | | +----+-------+------+-------+ 5 rows in set (0.00 sec) The following is the query to get hash value of each row − mysql> select md5(concat(Id,Name,Age,Marks)) as HashValueOfEachRow from getHashValueForEachRow; Here is the output − +----------------------------------+ | HashValueOfEachRow | +----------------------------------+ | a5f6b8e1a701d467cf1b4d141027ca27 | | 6e649522c773b6a6672e625939eb4225 | | 8bd419e9b7e9e014a4dc0596d70e93c8 | | 504cf50194a2a6e3481dfa9b8568b9e6 | | 08716a8dad7105a00c49ea30d278b315 | +----------------------------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1149, "s": 1062, "text": "Get hash value of each row using MD5() function from MySQL. The syntax is as follows −" }, { "code": null, "e": 1265, "s": 1149, "text": "SELECT MD5(CONCAT(yourColumnName1,yourColumnName2,yourColumnName3,.......N)) as anyVariableName FROM yourTableName;" }, { "code": null, "e": 1364, "s": 1265, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1577, "s": 1364, "text": "mysql> create table getHashValueForEachRow\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Name varchar(20),\n -> Age int,\n -> Marks int,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (1.25 sec)" }, { "code": null, "e": 1653, "s": 1577, "text": "Insert records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2237, "s": 1653, "text": "mysql> insert into getHashValueForEachRow(Name,Age,Marks) values('Larry',24,89);\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into getHashValueForEachRow(Name,Age,Marks) values('David',26,98);\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into getHashValueForEachRow(Name,Age,Marks) values('Bob',21,67);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into getHashValueForEachRow(Name,Age,Marks) values('Sam',22,56);\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into getHashValueForEachRow(Name,Age,Marks) values('Mike',25,80);\nQuery OK, 1 row affected (0.72 sec)" }, { "code": null, "e": 2322, "s": 2237, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2366, "s": 2322, "text": "mysql> select *from getHashValueForEachRow;" }, { "code": null, "e": 2396, "s": 2366, "text": "The following is the output −" }, { "code": null, "e": 2691, "s": 2396, "text": "+----+-------+------+-------+\n| Id | Name | Age | Marks |\n+----+-------+------+-------+\n| 1 | Larry | 24 | 89 |\n| 2 | David | 26 | 98 |\n| 3 | Bob | 21 | 67 |\n| 4 | Sam | 22 | 56 |\n| 5 | Mike 25 | 80 | |\n+----+-------+------+-------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2750, "s": 2691, "text": "The following is the query to get hash value of each row −" }, { "code": null, "e": 2846, "s": 2750, "text": "mysql> select md5(concat(Id,Name,Age,Marks)) as HashValueOfEachRow from getHashValueForEachRow;" }, { "code": null, "e": 2867, "s": 2846, "text": "Here is the output −" }, { "code": null, "e": 3225, "s": 2867, "text": "+----------------------------------+\n| HashValueOfEachRow |\n+----------------------------------+\n| a5f6b8e1a701d467cf1b4d141027ca27 |\n| 6e649522c773b6a6672e625939eb4225 |\n| 8bd419e9b7e9e014a4dc0596d70e93c8 |\n| 504cf50194a2a6e3481dfa9b8568b9e6 |\n| 08716a8dad7105a00c49ea30d278b315 |\n+----------------------------------+\n5 rows in set (0.00 sec)" } ]
Find elements of array using XOR of consecutive elements in C++
Consider we have to find a list of n elements. But we have the XOR value of two consecutive elements of the actual array. Also the first element of the actual is given. So if the array elements are a, b, c, d, e, f, then the given array will be a^b, b^c, c^d, d^e and e^f. As the first number is given, named a, that can help us to find all numbers. If we want to find the second element of the actual array, then we have to perform b = a ^ arr[i], for second element c = b ^ arr[1] and so on. #include<iostream> using namespace std; void findActualElements(int a, int arr[], int n) { int actual[n + 1]; actual[0] = a; for (int i = 0; i < n; i++) { actual[i + 1] = arr[i] ^ actual[i]; } for (int i = 0; i < n + 1; i++) cout << actual[i] << " "; } int main() { int arr[] = { 12, 5, 26, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int a = 6; findActualElements(a, arr, n); } 6 10 15 21 18
[ { "code": null, "e": 1335, "s": 1062, "text": "Consider we have to find a list of n elements. But we have the XOR value of two consecutive elements of the actual array. Also the first element of the actual is given. So if the array elements are a, b, c, d, e, f, then the given array will be a^b, b^c, c^d, d^e and e^f." }, { "code": null, "e": 1556, "s": 1335, "text": "As the first number is given, named a, that can help us to find all numbers. If we want to find the second element of the actual array, then we have to perform b = a ^ arr[i], for second element c = b ^ arr[1] and so on." }, { "code": null, "e": 1973, "s": 1556, "text": "#include<iostream>\nusing namespace std;\nvoid findActualElements(int a, int arr[], int n) {\n int actual[n + 1];\n actual[0] = a;\n for (int i = 0; i < n; i++) {\n actual[i + 1] = arr[i] ^ actual[i];\n }\n for (int i = 0; i < n + 1; i++)\n cout << actual[i] << \" \";\n}\nint main() {\n int arr[] = { 12, 5, 26, 7 };\n int n = sizeof(arr) / sizeof(arr[0]);\n int a = 6;\n findActualElements(a, arr, n);\n}" }, { "code": null, "e": 1987, "s": 1973, "text": "6 10 15 21 18" } ]
AWT BorderLayout Class
The class BorderLayout arranges the components to fit in the five regions: east, west, north, south and center. Each region is can contain only one component and each component in each region is identified by the corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER. Following is the declaration for java.awt.BorderLayout class: public class BorderLayout extends Object implements LayoutManager2, Serializable Following are the fields for java.awt.BorderLayout class: static String AFTER_LAST_LINE -- Synonym for PAGE_END. static String AFTER_LAST_LINE -- Synonym for PAGE_END. static String AFTER_LINE_ENDS -- Synonym for LINE_END. static String AFTER_LINE_ENDS -- Synonym for LINE_END. static String BEFORE_FIRST_LINE -- Synonym for PAGE_START. static String BEFORE_FIRST_LINE -- Synonym for PAGE_START. static String BEFORE_LINE_BEGINS -- Synonym for LINE_START. static String BEFORE_LINE_BEGINS -- Synonym for LINE_START. static String CENTER -- The center layout constraint (middle of container). static String CENTER -- The center layout constraint (middle of container). static String EAST -- The east layout constraint (right side of container). static String EAST -- The east layout constraint (right side of container). static String LINE_END -- The component goes at the end of the line direction for the layout. static String LINE_END -- The component goes at the end of the line direction for the layout. static String LINE_START -- The component goes at the beginning of the line direction for the layout. static String LINE_START -- The component goes at the beginning of the line direction for the layout. static String NORTH -- The north layout constraint (top of container). static String NORTH -- The north layout constraint (top of container). static String PAGE_END -- The component comes after the last line of the layout's content. static String PAGE_END -- The component comes after the last line of the layout's content. static String PAGE_START -- The component comes before the first line of the layout's content. static String PAGE_START -- The component comes before the first line of the layout's content. static String SOUTH -- The south layout constraint (bottom of container). static String SOUTH -- The south layout constraint (bottom of container). static String WEST -- The west layout constraint (left side of container). static String WEST -- The west layout constraint (left side of container). BorderLayout() Constructs a new border layout with no gaps between components. BorderLayout(int hgap, int vgap) Constructs a border layout with the specified gaps between components. void addLayoutComponent(Component comp, Object constraints) Adds the specified component to the layout, using the specified constraint object. void addLayoutComponent(String name, Component comp) If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name. int getHgap() Returns the horizontal gap between components. float getLayoutAlignmentX(Container parent) Returns the alignment along the x axis. float getLayoutAlignmentY(Container parent) Returns the alignment along the y axis. int getVgap() Returns the vertical gap between components. void invalidateLayout(Container target) Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. void layoutContainer(Container target) Lays out the container argument using this border layout. Dimension maximumLayoutSize(Container target) Returns the maximum dimensions for this layout given the components in the specified target container. Dimension minimumLayoutSize(Container target) Determines the minimum size of the target container using this layout manager. Dimension preferredLayoutSize(Container target) Determines the preferred size of the target container using this layout manager, based on the components in the container. void removeLayoutComponent(Component comp) Removes the specified component from this border layout. void setHgap(int hgap) Sets the horizontal gap between components. void setVgap(int vgap) Sets the vertical gap between components. String toString() Returns a string representation of the state of this border layout. This class inherits methods from the following classes: java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtLayoutDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; private Label msglabel; public AwtLayoutDemo(){ prepareGUI(); } public static void main(String[] args){ AwtLayoutDemo awtLayoutDemo = new AwtLayoutDemo(); awtLayoutDemo.showBorderLayoutDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); msglabel = new Label(); msglabel.setAlignment(Label.CENTER); msglabel.setText("Welcome to TutorialsPoint AWT Tutorial."); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showBorderLayoutDemo(){ headerLabel.setText("Layout in action: BorderLayout"); Panel panel = new Panel(); panel.setBackground(Color.darkGray); panel.setSize(300,300); BorderLayout layout = new BorderLayout(); layout.setHgap(10); layout.setVgap(10); panel.setLayout(layout); panel.add(new Button("Center"),BorderLayout.CENTER); panel.add(new Button("Line Start"),BorderLayout.LINE_START); panel.add(new Button("Line End"),BorderLayout.LINE_END); panel.add(new Button("East"),BorderLayout.EAST); panel.add(new Button("West"),BorderLayout.WEST); panel.add(new Button("North"),BorderLayout.NORTH); panel.add(new Button("South"),BorderLayout.SOUTH); controlPanel.add(panel); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtlayoutDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtlayoutDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 2021, "s": 1747, "text": "The class BorderLayout arranges the components to fit in the five regions: east, west, north, south and center. Each region is can contain only one component and each component in each region is identified by the corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER." }, { "code": null, "e": 2083, "s": 2021, "text": "Following is the declaration for java.awt.BorderLayout class:" }, { "code": null, "e": 2173, "s": 2083, "text": "public class BorderLayout\n extends Object\n implements LayoutManager2, Serializable" }, { "code": null, "e": 2231, "s": 2173, "text": "Following are the fields for java.awt.BorderLayout class:" }, { "code": null, "e": 2287, "s": 2231, "text": "static String AFTER_LAST_LINE -- Synonym for PAGE_END." }, { "code": null, "e": 2343, "s": 2287, "text": "static String AFTER_LAST_LINE -- Synonym for PAGE_END." }, { "code": null, "e": 2399, "s": 2343, "text": "static String AFTER_LINE_ENDS -- Synonym for LINE_END." }, { "code": null, "e": 2455, "s": 2399, "text": "static String AFTER_LINE_ENDS -- Synonym for LINE_END." }, { "code": null, "e": 2515, "s": 2455, "text": "static String BEFORE_FIRST_LINE -- Synonym for PAGE_START." }, { "code": null, "e": 2575, "s": 2515, "text": "static String BEFORE_FIRST_LINE -- Synonym for PAGE_START." }, { "code": null, "e": 2636, "s": 2575, "text": "static String BEFORE_LINE_BEGINS -- Synonym for LINE_START." }, { "code": null, "e": 2697, "s": 2636, "text": "static String BEFORE_LINE_BEGINS -- Synonym for LINE_START." }, { "code": null, "e": 2774, "s": 2697, "text": "static String CENTER -- The center layout constraint (middle of container)." }, { "code": null, "e": 2851, "s": 2774, "text": "static String CENTER -- The center layout constraint (middle of container)." }, { "code": null, "e": 2928, "s": 2851, "text": "static String EAST -- The east layout constraint (right side of container)." }, { "code": null, "e": 3005, "s": 2928, "text": "static String EAST -- The east layout constraint (right side of container)." }, { "code": null, "e": 3100, "s": 3005, "text": "static String LINE_END -- The component goes at the end of the line direction for the layout." }, { "code": null, "e": 3195, "s": 3100, "text": "static String LINE_END -- The component goes at the end of the line direction for the layout." }, { "code": null, "e": 3298, "s": 3195, "text": "static String LINE_START -- The component goes at the beginning of the line direction for the layout." }, { "code": null, "e": 3401, "s": 3298, "text": "static String LINE_START -- The component goes at the beginning of the line direction for the layout." }, { "code": null, "e": 3473, "s": 3401, "text": "static String NORTH -- The north layout constraint (top of container)." }, { "code": null, "e": 3545, "s": 3473, "text": "static String NORTH -- The north layout constraint (top of container)." }, { "code": null, "e": 3637, "s": 3545, "text": "static String PAGE_END -- The component comes after the last line of the layout's content." }, { "code": null, "e": 3729, "s": 3637, "text": "static String PAGE_END -- The component comes after the last line of the layout's content." }, { "code": null, "e": 3825, "s": 3729, "text": "static String PAGE_START -- The component comes before the first line of the layout's content." }, { "code": null, "e": 3921, "s": 3825, "text": "static String PAGE_START -- The component comes before the first line of the layout's content." }, { "code": null, "e": 3996, "s": 3921, "text": "static String SOUTH -- The south layout constraint (bottom of container)." }, { "code": null, "e": 4071, "s": 3996, "text": "static String SOUTH -- The south layout constraint (bottom of container)." }, { "code": null, "e": 4147, "s": 4071, "text": "static String WEST -- The west layout constraint (left side of container)." }, { "code": null, "e": 4223, "s": 4147, "text": "static String WEST -- The west layout constraint (left side of container)." }, { "code": null, "e": 4239, "s": 4223, "text": "BorderLayout() " }, { "code": null, "e": 4303, "s": 4239, "text": "Constructs a new border layout with no gaps between components." }, { "code": null, "e": 4337, "s": 4303, "text": "BorderLayout(int hgap, int vgap) " }, { "code": null, "e": 4408, "s": 4337, "text": "Constructs a border layout with the specified gaps between components." }, { "code": null, "e": 4469, "s": 4408, "text": "void addLayoutComponent(Component comp, Object constraints) " }, { "code": null, "e": 4552, "s": 4469, "text": "Adds the specified component to the layout, using the specified constraint object." }, { "code": null, "e": 4606, "s": 4552, "text": "void addLayoutComponent(String name, Component comp) " }, { "code": null, "e": 4746, "s": 4606, "text": "If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name." }, { "code": null, "e": 4761, "s": 4746, "text": "int getHgap() " }, { "code": null, "e": 4808, "s": 4761, "text": "Returns the horizontal gap between components." }, { "code": null, "e": 4853, "s": 4808, "text": "float getLayoutAlignmentX(Container parent) " }, { "code": null, "e": 4893, "s": 4853, "text": "Returns the alignment along the x axis." }, { "code": null, "e": 4938, "s": 4893, "text": "float getLayoutAlignmentY(Container parent) " }, { "code": null, "e": 4978, "s": 4938, "text": "Returns the alignment along the y axis." }, { "code": null, "e": 4993, "s": 4978, "text": "int getVgap() " }, { "code": null, "e": 5038, "s": 4993, "text": "Returns the vertical gap between components." }, { "code": null, "e": 5079, "s": 5038, "text": "void invalidateLayout(Container target) " }, { "code": null, "e": 5188, "s": 5079, "text": "Invalidates the layout, indicating that if the layout manager has cached information it should be discarded." }, { "code": null, "e": 5228, "s": 5188, "text": "void layoutContainer(Container target) " }, { "code": null, "e": 5287, "s": 5228, "text": " Lays out the container argument using this border layout." }, { "code": null, "e": 5334, "s": 5287, "text": "Dimension maximumLayoutSize(Container target) " }, { "code": null, "e": 5437, "s": 5334, "text": "Returns the maximum dimensions for this layout given the components in the specified target container." }, { "code": null, "e": 5484, "s": 5437, "text": "Dimension minimumLayoutSize(Container target) " }, { "code": null, "e": 5563, "s": 5484, "text": "Determines the minimum size of the target container using this layout manager." }, { "code": null, "e": 5611, "s": 5563, "text": "Dimension preferredLayoutSize(Container target)" }, { "code": null, "e": 5735, "s": 5611, "text": " Determines the preferred size of the target container using this layout manager, based on the components in the container." }, { "code": null, "e": 5779, "s": 5735, "text": "void removeLayoutComponent(Component comp) " }, { "code": null, "e": 5836, "s": 5779, "text": "Removes the specified component from this border layout." }, { "code": null, "e": 5860, "s": 5836, "text": "void setHgap(int hgap) " }, { "code": null, "e": 5904, "s": 5860, "text": "Sets the horizontal gap between components." }, { "code": null, "e": 5928, "s": 5904, "text": "void setVgap(int vgap) " }, { "code": null, "e": 5970, "s": 5928, "text": "Sets the vertical gap between components." }, { "code": null, "e": 5989, "s": 5970, "text": "String toString() " }, { "code": null, "e": 6057, "s": 5989, "text": "Returns a string representation of the state of this border layout." }, { "code": null, "e": 6113, "s": 6057, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 6130, "s": 6113, "text": "java.lang.Object" }, { "code": null, "e": 6147, "s": 6130, "text": "java.lang.Object" }, { "code": null, "e": 6261, "s": 6147, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 8500, "s": 6261, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtLayoutDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n private Label msglabel;\n\n public AwtLayoutDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtLayoutDemo awtLayoutDemo = new AwtLayoutDemo(); \n awtLayoutDemo.showBorderLayoutDemo(); \n }\n \n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n msglabel = new Label();\n msglabel.setAlignment(Label.CENTER);\n msglabel.setText(\"Welcome to TutorialsPoint AWT Tutorial.\");\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showBorderLayoutDemo(){\n headerLabel.setText(\"Layout in action: BorderLayout\"); \n\n Panel panel = new Panel();\n panel.setBackground(Color.darkGray);\n panel.setSize(300,300);\n BorderLayout layout = new BorderLayout();\n layout.setHgap(10);\n layout.setVgap(10);\n panel.setLayout(layout); \n\t \n panel.add(new Button(\"Center\"),BorderLayout.CENTER);\n panel.add(new Button(\"Line Start\"),BorderLayout.LINE_START); \n panel.add(new Button(\"Line End\"),BorderLayout.LINE_END);\n panel.add(new Button(\"East\"),BorderLayout.EAST); \n panel.add(new Button(\"West\"),BorderLayout.WEST); \n panel.add(new Button(\"North\"),BorderLayout.NORTH); \n panel.add(new Button(\"South\"),BorderLayout.SOUTH); \n\n controlPanel.add(panel);\n\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 8591, "s": 8500, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 8646, "s": 8591, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtlayoutDemo.java" }, { "code": null, "e": 8743, "s": 8646, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 8792, "s": 8743, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtlayoutDemo" }, { "code": null, "e": 8820, "s": 8792, "text": "Verify the following output" }, { "code": null, "e": 8853, "s": 8820, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 8861, "s": 8853, "text": " EduOLC" }, { "code": null, "e": 8868, "s": 8861, "text": " Print" }, { "code": null, "e": 8879, "s": 8868, "text": " Add Notes" } ]
Program to calculate area and perimeter of equilateral triangle
Tringle is a closed figure with three sides. An equilateral triangle has all sides equal. Area and perimeter of an equilateral triangle can be found using the below formula, Area of equilateral triangle = (√3)/4*a2 Perimeter of equilateral triangle = 3 * a To find the area of an equilateral triangle program uses square-root and power functions. The math library has both these functions and can be used to do the calculation in the program. The below code display program to calculate the area and perimeter of an equilateral triangle, Live Demo #include <stdio.h> #include <math.h> int main(){ int side = 5, perimeter; float area; perimeter = (3 * side); area = (sqrt(3)/4)*(side*side); printf("perimeter is %d\n", perimeter); printf("area is %f", area); return 0; } perimeter is 15 area is 10.825317
[ { "code": null, "e": 1236, "s": 1062, "text": "Tringle is a closed figure with three sides. An equilateral triangle has all sides equal. Area and perimeter of an equilateral triangle can be found using the below formula," }, { "code": null, "e": 1277, "s": 1236, "text": "Area of equilateral triangle = (√3)/4*a2" }, { "code": null, "e": 1319, "s": 1277, "text": "Perimeter of equilateral triangle = 3 * a" }, { "code": null, "e": 1505, "s": 1319, "text": "To find the area of an equilateral triangle program uses square-root and power functions. The math library has both these functions and can be used to do the calculation in the program." }, { "code": null, "e": 1600, "s": 1505, "text": "The below code display program to calculate the area and perimeter of an equilateral triangle," }, { "code": null, "e": 1611, "s": 1600, "text": " Live Demo" }, { "code": null, "e": 1854, "s": 1611, "text": "#include <stdio.h>\n#include <math.h>\nint main(){\n int side = 5, perimeter;\n float area;\n perimeter = (3 * side);\n area = (sqrt(3)/4)*(side*side);\n printf(\"perimeter is %d\\n\", perimeter);\n printf(\"area is %f\", area);\n return 0;\n}" }, { "code": null, "e": 1888, "s": 1854, "text": "perimeter is 15\narea is 10.825317" } ]
Roll In Animation Effect with CSS
To create a roll in animation effect with CSS, you can try to run the following code − Live Demo <html> <head> <style> .animated { background-image: url(/css/images/logo.png); background-repeat: no-repeat; background-position: left top; padding-top:95px; margin-bottom:60px; -webkit-animation-duration: 10s; animation-duration: 10s; -webkit-animation-fill-mode: both; animation-fill-mode: both; } @-webkit-keyframes rollIn { 0% { opacity: 0; -webkit-transform: translateX(-100%) rotate(-120deg); } 100% { opacity: 1; -webkit-transform: translateX(0px) rotate(0deg); } } @keyframes rollIn { 0% { opacity: 0; transform: translateX(-100%) rotate(-120deg); } 100% { opacity: 1; transform: translateX(0px) rotate(0deg); } } .rollIn { -webkit-animation-name: rollIn; animation-name: rollIn; } </style> </head> <body> <div id = "animated-example" class = "animated rollIn"></div> <button onclick = "myFunction()">Reload page</button> <script> function myFunction() { location.reload(); } </script> </body> </html>
[ { "code": null, "e": 1149, "s": 1062, "text": "To create a roll in animation effect with CSS, you can try to run the following code −" }, { "code": null, "e": 1159, "s": 1149, "text": "Live Demo" }, { "code": null, "e": 2570, "s": 1159, "text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n @-webkit-keyframes rollIn {\n 0% {\n opacity: 0;\n -webkit-transform: translateX(-100%) rotate(-120deg);\n }\n 100% {\n opacity: 1;\n -webkit-transform: translateX(0px) rotate(0deg);\n }\n }\n @keyframes rollIn {\n 0% {\n opacity: 0;\n transform: translateX(-100%) rotate(-120deg);\n }\n 100% {\n opacity: 1;\n transform: translateX(0px) rotate(0deg);\n } \n }\n .rollIn {\n -webkit-animation-name: rollIn;\n animation-name: rollIn;\n }\n </style>\n </head>\n\n <body>\n <div id = \"animated-example\" class = \"animated rollIn\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n </body>\n</html>" } ]
How to delete element from an array in MongoDB?
To delete element from an array, use $pull. Let us create a collection with documents − > db.demo279.insertOne({id:[101,103,105,110]}); { "acknowledged" : true, "insertedId" : ObjectId("5e490af7dd099650a5401a58") } > db.demo279.insertOne({id:[107,111,110]}); { "acknowledged" : true, "insertedId" : ObjectId("5e490b06dd099650a5401a59") } Display all documents from a collection with the help of find() method − > db.demo279.find(); This will produce the following output − { "_id" : ObjectId("5e490af7dd099650a5401a58"), "id" : [ 101, 103, 105, 110 ] } { "_id" : ObjectId("5e490b06dd099650a5401a59"), "id" : [ 107, 111, 110 ] } Following is the query to delete element from an array &minus'; > db.demo279.update({},{$pull:{id:110}},{multi:true}); WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 }) Display all documents from a collection with the help of find() method − > db.demo279.find(); This will produce the following output − { "_id" : ObjectId("5e490af7dd099650a5401a58"), "id" : [ 101, 103, 105 ] } { "_id" : ObjectId("5e490b06dd099650a5401a59"), "id" : [ 107, 111 ] }
[ { "code": null, "e": 1150, "s": 1062, "text": "To delete element from an array, use $pull. Let us create a collection with documents −" }, { "code": null, "e": 1412, "s": 1150, "text": "> db.demo279.insertOne({id:[101,103,105,110]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e490af7dd099650a5401a58\")\n}\n> db.demo279.insertOne({id:[107,111,110]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e490b06dd099650a5401a59\")\n}" }, { "code": null, "e": 1485, "s": 1412, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1506, "s": 1485, "text": "> db.demo279.find();" }, { "code": null, "e": 1547, "s": 1506, "text": "This will produce the following output −" }, { "code": null, "e": 1702, "s": 1547, "text": "{ \"_id\" : ObjectId(\"5e490af7dd099650a5401a58\"), \"id\" : [ 101, 103, 105, 110 ] }\n{ \"_id\" : ObjectId(\"5e490b06dd099650a5401a59\"), \"id\" : [ 107, 111, 110 ] }" }, { "code": null, "e": 1766, "s": 1702, "text": "Following is the query to delete element from an array &minus';" }, { "code": null, "e": 1887, "s": 1766, "text": "> db.demo279.update({},{$pull:{id:110}},{multi:true});\nWriteResult({ \"nMatched\" : 2, \"nUpserted\" : 0, \"nModified\" : 2 })" }, { "code": null, "e": 1960, "s": 1887, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1981, "s": 1960, "text": "> db.demo279.find();" }, { "code": null, "e": 2022, "s": 1981, "text": "This will produce the following output −" }, { "code": null, "e": 2167, "s": 2022, "text": "{ \"_id\" : ObjectId(\"5e490af7dd099650a5401a58\"), \"id\" : [ 101, 103, 105 ] }\n{ \"_id\" : ObjectId(\"5e490b06dd099650a5401a59\"), \"id\" : [ 107, 111 ] }" } ]
Dashboard KPI essential Template — Hands-on Tableau Data Science | Medium | Towards Data Science
Key Performance Indicators (KPIs) are the bricks of any Dashboard, in any Business domain. A smart way to make those bricks is developing a KPI template, which is a set of expressions and parameters that blend data to explain the Business. Ok, but how can we make a KPI template? In this article, I’m going to explain and show how to develop the underlying objects of a clean KPI visualization in a professional Dashboard. The idea is to build a KPI template that can be applied to any business domain. I will do it by Tableau, but it will be easily adaptable to other dashboarding tools such as Qlik or Power BI. If you wish to repeat the steps yourself in a demo style, you might want to create a Tableau Public login (for free), and download the dataset I used(link). If you read my other article “Inspiring Ideas for Dashboards Design” (link below), what I’ll explain here is how to exactly develop any of the KPIs shown in the Cockpit. medium.com For details about Tableau, I already talked about its Public version in the section “Reporting or Dashboarding: Tableau Public” of my other article linked below medium.com Our goal is to build all the objects to make a standard KPI template, by building its 3 core elements: KPI value, trend, and performance. For Example, the following visualization uses 8 times the template that we are going to develop. The input of our KPI Template is a dataset with a business measure expressed over time (e.g. the VALUE of month Sale Turnover, over ID_DATE). We want the KPI Template visualization to be dynamically responding to the selectors for Time and Performance scopes. The KPI Template’s output will need to provide 3 information a) KPI value of the business measure over for the selected period b) KPI performance defined as KPI value vs Benchmark c) KPI trend of the KPI over a sliding period of 1 year In the next 6 paragraphs, I will walk you through the actual step-by-step development of the KPI Template visualization. You can download the source dataset from this link. Create a Tableau workbook and configure the Data Source tab to connect to a Text file (the file is a .csv in the example). Once done, you should see the imported data: each row gives the Value of a business measure over time (e.g. it can be Profit, Margin,.., if you deal with the Sales domain, Net Promoter Score, Engagement Rate,.., in Digital Marketing, etc.). “Value” is the business measure, “Id Date” the date it’s referred to. The data types are chosen automatically, but you always need to check that. In this case, they are correct: # for the numeric columns and Date for “Id Date”. You’ll always need to check that and in case manually change the data type. We now need to create all the Tableau objects that will be the bricks of our visualization. It all begins by creating a Tableau Sheet, by the tabs at the bottom. A Tableau Sheet is the most detailed level of visualization in Tableau. It’s where you can define the objects containing the data expressions ( calculations, transformations, filtering, etc.) and the visualization (charts, views, maps, etc.). Usually, Dashboards are composed of several Tableau Sheets. On the left-hand side, you can see the 3 columns of your source file. Tableau already put some intelligence on them: it classified “Id Date” and “Id Row” in as Dimensions objects (in blue), and “Value” as a Measure (in green). Parameters can be used to propagate values towards Dimension or Masure objects. In Tableau (other tools are different), one of the ways to use a parameter is by setting its value by a selector. Another way is to store a constant value. For our KPI template, we decided to show 3 selectors: Current Month, Year, and Performance scope. Current Month: define it as a list of Integers, with values from 1 to 12. Current Year: define it as a list of integers, with the years you need (2018,2019,2020). Performance Scope: define it as a list of Strings with the performances you want to allow. In this template, we provide show 3 scopes, but you might want to add some more: Current month compared to a Target value Current month compared to the previous month Current month compared to the current month of last year Now that we created our 3 parameters, we can then build the actual user selectors: right-click on each parameter and select “Show Parameter”, so that they appear on your Sheet and can be changed. To display the selector as I did, you need to right-click on the parameter and select the Compact List view mode. Finally, we need to create a new parameter to define the Target value we want to use for the performance scope “current month vs Target value”. We can define it as 10000 (this could represent the desired monthly sale profit, the number of new customers, or any other target benchmark). Based on the selectors “Current Year” and “Current Month” defined above, we need to interpret the actual dates they represent, by building some dimensions, which I call the utility dimensions. Even if the user will select just a single pair “Current Year” and “Current Month”, those dimensions allow the calculations of several measures, each on a different time period. Create the following 4 object dimensions With the following expressions Date Current Month - Current Year = MAKEDATE([Current Year],[Current Month],1)Date Current Month - Previous Year = MAKEDATE([Current Year]-1,[Current Month],1)Date Next Month = DATEADD('month',1,[Date Current Month - Current Year])Date Previous Month= DATEADD('month',-1,[Date Current Month - Current Year]) Explanation: the function MAKEDATE builds a date based on the provided Year, Month, and Day. In our template, Year and Month are our Parameters, the day is set to 1. The function DATEADD increments (or decrements) the date provided. Here we calculate the dates of next month by adding 1 month to the current month. We then create some dimensions to nicely display the dates in a textual format such as We do so by creating the 2 following dimensions defined by the expressions below. Current Period Lable= LEFT(DATENAME(“month”, [Date Current Month — Current Year]),3) + “-” + RIGHT(DATENAME(“year”,[Date Current Month — Current Year]),2)Performance Reference Lable= CASE [Performance Scope]WHEN 'CurrentMonth_vs_PreviousMonth' THEN LEFT(DATENAME("month", [Date Previous Month]),3) + "-" + RIGHT(DATENAME("year",[Date Previous Month]),2)WHEN 'CurrentMonth_vs_PreviousYear' THEN LEFT(DATENAME("month", [Date Current Month - Previous Year]),3) + "-" + RIGHT(DATENAME("year",[Date Current Month - Previous Year]),2)WHEN 'CurrentMonth_vs_Target' THEN "Target" END As you can notice, they are based on the objects which we previously built, which in turn were built upon the Parameters. Here is the most interesting part: the actual KPI calculations. For any KPI we need 2 ingredients: a business metric, and a business rule to turn the measure into a KPI. E.g. from telco: the duration of a phone call would be the business metric, and the business rule for the KPI “Daily Average Duration” would be: average duration of the phone calls per day. In our KPI template, our business metric corresponds to the Tableau object “Value”, which represents the source column named Value. I chose as a business rule the total Value by month. The rule can be changed by changing the aggregation function. E.g. the Average amount per transaction would be the following: Let’s build the corresponding Tableau object: Why do we need 3 measures? Because we are considering 3 different periods: the current month, the previous month, the current month of the previous year. You’ll understand better the reason later when we’ll calculate the KPI performance. Their expressions are the following: KPI (Current Month)=SUM(IF (YEAR([Id Date]) = [Current Year] AND MONTH([Id Date]) = [Current Month]) THEN [Value] ELSE NULL END)KPI (Previous Month)=SUM(IF (YEAR([Id Date]) = YEAR([Date Previous Month]) AND MONTH([Id Date])= MONTH([Date Previous Month]) ) THEN [Value] ELSE NULL END)KPI (Current Month Previous Year)=SUM(IF (YEAR([Id Date]) = [Current Year] - 1 AND MONTH([Id Date]) = [Current Month]) THEN [Value] ELSE NULL END) Let’s explain the first expression KPI (Current Month), the others follow the same concepts. We need to keep the source “Value” that belongs to the Current Month and force it to NULL elsewhere. This filtering is done by the part of the expression highlighted in blue, which tests row by row our data source whether its date (“Id Date”) belongs to the “Current Year” and “Current Month” period. For instance, If the date Selector was set as April 2018, KPI would only consider the source data in green: The remaining part of the expression highlighted below aggregates all the Value in scope following the KPI definition (i.e. Sum). Finally, we can build another measure that reads the parameter “Performance Scope” previously built. Create the object with the expression: KPI (Performance Scope)=CASE [Performance Scope]WHEN 'CurrentMonth_vs_PreviousMonth' THEN [KPI (Current Month)]WHEN 'CurrentMonth_vs_PreviousYear' THEN [KPI (Current Month)]WHEN 'CurrentMonth_vs_Target' THEN [KPI (Current Month)]END You can see that depending on the Performance Scope selector, the object acts as a switch and selects one KPI(t). In our Template we decided to look at the Current Month only, so in any case our switch is on “KPI (Current Month)”, but you might want to extend that to other scopes (e.g. Current Year, Quarter, Week, etc.). To visualize the trend of our KPI, we want to display its values over a sliding year. To do so we can build the following object and expression, which leverages the dates we previously calculated. KPI Sliding Year=SUM(IF ([Id Date] > [Date Current Month - Previous Year] AND [Id Date] < [Date Next Month] ) THEN [Value] ELSE NULL END) To display the KPI performances, we need to compare the KPI on a time scope against a benchmark. For our KPI template, we have set 3 different benchmarks: a Target value, the KPI value of the previous month, and the same month of previous year. To allow the dynamic behavior of the References we need to build the following 4 objects, which I’ll explain below. KPI Target=[Target] This object is simply derived from the parameter Target previously created. KPI Reference (Performance Scope)=CASE [Performance Scope]WHEN 'CurrentMonth_vs_PreviousMonth' THEN [KPI (Previous Month)]WHEN 'CurrentMonth_vs_PreviousYear' THEN [KPI (Current Month Previous Year)]WHEN 'CurrentMonth_vs_Target' THEN [KPI Target]END Depending on the value of the selector Performance Scope, one of the 3 benchmarks KPI (Previous Month), KPI (Current Month Previous Year), or KPI Target is selected to be the reference. KPI vs Reference (Performance Scope)=[KPI (Performance Scope)] - [KPI Reference (Performance Scope)] This object compares the KPI for the selected scope towards the KPI Reference (Performance Scope), by calculating the difference. In other cases, the expression could also be a ratio or %. We then create another (identical) measure that will be used just to display its value in a different way. We will see exactly how to configure some additional properties when we’ll build the actual visualization. KPI vs Reference (Performance Scope) Sign=[KPI (Performance Scope)] - [KPI Reference (Performance Scope)] We now need to combine the Tableau Dimensions and Measure to make our dynamic KPI visualization. In short: we’ll combine the dimensions and measures into 5 Tableau Worksheets, define how to visualize each of them, and finally compose a Dashboard section using the Worksheets to present the 3 KPI’s essential elements: value, trend, and performance. (1) KPI Value (2) Caption (3) Period Lable (4) Sign of KPI value vs Reference (5) KPI Trend I’m going to present how to make each Worksheet here below. Let’s begin from the KPI value: you will need to drag en drop the object KPI (Performance Scope) as a Text (just drag and drop it in the Text mark, see the yellow arrow below). To format the text as I did, you need to click on the Text mark and set the properties as follows To show the $ symbol there are a few ways. One is right-click on the KPI (Performance Scope) object, Format, and edit the number format as follows: (2) Caption The Caption zone displays the comparison of KPI value vs Perfomance velue selected. You need to create a new Tableau Worksheet, drag and drop KPI vs Reference (Performance Scope) and Performance Reference Lable as a Tooltip (just drag and drop them in the Tooltip mark, see the orange arrow below). Make the “Caption” windows visible on the bottom side of your Tableau canvas, click the top menu “Worksheet”, and select “Show Caption”. Then double click on the Caption area and on “Insert”, to add the two objects as follows To set the format as displayed for KPI vs Reference (Performance Scope) you need to edit its the format, as follows The expression I used is ▲ +$#;▼ -$#;= The Period label shows which period we analyze and against which benchmark we compare. To build the visualization you need to create a new worksheet, and drag en drop the objects Performance Reference Lable and Current Period Lable as a Text (4) Sign of KPI value vs Reference To visually display the comparison KPI value vs Reference we can show its sign as a colored ▲or ▼. It says whether the current period was better (green ▲) or worse (red ▼) than the Reference. To implement that, create a new worksheet, then drag en drop the object KPI vs Reference (Performance Scope) Sign as a Text and also as a Color mark. To set the shapes, edit the format of the Text object, using the expression ▲;▼;= To set the color click on the Color tab, and select the Red-Green Diverging, centered on zero. This way positive values will be displayed in green, negative in red. (5) KPI Trend To show the last year's trend, create a new worksheet, drag and drop KPI Sliding Year in the zone Rows, and define the following expression in the Columns. DATETRUNC('month', [Id Date]) Then in the Marks editor select the “Area” and you’ll see something similar to the following. You should then customize color and hide axes labels to show exactly as above. All the worksheets you just created can be combined into a Dashboard (section). In a real-life dashboard, we would display many KPIs visualizations together, all based on the same template, to give harmony and coherence, so here we do the Demo with just one KPI, to present the concept. Let’s create a new dashboard (by click on the orange box below) and import all the worksheets we created (see the yellow box), and arrange them as follows If you try to change the selector's values you’ll see the KPI values and performance changing. You might think for just a single KPI visualization you had to build quite a lot of objects, right?. In a real-life Dashboard, we usually present many KPIs together (see image below), and all of them share the same parameters and utility dimensions. So the actual development you’ll need to do is less than half we did in this demo. Also, once you have your KPI template, you can create new ones by duplicating the measures we created through §4 and §5, and just replace the basic source measures and calculations, if based on different business rules. That makes the development quick and simple, so I have no doubts about the advantage you get by using this or similar temples, rather than build a custom set of objects for each visualization. In this story, I shared with you my way to build a KPI template visualization, through a Hands-on Tableau. KPI templates make dashboard development simpler, quicker, and easier to maintain, than unstructured development. The methodology is easily applicable to any other tools (e.g. Qlik, Power BI, etc.) and business domains, as long as we have a metric moving over time. I also provided the source data I used and described step-by-step how I implemented each part of the KPI template so that you can redo it yourself if you wish, regardless of your skill level. Feel free to subscribe to my “Sharing Data Knowledge” Newsletter.
[ { "code": null, "e": 451, "s": 171, "text": "Key Performance Indicators (KPIs) are the bricks of any Dashboard, in any Business domain. A smart way to make those bricks is developing a KPI template, which is a set of expressions and parameters that blend data to explain the Business. Ok, but how can we make a KPI template?" }, { "code": null, "e": 674, "s": 451, "text": "In this article, I’m going to explain and show how to develop the underlying objects of a clean KPI visualization in a professional Dashboard. The idea is to build a KPI template that can be applied to any business domain." }, { "code": null, "e": 942, "s": 674, "text": "I will do it by Tableau, but it will be easily adaptable to other dashboarding tools such as Qlik or Power BI. If you wish to repeat the steps yourself in a demo style, you might want to create a Tableau Public login (for free), and download the dataset I used(link)." }, { "code": null, "e": 1112, "s": 942, "text": "If you read my other article “Inspiring Ideas for Dashboards Design” (link below), what I’ll explain here is how to exactly develop any of the KPIs shown in the Cockpit." }, { "code": null, "e": 1123, "s": 1112, "text": "medium.com" }, { "code": null, "e": 1284, "s": 1123, "text": "For details about Tableau, I already talked about its Public version in the section “Reporting or Dashboarding: Tableau Public” of my other article linked below" }, { "code": null, "e": 1295, "s": 1284, "text": "medium.com" }, { "code": null, "e": 1433, "s": 1295, "text": "Our goal is to build all the objects to make a standard KPI template, by building its 3 core elements: KPI value, trend, and performance." }, { "code": null, "e": 1530, "s": 1433, "text": "For Example, the following visualization uses 8 times the template that we are going to develop." }, { "code": null, "e": 1672, "s": 1530, "text": "The input of our KPI Template is a dataset with a business measure expressed over time (e.g. the VALUE of month Sale Turnover, over ID_DATE)." }, { "code": null, "e": 1790, "s": 1672, "text": "We want the KPI Template visualization to be dynamically responding to the selectors for Time and Performance scopes." }, { "code": null, "e": 1851, "s": 1790, "text": "The KPI Template’s output will need to provide 3 information" }, { "code": null, "e": 1917, "s": 1851, "text": "a) KPI value of the business measure over for the selected period" }, { "code": null, "e": 1970, "s": 1917, "text": "b) KPI performance defined as KPI value vs Benchmark" }, { "code": null, "e": 2026, "s": 1970, "text": "c) KPI trend of the KPI over a sliding period of 1 year" }, { "code": null, "e": 2147, "s": 2026, "text": "In the next 6 paragraphs, I will walk you through the actual step-by-step development of the KPI Template visualization." }, { "code": null, "e": 2199, "s": 2147, "text": "You can download the source dataset from this link." }, { "code": null, "e": 2322, "s": 2199, "text": "Create a Tableau workbook and configure the Data Source tab to connect to a Text file (the file is a .csv in the example)." }, { "code": null, "e": 2563, "s": 2322, "text": "Once done, you should see the imported data: each row gives the Value of a business measure over time (e.g. it can be Profit, Margin,.., if you deal with the Sales domain, Net Promoter Score, Engagement Rate,.., in Digital Marketing, etc.)." }, { "code": null, "e": 2633, "s": 2563, "text": "“Value” is the business measure, “Id Date” the date it’s referred to." }, { "code": null, "e": 2709, "s": 2633, "text": "The data types are chosen automatically, but you always need to check that." }, { "code": null, "e": 2867, "s": 2709, "text": "In this case, they are correct: # for the numeric columns and Date for “Id Date”. You’ll always need to check that and in case manually change the data type." }, { "code": null, "e": 3029, "s": 2867, "text": "We now need to create all the Tableau objects that will be the bricks of our visualization. It all begins by creating a Tableau Sheet, by the tabs at the bottom." }, { "code": null, "e": 3332, "s": 3029, "text": "A Tableau Sheet is the most detailed level of visualization in Tableau. It’s where you can define the objects containing the data expressions ( calculations, transformations, filtering, etc.) and the visualization (charts, views, maps, etc.). Usually, Dashboards are composed of several Tableau Sheets." }, { "code": null, "e": 3559, "s": 3332, "text": "On the left-hand side, you can see the 3 columns of your source file. Tableau already put some intelligence on them: it classified “Id Date” and “Id Row” in as Dimensions objects (in blue), and “Value” as a Measure (in green)." }, { "code": null, "e": 3893, "s": 3559, "text": "Parameters can be used to propagate values towards Dimension or Masure objects. In Tableau (other tools are different), one of the ways to use a parameter is by setting its value by a selector. Another way is to store a constant value. For our KPI template, we decided to show 3 selectors: Current Month, Year, and Performance scope." }, { "code": null, "e": 3967, "s": 3893, "text": "Current Month: define it as a list of Integers, with values from 1 to 12." }, { "code": null, "e": 4056, "s": 3967, "text": "Current Year: define it as a list of integers, with the years you need (2018,2019,2020)." }, { "code": null, "e": 4228, "s": 4056, "text": "Performance Scope: define it as a list of Strings with the performances you want to allow. In this template, we provide show 3 scopes, but you might want to add some more:" }, { "code": null, "e": 4269, "s": 4228, "text": "Current month compared to a Target value" }, { "code": null, "e": 4314, "s": 4269, "text": "Current month compared to the previous month" }, { "code": null, "e": 4371, "s": 4314, "text": "Current month compared to the current month of last year" }, { "code": null, "e": 4567, "s": 4371, "text": "Now that we created our 3 parameters, we can then build the actual user selectors: right-click on each parameter and select “Show Parameter”, so that they appear on your Sheet and can be changed." }, { "code": null, "e": 4681, "s": 4567, "text": "To display the selector as I did, you need to right-click on the parameter and select the Compact List view mode." }, { "code": null, "e": 4967, "s": 4681, "text": "Finally, we need to create a new parameter to define the Target value we want to use for the performance scope “current month vs Target value”. We can define it as 10000 (this could represent the desired monthly sale profit, the number of new customers, or any other target benchmark)." }, { "code": null, "e": 5338, "s": 4967, "text": "Based on the selectors “Current Year” and “Current Month” defined above, we need to interpret the actual dates they represent, by building some dimensions, which I call the utility dimensions. Even if the user will select just a single pair “Current Year” and “Current Month”, those dimensions allow the calculations of several measures, each on a different time period." }, { "code": null, "e": 5379, "s": 5338, "text": "Create the following 4 object dimensions" }, { "code": null, "e": 5410, "s": 5379, "text": "With the following expressions" }, { "code": null, "e": 5718, "s": 5410, "text": "Date Current Month - Current Year = MAKEDATE([Current Year],[Current Month],1)Date Current Month - Previous Year = MAKEDATE([Current Year]-1,[Current Month],1)Date Next Month = DATEADD('month',1,[Date Current Month - Current Year])Date Previous Month= DATEADD('month',-1,[Date Current Month - Current Year])" }, { "code": null, "e": 5884, "s": 5718, "text": "Explanation: the function MAKEDATE builds a date based on the provided Year, Month, and Day. In our template, Year and Month are our Parameters, the day is set to 1." }, { "code": null, "e": 6033, "s": 5884, "text": "The function DATEADD increments (or decrements) the date provided. Here we calculate the dates of next month by adding 1 month to the current month." }, { "code": null, "e": 6120, "s": 6033, "text": "We then create some dimensions to nicely display the dates in a textual format such as" }, { "code": null, "e": 6168, "s": 6120, "text": "We do so by creating the 2 following dimensions" }, { "code": null, "e": 6202, "s": 6168, "text": "defined by the expressions below." }, { "code": null, "e": 6794, "s": 6202, "text": "Current Period Lable= LEFT(DATENAME(“month”, [Date Current Month — Current Year]),3) + “-” + RIGHT(DATENAME(“year”,[Date Current Month — Current Year]),2)Performance Reference Lable= CASE [Performance Scope]WHEN 'CurrentMonth_vs_PreviousMonth' THEN LEFT(DATENAME(\"month\", [Date Previous Month]),3) + \"-\" + RIGHT(DATENAME(\"year\",[Date Previous Month]),2)WHEN 'CurrentMonth_vs_PreviousYear' THEN LEFT(DATENAME(\"month\", [Date Current Month - Previous Year]),3) + \"-\" + RIGHT(DATENAME(\"year\",[Date Current Month - Previous Year]),2)WHEN 'CurrentMonth_vs_Target' THEN \"Target\" END" }, { "code": null, "e": 6916, "s": 6794, "text": "As you can notice, they are based on the objects which we previously built, which in turn were built upon the Parameters." }, { "code": null, "e": 7276, "s": 6916, "text": "Here is the most interesting part: the actual KPI calculations. For any KPI we need 2 ingredients: a business metric, and a business rule to turn the measure into a KPI. E.g. from telco: the duration of a phone call would be the business metric, and the business rule for the KPI “Daily Average Duration” would be: average duration of the phone calls per day." }, { "code": null, "e": 7461, "s": 7276, "text": "In our KPI template, our business metric corresponds to the Tableau object “Value”, which represents the source column named Value. I chose as a business rule the total Value by month." }, { "code": null, "e": 7587, "s": 7461, "text": "The rule can be changed by changing the aggregation function. E.g. the Average amount per transaction would be the following:" }, { "code": null, "e": 7633, "s": 7587, "text": "Let’s build the corresponding Tableau object:" }, { "code": null, "e": 7871, "s": 7633, "text": "Why do we need 3 measures? Because we are considering 3 different periods: the current month, the previous month, the current month of the previous year. You’ll understand better the reason later when we’ll calculate the KPI performance." }, { "code": null, "e": 7908, "s": 7871, "text": "Their expressions are the following:" }, { "code": null, "e": 8392, "s": 7908, "text": "KPI (Current Month)=SUM(IF (YEAR([Id Date]) = [Current Year] AND MONTH([Id Date]) = [Current Month]) THEN [Value] ELSE NULL END)KPI (Previous Month)=SUM(IF (YEAR([Id Date]) = YEAR([Date Previous Month]) AND MONTH([Id Date])= MONTH([Date Previous Month]) ) THEN [Value] ELSE NULL END)KPI (Current Month Previous Year)=SUM(IF (YEAR([Id Date]) = [Current Year] - 1 AND MONTH([Id Date]) = [Current Month]) THEN [Value] ELSE NULL END)" }, { "code": null, "e": 8586, "s": 8392, "text": "Let’s explain the first expression KPI (Current Month), the others follow the same concepts. We need to keep the source “Value” that belongs to the Current Month and force it to NULL elsewhere." }, { "code": null, "e": 8786, "s": 8586, "text": "This filtering is done by the part of the expression highlighted in blue, which tests row by row our data source whether its date (“Id Date”) belongs to the “Current Year” and “Current Month” period." }, { "code": null, "e": 8894, "s": 8786, "text": "For instance, If the date Selector was set as April 2018, KPI would only consider the source data in green:" }, { "code": null, "e": 9024, "s": 8894, "text": "The remaining part of the expression highlighted below aggregates all the Value in scope following the KPI definition (i.e. Sum)." }, { "code": null, "e": 9143, "s": 9024, "text": "Finally, we can build another measure that reads the parameter “Performance Scope” previously built. Create the object" }, { "code": null, "e": 9164, "s": 9143, "text": "with the expression:" }, { "code": null, "e": 9400, "s": 9164, "text": "KPI (Performance Scope)=CASE [Performance Scope]WHEN 'CurrentMonth_vs_PreviousMonth' THEN [KPI (Current Month)]WHEN 'CurrentMonth_vs_PreviousYear' THEN [KPI (Current Month)]WHEN 'CurrentMonth_vs_Target' THEN [KPI (Current Month)]END" }, { "code": null, "e": 9723, "s": 9400, "text": "You can see that depending on the Performance Scope selector, the object acts as a switch and selects one KPI(t). In our Template we decided to look at the Current Month only, so in any case our switch is on “KPI (Current Month)”, but you might want to extend that to other scopes (e.g. Current Year, Quarter, Week, etc.)." }, { "code": null, "e": 9920, "s": 9723, "text": "To visualize the trend of our KPI, we want to display its values over a sliding year. To do so we can build the following object and expression, which leverages the dates we previously calculated." }, { "code": null, "e": 10076, "s": 9920, "text": "KPI Sliding Year=SUM(IF ([Id Date] > [Date Current Month - Previous Year] AND [Id Date] < [Date Next Month] ) THEN [Value] ELSE NULL END)" }, { "code": null, "e": 10321, "s": 10076, "text": "To display the KPI performances, we need to compare the KPI on a time scope against a benchmark. For our KPI template, we have set 3 different benchmarks: a Target value, the KPI value of the previous month, and the same month of previous year." }, { "code": null, "e": 10437, "s": 10321, "text": "To allow the dynamic behavior of the References we need to build the following 4 objects, which I’ll explain below." }, { "code": null, "e": 10457, "s": 10437, "text": "KPI Target=[Target]" }, { "code": null, "e": 10533, "s": 10457, "text": "This object is simply derived from the parameter Target previously created." }, { "code": null, "e": 10797, "s": 10533, "text": "KPI Reference (Performance Scope)=CASE [Performance Scope]WHEN 'CurrentMonth_vs_PreviousMonth' THEN [KPI (Previous Month)]WHEN 'CurrentMonth_vs_PreviousYear' THEN [KPI (Current Month Previous Year)]WHEN 'CurrentMonth_vs_Target' THEN [KPI Target]END" }, { "code": null, "e": 10983, "s": 10797, "text": "Depending on the value of the selector Performance Scope, one of the 3 benchmarks KPI (Previous Month), KPI (Current Month Previous Year), or KPI Target is selected to be the reference." }, { "code": null, "e": 11084, "s": 10983, "text": "KPI vs Reference (Performance Scope)=[KPI (Performance Scope)] - [KPI Reference (Performance Scope)]" }, { "code": null, "e": 11273, "s": 11084, "text": "This object compares the KPI for the selected scope towards the KPI Reference (Performance Scope), by calculating the difference. In other cases, the expression could also be a ratio or %." }, { "code": null, "e": 11487, "s": 11273, "text": "We then create another (identical) measure that will be used just to display its value in a different way. We will see exactly how to configure some additional properties when we’ll build the actual visualization." }, { "code": null, "e": 11593, "s": 11487, "text": "KPI vs Reference (Performance Scope) Sign=[KPI (Performance Scope)] - [KPI Reference (Performance Scope)]" }, { "code": null, "e": 11690, "s": 11593, "text": "We now need to combine the Tableau Dimensions and Measure to make our dynamic KPI visualization." }, { "code": null, "e": 11942, "s": 11690, "text": "In short: we’ll combine the dimensions and measures into 5 Tableau Worksheets, define how to visualize each of them, and finally compose a Dashboard section using the Worksheets to present the 3 KPI’s essential elements: value, trend, and performance." }, { "code": null, "e": 11956, "s": 11942, "text": "(1) KPI Value" }, { "code": null, "e": 11968, "s": 11956, "text": "(2) Caption" }, { "code": null, "e": 11985, "s": 11968, "text": "(3) Period Lable" }, { "code": null, "e": 12020, "s": 11985, "text": "(4) Sign of KPI value vs Reference" }, { "code": null, "e": 12034, "s": 12020, "text": "(5) KPI Trend" }, { "code": null, "e": 12094, "s": 12034, "text": "I’m going to present how to make each Worksheet here below." }, { "code": null, "e": 12271, "s": 12094, "text": "Let’s begin from the KPI value: you will need to drag en drop the object KPI (Performance Scope) as a Text (just drag and drop it in the Text mark, see the yellow arrow below)." }, { "code": null, "e": 12369, "s": 12271, "text": "To format the text as I did, you need to click on the Text mark and set the properties as follows" }, { "code": null, "e": 12517, "s": 12369, "text": "To show the $ symbol there are a few ways. One is right-click on the KPI (Performance Scope) object, Format, and edit the number format as follows:" }, { "code": null, "e": 12529, "s": 12517, "text": "(2) Caption" }, { "code": null, "e": 12613, "s": 12529, "text": "The Caption zone displays the comparison of KPI value vs Perfomance velue selected." }, { "code": null, "e": 12828, "s": 12613, "text": "You need to create a new Tableau Worksheet, drag and drop KPI vs Reference (Performance Scope) and Performance Reference Lable as a Tooltip (just drag and drop them in the Tooltip mark, see the orange arrow below)." }, { "code": null, "e": 12965, "s": 12828, "text": "Make the “Caption” windows visible on the bottom side of your Tableau canvas, click the top menu “Worksheet”, and select “Show Caption”." }, { "code": null, "e": 13054, "s": 12965, "text": "Then double click on the Caption area and on “Insert”, to add the two objects as follows" }, { "code": null, "e": 13170, "s": 13054, "text": "To set the format as displayed for KPI vs Reference (Performance Scope) you need to edit its the format, as follows" }, { "code": null, "e": 13195, "s": 13170, "text": "The expression I used is" }, { "code": null, "e": 13209, "s": 13195, "text": "▲ +$#;▼ -$#;=" }, { "code": null, "e": 13296, "s": 13209, "text": "The Period label shows which period we analyze and against which benchmark we compare." }, { "code": null, "e": 13451, "s": 13296, "text": "To build the visualization you need to create a new worksheet, and drag en drop the objects Performance Reference Lable and Current Period Lable as a Text" }, { "code": null, "e": 13486, "s": 13451, "text": "(4) Sign of KPI value vs Reference" }, { "code": null, "e": 13678, "s": 13486, "text": "To visually display the comparison KPI value vs Reference we can show its sign as a colored ▲or ▼. It says whether the current period was better (green ▲) or worse (red ▼) than the Reference." }, { "code": null, "e": 13828, "s": 13678, "text": "To implement that, create a new worksheet, then drag en drop the object KPI vs Reference (Performance Scope) Sign as a Text and also as a Color mark." }, { "code": null, "e": 13904, "s": 13828, "text": "To set the shapes, edit the format of the Text object, using the expression" }, { "code": null, "e": 13910, "s": 13904, "text": "▲;▼;=" }, { "code": null, "e": 14075, "s": 13910, "text": "To set the color click on the Color tab, and select the Red-Green Diverging, centered on zero. This way positive values will be displayed in green, negative in red." }, { "code": null, "e": 14089, "s": 14075, "text": "(5) KPI Trend" }, { "code": null, "e": 14245, "s": 14089, "text": "To show the last year's trend, create a new worksheet, drag and drop KPI Sliding Year in the zone Rows, and define the following expression in the Columns." }, { "code": null, "e": 14275, "s": 14245, "text": "DATETRUNC('month', [Id Date])" }, { "code": null, "e": 14369, "s": 14275, "text": "Then in the Marks editor select the “Area” and you’ll see something similar to the following." }, { "code": null, "e": 14448, "s": 14369, "text": "You should then customize color and hide axes labels to show exactly as above." }, { "code": null, "e": 14735, "s": 14448, "text": "All the worksheets you just created can be combined into a Dashboard (section). In a real-life dashboard, we would display many KPIs visualizations together, all based on the same template, to give harmony and coherence, so here we do the Demo with just one KPI, to present the concept." }, { "code": null, "e": 14890, "s": 14735, "text": "Let’s create a new dashboard (by click on the orange box below) and import all the worksheets we created (see the yellow box), and arrange them as follows" }, { "code": null, "e": 14985, "s": 14890, "text": "If you try to change the selector's values you’ll see the KPI values and performance changing." }, { "code": null, "e": 15318, "s": 14985, "text": "You might think for just a single KPI visualization you had to build quite a lot of objects, right?. In a real-life Dashboard, we usually present many KPIs together (see image below), and all of them share the same parameters and utility dimensions. So the actual development you’ll need to do is less than half we did in this demo." }, { "code": null, "e": 15731, "s": 15318, "text": "Also, once you have your KPI template, you can create new ones by duplicating the measures we created through §4 and §5, and just replace the basic source measures and calculations, if based on different business rules. That makes the development quick and simple, so I have no doubts about the advantage you get by using this or similar temples, rather than build a custom set of objects for each visualization." }, { "code": null, "e": 15952, "s": 15731, "text": "In this story, I shared with you my way to build a KPI template visualization, through a Hands-on Tableau. KPI templates make dashboard development simpler, quicker, and easier to maintain, than unstructured development." }, { "code": null, "e": 16104, "s": 15952, "text": "The methodology is easily applicable to any other tools (e.g. Qlik, Power BI, etc.) and business domains, as long as we have a metric moving over time." }, { "code": null, "e": 16296, "s": 16104, "text": "I also provided the source data I used and described step-by-step how I implemented each part of the KPI template so that you can redo it yourself if you wish, regardless of your skill level." } ]
MongoDB – Multiply Operator ($mul)
10 May, 2020 MongoDB provides different types of field update operators to update the values of the fields of the documents and $mul operator is one of them. This operator is used to multiply the value of the field by a number. $mul operator only updates those fields whose value are of numeric type like int, float, etc. If the specified field is not present in the document, then this operator will add that field in the document and assign the value of that field to zero of the same numeric type as the multiplier. This operator is an atomic operation within a single document. In this operator, multiplication with values of mixed numeric types like 32-bit integer, 64-bit integer, float, etc., may result in conversion of numeric type. The following rules are applied in the multiplication with the values of mixed numeric types:32-bit Integer64-bit IntegerFloat32-bit Integer32-bit or 64-bit Integer64-bit IntegerFloat64-bit Integer64-bit Integer64-bit IntegerFloatFloatFloatFloatFloat $mul operator can also work with embedded/nested documents or arrays. You can use this operator in methods like update(), findAndModify(), etc., according to your requirements. Syntax: { $mul: { <field1>: <number1>, <field2>: <number2>, ... } } Here, <field> can specify with dot notation in embedded/nested documents. In the following examples, we are working with: Database: FruitsCollection: DetailsDocument: two documents that contain the details of the fruits in the form of field-value pairs. In this example, we are multiplying the value of price field by 2.10 in the document who matches the specified condition, i.e., name = mango. db.Details.update({name: "mango"}, {$mul: {price: NumberDecimal("2.10")}}) In this example, we are multiplying the value of quantity.tQuantity field by 3 in the document who matches the specified condition, i.e., name = mango. db.Details.update({name: "mango"}, {$mul: {"quantity.tQuantity": 3}}) In this example, we are applying $mul operator to a non- existing field in the document who matches the specified condition, i.e., name = apple. db.Details.update({name: "apple"}, {$mul: {"batchNumber":NumberInt(230)}}) In this example, we are multiplying the value(float type) of price field in the document who matches the specified condition, i.e., name = apple. db.Details.update({name: "apple"}, {$mul: {price: NumberDecimal(5)}}) MongoDB MongoDB-operators MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Spring Boot JpaRepository with Example Mongoose Populate() Method MongoDB - db.collection.Find() Method Aggregation in MongoDB How to connect MongoDB with ReactJS ? Upsert in MongoDB MongoDB - Check the existence of the fields in the specified collection How to build a basic CRUD app with Node.js and ReactJS ? MongoDB: An introduction MongoDB - limit() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 243, "s": 28, "text": "MongoDB provides different types of field update operators to update the values of the fields of the documents and $mul operator is one of them. This operator is used to multiply the value of the field by a number." }, { "code": null, "e": 337, "s": 243, "text": "$mul operator only updates those fields whose value are of numeric type like int, float, etc." }, { "code": null, "e": 534, "s": 337, "text": "If the specified field is not present in the document, then this operator will add that field in the document and assign the value of that field to zero of the same numeric type as the multiplier." }, { "code": null, "e": 597, "s": 534, "text": "This operator is an atomic operation within a single document." }, { "code": null, "e": 1008, "s": 597, "text": "In this operator, multiplication with values of mixed numeric types like 32-bit integer, 64-bit integer, float, etc., may result in conversion of numeric type. The following rules are applied in the multiplication with the values of mixed numeric types:32-bit Integer64-bit IntegerFloat32-bit Integer32-bit or 64-bit Integer64-bit IntegerFloat64-bit Integer64-bit Integer64-bit IntegerFloatFloatFloatFloatFloat" }, { "code": null, "e": 1185, "s": 1008, "text": "$mul operator can also work with embedded/nested documents or arrays. You can use this operator in methods like update(), findAndModify(), etc., according to your requirements." }, { "code": null, "e": 1193, "s": 1185, "text": "Syntax:" }, { "code": null, "e": 1253, "s": 1193, "text": "{ $mul: { <field1>: <number1>, <field2>: <number2>, ... } }" }, { "code": null, "e": 1327, "s": 1253, "text": "Here, <field> can specify with dot notation in embedded/nested documents." }, { "code": null, "e": 1375, "s": 1327, "text": "In the following examples, we are working with:" }, { "code": null, "e": 1507, "s": 1375, "text": "Database: FruitsCollection: DetailsDocument: two documents that contain the details of the fruits in the form of field-value pairs." }, { "code": null, "e": 1649, "s": 1507, "text": "In this example, we are multiplying the value of price field by 2.10 in the document who matches the specified condition, i.e., name = mango." }, { "code": "db.Details.update({name: \"mango\"}, {$mul: {price: NumberDecimal(\"2.10\")}})", "e": 1724, "s": 1649, "text": null }, { "code": null, "e": 1876, "s": 1724, "text": "In this example, we are multiplying the value of quantity.tQuantity field by 3 in the document who matches the specified condition, i.e., name = mango." }, { "code": "db.Details.update({name: \"mango\"}, {$mul: {\"quantity.tQuantity\": 3}})", "e": 1946, "s": 1876, "text": null }, { "code": null, "e": 2091, "s": 1946, "text": "In this example, we are applying $mul operator to a non- existing field in the document who matches the specified condition, i.e., name = apple." }, { "code": "db.Details.update({name: \"apple\"}, {$mul: {\"batchNumber\":NumberInt(230)}})", "e": 2166, "s": 2091, "text": null }, { "code": null, "e": 2312, "s": 2166, "text": "In this example, we are multiplying the value(float type) of price field in the document who matches the specified condition, i.e., name = apple." }, { "code": "db.Details.update({name: \"apple\"}, {$mul: {price: NumberDecimal(5)}})", "e": 2382, "s": 2312, "text": null }, { "code": null, "e": 2390, "s": 2382, "text": "MongoDB" }, { "code": null, "e": 2408, "s": 2390, "text": "MongoDB-operators" }, { "code": null, "e": 2416, "s": 2408, "text": "MongoDB" }, { "code": null, "e": 2514, "s": 2416, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2553, "s": 2514, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 2580, "s": 2553, "text": "Mongoose Populate() Method" }, { "code": null, "e": 2618, "s": 2580, "text": "MongoDB - db.collection.Find() Method" }, { "code": null, "e": 2641, "s": 2618, "text": "Aggregation in MongoDB" }, { "code": null, "e": 2679, "s": 2641, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 2697, "s": 2679, "text": "Upsert in MongoDB" }, { "code": null, "e": 2769, "s": 2697, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 2826, "s": 2769, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 2851, "s": 2826, "text": "MongoDB: An introduction" } ]
Spy Number (Sum and Products of Digits are same)
01 Mar, 2021 A number is said to be a Spy number if the sum of all the digits is equal to the product of all digits. Examples : Input : 1412 Explanation : sum = (1 + 4 + 1 + 2) = 8 product = (1 * 4 * 1 * 2) = 8 since, sum == product == 8 Output : Spy Number Input : 132 Explanation : sum = (1 + 3 + 2) = 6 product = (1 * 3 * 2) = 6 since, sum == product == 6 Output : Spy Number C++ Java Python3 C# PHP Javascript // CPP program to check// a spy number#include <bits/stdc++.h>using namespace std; // Function to// check spy numberbool checkSpy(int num){ int digit, sum = 0, product = 1; while (num > 0) { digit = num % 10; // getting sum of digits sum += digit; // getting product of digits product *= digit; num = num / 10; } if (sum == product) return true; else return false;} // Driver codeint main(){ int num = 1412; if (checkSpy(num)) cout << "The number is " << "a Spy number" << endl; else cout << "The number is " << "NOT a spy number" << endl; return 0;} // Java program to// check Spy numberimport java.util.*; class GFG{ // boolean function to // check Spy number static boolean checkSpy(int input) { int digit, sum = 0, product = 1; while (input > 0) { digit = input % 10; // getting the // sum of digits sum += digit; // getting the product // of digits product *= digit; input = input / 10; } // Comparing the // sum and product if (sum == product) return true; else return false; } // Driver code public static void main(String args[]) { int input = 1412; if (checkSpy(input)) System.out.println("The number is "+ "a Spy number"); else System.out.println("The number is "+ "NOT a Spy number"); }} # Python program to check# Spy number # Function to check# Spy numberdef checkSpy(num): sums = 0 product = 1 while num>0: digit = num % 10 # getting the # sum of digits sums = sums + digit # getting the product # of digits product = product * digit num = num // 10 if sums == product: return True else: return False # Driver Codenum = 1412if (checkSpy(num)): print("The number is a Spy Number")else: print("The number is NOT a spy number") // C# program to check// Spy numberusing System; class GFG{ // boolean function to // check Spy number static bool checkSpy(int input) { int digit, sum = 0, product = 1; while (input > 0) { digit = input % 10; // getting the sum // of digits sum += digit; // getting the product // of digits product *= digit; input = input / 10; } // Comparing the sum // and product if (sum == product) return true; else return false; } // Driver code public static void Main() { int input = 1412; if (checkSpy(input)) Console.WriteLine("The number is " + "a Spy number"); else Console.WriteLine("The number is " + "NOT a Spy number"); }} // This code is Contributed by vt_m. <?php// PHP program to check// a spy number // Function to check// spy numberfunction checkSpy($num){ $digit; $sum = 0; $product = 1; while ($num > 0) { $digit = $num % 10; // getting sum // of digits $sum += $digit; // getting product // of digits $product *= $digit; $num = $num / 10; } if ($sum == $product) return 1; else return -1;} // Driver code$num = 1412;if (checkSpy($num)) echo "The number is a ". "Spy number","\n"; else echo "The number is NOT ". "a spy number","\n"; // This code is contributed by ajit.?> <script> // Javascript program to check// a spy number // Function to// check spy numberfunction checkSpy(num){ let digit, sum = 0, product = 1; while (num > 0) { digit = num % 10; // getting sum of digits sum += digit; // getting product of digits product *= digit; num = Math.floor(num / 10); } if (sum == product) return true; else return false;} // Driver code let num = 1412; if (checkSpy(num)) document.write("The number is " + "a Spy number" + "<br>"); else document.write("The number is " + "NOT a spy number" + "<br>"); // This code is contributed by Mayank Tyagi </script> Output : The number is a Spy number This article is contributed by Chinmoy Lenka. 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. jit_t mayanktyagi1709 number-digits series School Programming series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Mar, 2021" }, { "code": null, "e": 145, "s": 28, "text": "A number is said to be a Spy number if the sum of all the digits is equal to the product of all digits. Examples : " }, { "code": null, "e": 399, "s": 145, "text": "Input : 1412\nExplanation : \nsum = (1 + 4 + 1 + 2) = 8\nproduct = (1 * 4 * 1 * 2) = 8\nsince, sum == product == 8\nOutput : Spy Number\n\nInput : 132\nExplanation : \nsum = (1 + 3 + 2) = 6\nproduct = (1 * 3 * 2) = 6\nsince, sum == product == 6\nOutput : Spy Number" }, { "code": null, "e": 407, "s": 403, "text": "C++" }, { "code": null, "e": 412, "s": 407, "text": "Java" }, { "code": null, "e": 420, "s": 412, "text": "Python3" }, { "code": null, "e": 423, "s": 420, "text": "C#" }, { "code": null, "e": 427, "s": 423, "text": "PHP" }, { "code": null, "e": 438, "s": 427, "text": "Javascript" }, { "code": "// CPP program to check// a spy number#include <bits/stdc++.h>using namespace std; // Function to// check spy numberbool checkSpy(int num){ int digit, sum = 0, product = 1; while (num > 0) { digit = num % 10; // getting sum of digits sum += digit; // getting product of digits product *= digit; num = num / 10; } if (sum == product) return true; else return false;} // Driver codeint main(){ int num = 1412; if (checkSpy(num)) cout << \"The number is \" << \"a Spy number\" << endl; else cout << \"The number is \" << \"NOT a spy number\" << endl; return 0;}", "e": 1167, "s": 438, "text": null }, { "code": "// Java program to// check Spy numberimport java.util.*; class GFG{ // boolean function to // check Spy number static boolean checkSpy(int input) { int digit, sum = 0, product = 1; while (input > 0) { digit = input % 10; // getting the // sum of digits sum += digit; // getting the product // of digits product *= digit; input = input / 10; } // Comparing the // sum and product if (sum == product) return true; else return false; } // Driver code public static void main(String args[]) { int input = 1412; if (checkSpy(input)) System.out.println(\"The number is \"+ \"a Spy number\"); else System.out.println(\"The number is \"+ \"NOT a Spy number\"); }}", "e": 2169, "s": 1167, "text": null }, { "code": "# Python program to check# Spy number # Function to check# Spy numberdef checkSpy(num): sums = 0 product = 1 while num>0: digit = num % 10 # getting the # sum of digits sums = sums + digit # getting the product # of digits product = product * digit num = num // 10 if sums == product: return True else: return False # Driver Codenum = 1412if (checkSpy(num)): print(\"The number is a Spy Number\")else: print(\"The number is NOT a spy number\")", "e": 2727, "s": 2169, "text": null }, { "code": "// C# program to check// Spy numberusing System; class GFG{ // boolean function to // check Spy number static bool checkSpy(int input) { int digit, sum = 0, product = 1; while (input > 0) { digit = input % 10; // getting the sum // of digits sum += digit; // getting the product // of digits product *= digit; input = input / 10; } // Comparing the sum // and product if (sum == product) return true; else return false; } // Driver code public static void Main() { int input = 1412; if (checkSpy(input)) Console.WriteLine(\"The number is \" + \"a Spy number\"); else Console.WriteLine(\"The number is \" + \"NOT a Spy number\"); }} // This code is Contributed by vt_m.", "e": 3702, "s": 2727, "text": null }, { "code": "<?php// PHP program to check// a spy number // Function to check// spy numberfunction checkSpy($num){ $digit; $sum = 0; $product = 1; while ($num > 0) { $digit = $num % 10; // getting sum // of digits $sum += $digit; // getting product // of digits $product *= $digit; $num = $num / 10; } if ($sum == $product) return 1; else return -1;} // Driver code$num = 1412;if (checkSpy($num)) echo \"The number is a \". \"Spy number\",\"\\n\"; else echo \"The number is NOT \". \"a spy number\",\"\\n\"; // This code is contributed by ajit.?>", "e": 4364, "s": 3702, "text": null }, { "code": "<script> // Javascript program to check// a spy number // Function to// check spy numberfunction checkSpy(num){ let digit, sum = 0, product = 1; while (num > 0) { digit = num % 10; // getting sum of digits sum += digit; // getting product of digits product *= digit; num = Math.floor(num / 10); } if (sum == product) return true; else return false;} // Driver code let num = 1412; if (checkSpy(num)) document.write(\"The number is \" + \"a Spy number\" + \"<br>\"); else document.write(\"The number is \" + \"NOT a spy number\" + \"<br>\"); // This code is contributed by Mayank Tyagi </script>", "e": 5124, "s": 4364, "text": null }, { "code": null, "e": 5135, "s": 5124, "text": "Output : " }, { "code": null, "e": 5162, "s": 5135, "text": "The number is a Spy number" }, { "code": null, "e": 5588, "s": 5162, "text": "This article is contributed by Chinmoy Lenka. 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. " }, { "code": null, "e": 5594, "s": 5588, "text": "jit_t" }, { "code": null, "e": 5610, "s": 5594, "text": "mayanktyagi1709" }, { "code": null, "e": 5624, "s": 5610, "text": "number-digits" }, { "code": null, "e": 5631, "s": 5624, "text": "series" }, { "code": null, "e": 5650, "s": 5631, "text": "School Programming" }, { "code": null, "e": 5657, "s": 5650, "text": "series" } ]
Files copy() Method in Java with Examples
10 Jun, 2022 The copy() method of java.nio.file.Files Class is used to copy bytes from a file to I/O streams or from I/O streams to a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files. Methods: Based on the type of arguments passed, the Files class provides 3 types of copy() method. Using copy(InputStream in, Path target, CopyOption... options) MethodUsing copy(Path source, OutputStream out) MethodUsing copy(Path source, Path target, CopyOption... options) Method Using copy(InputStream in, Path target, CopyOption... options) Method Using copy(Path source, OutputStream out) Method Using copy(Path source, Path target, CopyOption... options) Method Method 1: Using copy(InputStream in, Path target, CopyOption... options) Method This method is used to copy all bytes from an input stream to a file. Parameters: in: The input stream whose the data will be copied target: The path of the file where data will be copied options: Options describing the ways in which the data will be copied Return Type: Number of copied bytes Exceptions: IOException: If while reading or writing an error occurred FileAlreadyExistsException: If the target file already exists and can not be replaced DirectoryNotEmptyException: If the target file can not be replaced because it is a non-empty directory UnsupportedOperationException: If the way of copying described by an option is not supported SecurityException: If the write access to the target file is denied by the security manager Implementation: Example Java // Impoerting classes from java.nio package as// this package is responsible for network linkingimport java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.StandardCopyOption; // Main Classpublic class GFG { // Main driver method public static void main(String[] args) { // Input custom string String text = "geeksforgeeks"; // Path of the file where data is to be copied Path path = (Path)Paths.get("/usr", "local", "bin", "fileIn.txt"); System.out.println("Path of target file: " + path.toString()); // Byte stream whose data is to be copied InputStream in = new ByteArrayInputStream(text.getBytes()); // Try block to check for exceptions try { // Printing number of copied bytes System.out.println( "Number of bytes copied: " + Files.copy( in, path, StandardCopyOption.REPLACE_EXISTING)); } // Catch block to handle the exceptions catch (IOException e) { // Print the line number where exception occurred e.printStackTrace(); } }} Output: Path of target file: /usr/local/bin/fileIn.txt Number of bytes copied: 13 Method 2: Using copy(Path source, OutputStream out) Method This method is used to copy all bytes from a file to an output stream. Parameters: It takes two namely source: The path of the file whose data will be copied out: The output stream where the copied data will be written Return Type: Number of copied bytes Exceptions: IOException: If while reading or writing an error occurred SecurityException: If the read access to the target file is denied by the security manager Implementation: Example Java // Impoerting classes from java.nio package as// this package is responsible for network linkingimport java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.OutputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths; // Main Classpublic class GFG { // Main driver method public static void main(String[] args) { // Path of file whose data is to be copied Path path = (Path)Paths.get("/usr", "local", "bin", "fileOut.txt"); // Getting the path of source file System.out.println("Path of source file: " + path.toString()); // Output stream where data is to written OutputStream out = new ByteArrayOutputStream(); // Try block to check for exceptions try { // Printing number of copied bytes System.out.println("Number of bytes copied: " + Files.copy(path, out)); } // Catch block to handle the exception catch (IOException e) { // Print the line number where exception occurred e.printStackTrace(); } }} Output: Path of source file: /usr/local/bin/fileOut.txt Number of bytes copied: 13 Method 3: Using copy(Path source, Path target, CopyOption... options) Method This method is used to copy a file to a target file. Parameters: source: The path of the file whose data will be copied target: The path of the file where data will be copied options: Options describing the ways in which the data will be copied Return Type: The path to the file where data is copied Exceptions: IOException: If while reading or writing an error occurred FileAlreadyExistsException: If the target file already exists and can not be replaced DirectoryNotEmptyException: If the target file can not be replaced because it is a non-empty directory UnsupportedOperationException: If the way of copying described by an option is not supported SecurityException: If the write access to the target file is denied by the security manager Implementation: Example Java // Impoerting classes from java.nio package as// this package is responsible for network linkingimport java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.StandardCopyOption; // Main Classpublic class GFG { // Main driver method public static void main(String[] args) { // Path of file where data is to copied Path pathIn = (Path)Paths.get("/usr", "local", "bin", "fileIn.txt"); // Path of file whose data is to be copied Path pathOut = (Path)Paths.get( "/usr", "local", "bin", "fileOut.txt"); System.out.println("Path of target file: " + pathIn.toString()); System.out.println("Path of source file: " + pathOut.toString()); // Try block to check for exceptions try { // Printing number of bytes copied System.out.println( "Number of bytes copied: " + Files.copy( pathOut, pathIn, StandardCopyOption.REPLACE_EXISTING)); } // Catch block to handle the exceptions catch (IOException e) { // Print the line number where exception occurred e.printStackTrace(); } }} Output: Path of target file: /usr/local/bin/fileIn.txt Path of source file: /usr/local/bin/fileOut.txt Number of bytes copied: 13 gabaa406 nikhatkhan11 Java-Files Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2022" }, { "code": null, "e": 267, "s": 28, "text": "The copy() method of java.nio.file.Files Class is used to copy bytes from a file to I/O streams or from I/O streams to a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files." }, { "code": null, "e": 366, "s": 267, "text": "Methods: Based on the type of arguments passed, the Files class provides 3 types of copy() method." }, { "code": null, "e": 550, "s": 366, "text": "Using copy(InputStream in, Path target, CopyOption... options) MethodUsing copy(Path source, OutputStream out) MethodUsing copy(Path source, Path target, CopyOption... options) Method" }, { "code": null, "e": 620, "s": 550, "text": "Using copy(InputStream in, Path target, CopyOption... options) Method" }, { "code": null, "e": 669, "s": 620, "text": "Using copy(Path source, OutputStream out) Method" }, { "code": null, "e": 736, "s": 669, "text": "Using copy(Path source, Path target, CopyOption... options) Method" }, { "code": null, "e": 816, "s": 736, "text": "Method 1: Using copy(InputStream in, Path target, CopyOption... options) Method" }, { "code": null, "e": 887, "s": 816, "text": " This method is used to copy all bytes from an input stream to a file." }, { "code": null, "e": 899, "s": 887, "text": "Parameters:" }, { "code": null, "e": 950, "s": 899, "text": "in: The input stream whose the data will be copied" }, { "code": null, "e": 1005, "s": 950, "text": "target: The path of the file where data will be copied" }, { "code": null, "e": 1075, "s": 1005, "text": "options: Options describing the ways in which the data will be copied" }, { "code": null, "e": 1111, "s": 1075, "text": "Return Type: Number of copied bytes" }, { "code": null, "e": 1123, "s": 1111, "text": "Exceptions:" }, { "code": null, "e": 1182, "s": 1123, "text": "IOException: If while reading or writing an error occurred" }, { "code": null, "e": 1268, "s": 1182, "text": "FileAlreadyExistsException: If the target file already exists and can not be replaced" }, { "code": null, "e": 1371, "s": 1268, "text": "DirectoryNotEmptyException: If the target file can not be replaced because it is a non-empty directory" }, { "code": null, "e": 1464, "s": 1371, "text": "UnsupportedOperationException: If the way of copying described by an option is not supported" }, { "code": null, "e": 1556, "s": 1464, "text": "SecurityException: If the write access to the target file is denied by the security manager" }, { "code": null, "e": 1572, "s": 1556, "text": "Implementation:" }, { "code": null, "e": 1580, "s": 1572, "text": "Example" }, { "code": null, "e": 1585, "s": 1580, "text": "Java" }, { "code": "// Impoerting classes from java.nio package as// this package is responsible for network linkingimport java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.StandardCopyOption; // Main Classpublic class GFG { // Main driver method public static void main(String[] args) { // Input custom string String text = \"geeksforgeeks\"; // Path of the file where data is to be copied Path path = (Path)Paths.get(\"/usr\", \"local\", \"bin\", \"fileIn.txt\"); System.out.println(\"Path of target file: \" + path.toString()); // Byte stream whose data is to be copied InputStream in = new ByteArrayInputStream(text.getBytes()); // Try block to check for exceptions try { // Printing number of copied bytes System.out.println( \"Number of bytes copied: \" + Files.copy( in, path, StandardCopyOption.REPLACE_EXISTING)); } // Catch block to handle the exceptions catch (IOException e) { // Print the line number where exception occurred e.printStackTrace(); } }}", "e": 2945, "s": 1585, "text": null }, { "code": null, "e": 2954, "s": 2945, "text": " Output:" }, { "code": null, "e": 3028, "s": 2954, "text": "Path of target file: /usr/local/bin/fileIn.txt\nNumber of bytes copied: 13" }, { "code": null, "e": 3087, "s": 3028, "text": "Method 2: Using copy(Path source, OutputStream out) Method" }, { "code": null, "e": 3159, "s": 3087, "text": "This method is used to copy all bytes from a file to an output stream. " }, { "code": null, "e": 3192, "s": 3159, "text": "Parameters: It takes two namely " }, { "code": null, "e": 3247, "s": 3192, "text": "source: The path of the file whose data will be copied" }, { "code": null, "e": 3308, "s": 3247, "text": "out: The output stream where the copied data will be written" }, { "code": null, "e": 3344, "s": 3308, "text": "Return Type: Number of copied bytes" }, { "code": null, "e": 3357, "s": 3344, "text": "Exceptions: " }, { "code": null, "e": 3416, "s": 3357, "text": "IOException: If while reading or writing an error occurred" }, { "code": null, "e": 3508, "s": 3416, "text": "SecurityException: If the read access to the target file is denied by the security manager " }, { "code": null, "e": 3524, "s": 3508, "text": "Implementation:" }, { "code": null, "e": 3532, "s": 3524, "text": "Example" }, { "code": null, "e": 3537, "s": 3532, "text": "Java" }, { "code": "// Impoerting classes from java.nio package as// this package is responsible for network linkingimport java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.OutputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths; // Main Classpublic class GFG { // Main driver method public static void main(String[] args) { // Path of file whose data is to be copied Path path = (Path)Paths.get(\"/usr\", \"local\", \"bin\", \"fileOut.txt\"); // Getting the path of source file System.out.println(\"Path of source file: \" + path.toString()); // Output stream where data is to written OutputStream out = new ByteArrayOutputStream(); // Try block to check for exceptions try { // Printing number of copied bytes System.out.println(\"Number of bytes copied: \" + Files.copy(path, out)); } // Catch block to handle the exception catch (IOException e) { // Print the line number where exception occurred e.printStackTrace(); } }}", "e": 4729, "s": 3537, "text": null }, { "code": null, "e": 4738, "s": 4729, "text": " Output:" }, { "code": null, "e": 4813, "s": 4738, "text": "Path of source file: /usr/local/bin/fileOut.txt\nNumber of bytes copied: 13" }, { "code": null, "e": 4891, "s": 4813, "text": " Method 3: Using copy(Path source, Path target, CopyOption... options) Method" }, { "code": null, "e": 4944, "s": 4891, "text": "This method is used to copy a file to a target file." }, { "code": null, "e": 4956, "s": 4944, "text": "Parameters:" }, { "code": null, "e": 5011, "s": 4956, "text": "source: The path of the file whose data will be copied" }, { "code": null, "e": 5066, "s": 5011, "text": "target: The path of the file where data will be copied" }, { "code": null, "e": 5136, "s": 5066, "text": "options: Options describing the ways in which the data will be copied" }, { "code": null, "e": 5192, "s": 5136, "text": " Return Type: The path to the file where data is copied" }, { "code": null, "e": 5205, "s": 5192, "text": "Exceptions: " }, { "code": null, "e": 5264, "s": 5205, "text": "IOException: If while reading or writing an error occurred" }, { "code": null, "e": 5350, "s": 5264, "text": "FileAlreadyExistsException: If the target file already exists and can not be replaced" }, { "code": null, "e": 5453, "s": 5350, "text": "DirectoryNotEmptyException: If the target file can not be replaced because it is a non-empty directory" }, { "code": null, "e": 5546, "s": 5453, "text": "UnsupportedOperationException: If the way of copying described by an option is not supported" }, { "code": null, "e": 5638, "s": 5546, "text": "SecurityException: If the write access to the target file is denied by the security manager" }, { "code": null, "e": 5654, "s": 5638, "text": "Implementation:" }, { "code": null, "e": 5662, "s": 5654, "text": "Example" }, { "code": null, "e": 5667, "s": 5662, "text": "Java" }, { "code": "// Impoerting classes from java.nio package as// this package is responsible for network linkingimport java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.StandardCopyOption; // Main Classpublic class GFG { // Main driver method public static void main(String[] args) { // Path of file where data is to copied Path pathIn = (Path)Paths.get(\"/usr\", \"local\", \"bin\", \"fileIn.txt\"); // Path of file whose data is to be copied Path pathOut = (Path)Paths.get( \"/usr\", \"local\", \"bin\", \"fileOut.txt\"); System.out.println(\"Path of target file: \" + pathIn.toString()); System.out.println(\"Path of source file: \" + pathOut.toString()); // Try block to check for exceptions try { // Printing number of bytes copied System.out.println( \"Number of bytes copied: \" + Files.copy( pathOut, pathIn, StandardCopyOption.REPLACE_EXISTING)); } // Catch block to handle the exceptions catch (IOException e) { // Print the line number where exception occurred e.printStackTrace(); } }}", "e": 7013, "s": 5667, "text": null }, { "code": null, "e": 7022, "s": 7013, "text": " Output:" }, { "code": null, "e": 7145, "s": 7022, "text": "Path of target file: /usr/local/bin/fileIn.txt\nPath of source file: /usr/local/bin/fileOut.txt\nNumber of bytes copied: 13 " }, { "code": null, "e": 7154, "s": 7145, "text": "gabaa406" }, { "code": null, "e": 7167, "s": 7154, "text": "nikhatkhan11" }, { "code": null, "e": 7178, "s": 7167, "text": "Java-Files" }, { "code": null, "e": 7183, "s": 7178, "text": "Java" }, { "code": null, "e": 7188, "s": 7183, "text": "Java" } ]
Introduction to Solidity
11 May, 2022 Solidity is a brand-new programming language created by the Ethereum which is the second-largest market of cryptocurrency by capitalization, released in the year 2015 led by Christian Reitwiessner. Some key features of solidity are listed below: Solidity is a high-level programming language designed for implementing smart contracts. It is statically-typed object-oriented(contract-oriented) language. Solidity is highly influenced by Python, c++, and JavaScript which runs on the Ethereum Virtual Machine(EVM). Solidity supports complex user-defined programming, libraries and inheritance. Solidity is primary language for blockchains running platforms. Solidity can be used to creating contracts like voting, blind auctions, crowdfunding, multi-signature wallets, etc. Ethereum is a decentralized open-source platform based on blockchain domain, used to run smart contracts i.e. applications that execute the program exactly as it was programmed without the possibility of any fraud, interference from a third party, censorship, or downtime. It serves a platform for nearly 2,60,000 different cryptocurrencies. Ether is a cryptocurrency generated by ethereum miners, used to reward for the computations performed to secure the blockchain. Ethereum Virtual Machine abbreviated as EVM is a runtime environment for executing smart contracts in ethereum. It focuses widely on providing security and execution of untrusted code using an international network of public nodes. EVM is specialized to prevent Denial-of-service attack and confirms that the program does not have any access to each other’s state, also ensures that the communication is established without any potential interference. Smart contracts are high-level program codes that are compiled to EVM byte code and deployed to the ethereum blockchain for further execution. It allows us to perform credible transactions without any interference of the third party, these transactions are trackable and irreversible. Languages used to write smart contracts are Solidity (a language library with similarities to C and JavaScript), Serpent (similar to Python, but deprecated), LLL (a low-level Lisp-like language), and Mutan (Go-based, but deprecated). Example: In the below example, we have discussed a sample solidity program to demonstrate how to write a smart contract in Solidity. Solidity // Solidity program to // demonstrate how to // write a smart contract pragma solidity >= 0.4.16 < 0.7.0; // Defining a contract contract Test{ // Declaring state variables uint public var1; uint public var2; uint public sum; // Defining public function // that sets the value of // the state variable function set(uint x, uint y) public { var1 = x; var2=y; sum=var1+var2; } // Defining function to // print the sum of // state variables function get( ) public view returns (uint) { return sum; } } Output: Explanation: 1. Version Pragma: pragma solidity >=0.4.16 <0.7.0; Pragmas are instructions to the compiler on how to treat the code. All solidity source code should start with a “version pragma” which is a declaration of the version of the solidity compiler this code should use. This helps the code from being incompatible with the future versions of the compiler which may bring changes. The above-mentioned code states that it is compatible with compilers of version greater than and equal to 0.4.16 but less than version 0.7.0. 2. The contract keyword: contract Test{ //Functions and Data } The contract keyword declares a contract under which is the code encapsulated. 3. State variables: uint public var1; uint public var2; uint public sum; State variables are permanently stored in contract storage that they are written in Ethereum Blockchain. The line uint public var1 declares a state variable called var1 of type uint (unsigned integer of 256 bits). Think of it as adding a slot in a database. Similarly, goes with the declaration uint public var2 and uint public sum. 4. A function declaration: function set(uint x, uint y) public function get() public view returns (uint) This is a function named set of access modifier type public which takes a variable x and variable y of datatype uint as a parameter. This was an example of a simple smart contract which updates the value of var1 and var2. Anyone can call the function set and overwrite the value of var1 and var2 which is stored in Ethereum blockchain. This is an example of a decentralized application that is censorship proof and unaffected to the shutdown of any centralized server. As long as someone is running a single node of Ethereum blockchain, this smart contract will be accessible. The variable sum is calculated by adding the values of the variables var1 and var2. Function get will retrieve and print the value of the state variable sum. There are practically two ways to execute a solidity smart contract: 1. Offline Mode: Running a solidity smart contract in Offline mode requires three prerequisites and 4 major steps to be followed to get the smart contract running: Prerequisites:Download and install node.js.Install Truffle globally.Install ganache-cli. Download and install node.js. Install Truffle globally. Install ganache-cli. Objectives:Create a truffle project and configure a development networkCreate and deploy smart contractsInteract with the smart contract from Truffle consoleWrite tests for testing main features offered by Solidity Create a truffle project and configure a development network Create and deploy smart contracts Interact with the smart contract from Truffle console Write tests for testing main features offered by Solidity 2. Online Mode: Remix IDE is generally used to compile and run Solidity smart contracts in the Online Mode. You can find the complete articles with all the steps here. Solidity-Basics Blockchain Solidity Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n11 May, 2022" }, { "code": null, "e": 300, "s": 53, "text": "Solidity is a brand-new programming language created by the Ethereum which is the second-largest market of cryptocurrency by capitalization, released in the year 2015 led by Christian Reitwiessner. Some key features of solidity are listed below: " }, { "code": null, "e": 389, "s": 300, "text": "Solidity is a high-level programming language designed for implementing smart contracts." }, { "code": null, "e": 457, "s": 389, "text": "It is statically-typed object-oriented(contract-oriented) language." }, { "code": null, "e": 567, "s": 457, "text": "Solidity is highly influenced by Python, c++, and JavaScript which runs on the Ethereum Virtual Machine(EVM)." }, { "code": null, "e": 646, "s": 567, "text": "Solidity supports complex user-defined programming, libraries and inheritance." }, { "code": null, "e": 710, "s": 646, "text": "Solidity is primary language for blockchains running platforms." }, { "code": null, "e": 826, "s": 710, "text": "Solidity can be used to creating contracts like voting, blind auctions, crowdfunding, multi-signature wallets, etc." }, { "code": null, "e": 1297, "s": 826, "text": "Ethereum is a decentralized open-source platform based on blockchain domain, used to run smart contracts i.e. applications that execute the program exactly as it was programmed without the possibility of any fraud, interference from a third party, censorship, or downtime. It serves a platform for nearly 2,60,000 different cryptocurrencies. Ether is a cryptocurrency generated by ethereum miners, used to reward for the computations performed to secure the blockchain. " }, { "code": null, "e": 1750, "s": 1297, "text": "Ethereum Virtual Machine abbreviated as EVM is a runtime environment for executing smart contracts in ethereum. It focuses widely on providing security and execution of untrusted code using an international network of public nodes. EVM is specialized to prevent Denial-of-service attack and confirms that the program does not have any access to each other’s state, also ensures that the communication is established without any potential interference. " }, { "code": null, "e": 2269, "s": 1750, "text": "Smart contracts are high-level program codes that are compiled to EVM byte code and deployed to the ethereum blockchain for further execution. It allows us to perform credible transactions without any interference of the third party, these transactions are trackable and irreversible. Languages used to write smart contracts are Solidity (a language library with similarities to C and JavaScript), Serpent (similar to Python, but deprecated), LLL (a low-level Lisp-like language), and Mutan (Go-based, but deprecated)." }, { "code": null, "e": 2402, "s": 2269, "text": "Example: In the below example, we have discussed a sample solidity program to demonstrate how to write a smart contract in Solidity." }, { "code": null, "e": 2411, "s": 2402, "text": "Solidity" }, { "code": "// Solidity program to // demonstrate how to // write a smart contract pragma solidity >= 0.4.16 < 0.7.0; // Defining a contract contract Test{ // Declaring state variables uint public var1; uint public var2; uint public sum; // Defining public function // that sets the value of // the state variable function set(uint x, uint y) public { var1 = x; var2=y; sum=var1+var2; } // Defining function to // print the sum of // state variables function get( ) public view returns (uint) { return sum; } }", "e": 3025, "s": 2411, "text": null }, { "code": null, "e": 3033, "s": 3025, "text": "Output:" }, { "code": null, "e": 3046, "s": 3033, "text": "Explanation:" }, { "code": null, "e": 3066, "s": 3046, "text": "1. Version Pragma: " }, { "code": null, "e": 3100, "s": 3066, "text": "pragma solidity >=0.4.16 <0.7.0;\n" }, { "code": null, "e": 3566, "s": 3100, "text": "Pragmas are instructions to the compiler on how to treat the code. All solidity source code should start with a “version pragma” which is a declaration of the version of the solidity compiler this code should use. This helps the code from being incompatible with the future versions of the compiler which may bring changes. The above-mentioned code states that it is compatible with compilers of version greater than and equal to 0.4.16 but less than version 0.7.0." }, { "code": null, "e": 3592, "s": 3566, "text": "2. The contract keyword: " }, { "code": null, "e": 3633, "s": 3592, "text": "contract Test{ \n//Functions and Data \n}\n" }, { "code": null, "e": 3712, "s": 3633, "text": "The contract keyword declares a contract under which is the code encapsulated." }, { "code": null, "e": 3733, "s": 3712, "text": "3. State variables: " }, { "code": null, "e": 3787, "s": 3733, "text": "uint public var1;\nuint public var2;\nuint public sum;\n" }, { "code": null, "e": 4120, "s": 3787, "text": "State variables are permanently stored in contract storage that they are written in Ethereum Blockchain. The line uint public var1 declares a state variable called var1 of type uint (unsigned integer of 256 bits). Think of it as adding a slot in a database. Similarly, goes with the declaration uint public var2 and uint public sum." }, { "code": null, "e": 4147, "s": 4120, "text": "4. A function declaration:" }, { "code": null, "e": 4226, "s": 4147, "text": "function set(uint x, uint y) public\nfunction get() public view returns (uint)\n" }, { "code": null, "e": 4359, "s": 4226, "text": "This is a function named set of access modifier type public which takes a variable x and variable y of datatype uint as a parameter." }, { "code": null, "e": 4803, "s": 4359, "text": "This was an example of a simple smart contract which updates the value of var1 and var2. Anyone can call the function set and overwrite the value of var1 and var2 which is stored in Ethereum blockchain. This is an example of a decentralized application that is censorship proof and unaffected to the shutdown of any centralized server. As long as someone is running a single node of Ethereum blockchain, this smart contract will be accessible." }, { "code": null, "e": 4887, "s": 4803, "text": "The variable sum is calculated by adding the values of the variables var1 and var2." }, { "code": null, "e": 4961, "s": 4887, "text": "Function get will retrieve and print the value of the state variable sum." }, { "code": null, "e": 5030, "s": 4961, "text": "There are practically two ways to execute a solidity smart contract:" }, { "code": null, "e": 5194, "s": 5030, "text": "1. Offline Mode: Running a solidity smart contract in Offline mode requires three prerequisites and 4 major steps to be followed to get the smart contract running:" }, { "code": null, "e": 5283, "s": 5194, "text": "Prerequisites:Download and install node.js.Install Truffle globally.Install ganache-cli." }, { "code": null, "e": 5313, "s": 5283, "text": "Download and install node.js." }, { "code": null, "e": 5339, "s": 5313, "text": "Install Truffle globally." }, { "code": null, "e": 5360, "s": 5339, "text": "Install ganache-cli." }, { "code": null, "e": 5575, "s": 5360, "text": "Objectives:Create a truffle project and configure a development networkCreate and deploy smart contractsInteract with the smart contract from Truffle consoleWrite tests for testing main features offered by Solidity" }, { "code": null, "e": 5636, "s": 5575, "text": "Create a truffle project and configure a development network" }, { "code": null, "e": 5670, "s": 5636, "text": "Create and deploy smart contracts" }, { "code": null, "e": 5724, "s": 5670, "text": "Interact with the smart contract from Truffle console" }, { "code": null, "e": 5782, "s": 5724, "text": "Write tests for testing main features offered by Solidity" }, { "code": null, "e": 5950, "s": 5782, "text": "2. Online Mode: Remix IDE is generally used to compile and run Solidity smart contracts in the Online Mode. You can find the complete articles with all the steps here." }, { "code": null, "e": 5966, "s": 5950, "text": "Solidity-Basics" }, { "code": null, "e": 5977, "s": 5966, "text": "Blockchain" }, { "code": null, "e": 5986, "s": 5977, "text": "Solidity" } ]
Python | Sort words of sentence in ascending order
22 Nov, 2019 Given a sentence, sort it alphabetically in ascending order. Examples: Input : to learn programming refer geeksforgeeks Output : geeksforgeeks learn programming refer to Input : geeks for geeks Output : for geeks geeks We will use built in library function to sort the words of the sentence in ascending order.Prerequisites:1. split()2. sort() in Python3. join() Split the Sentence in words. Sort the words alphabetically Join the sorted words alphabetically to form a new Sentence. Below is the implementation of above idea. # Function to sort the words# in ascending orderdef sortedSentence(Sentence): # Splitting the Sentence into words words = Sentence.split(" ") # Sorting the words words.sort() # Making new Sentence by # joining the sorted words newSentence = " ".join(words) # Return newSentence return newSentence # Driver's Code Sentence = "to learn programming refer geeksforgeeks"# Print the sortedSentenceprint(sortedSentence(Sentence)) Sentence = "geeks for geeks"# Print the sortedSentenceprint(sortedSentence(Sentence)) Output: geeksforgeeks learn programming refer to for geeks geeks shubham_singh python-string Python Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Nov, 2019" }, { "code": null, "e": 114, "s": 53, "text": "Given a sentence, sort it alphabetically in ascending order." }, { "code": null, "e": 124, "s": 114, "text": "Examples:" }, { "code": null, "e": 274, "s": 124, "text": "Input : to learn programming refer geeksforgeeks\nOutput : geeksforgeeks learn programming refer to\n\nInput : geeks for geeks\nOutput : for geeks geeks\n" }, { "code": null, "e": 418, "s": 274, "text": "We will use built in library function to sort the words of the sentence in ascending order.Prerequisites:1. split()2. sort() in Python3. join()" }, { "code": null, "e": 447, "s": 418, "text": "Split the Sentence in words." }, { "code": null, "e": 477, "s": 447, "text": "Sort the words alphabetically" }, { "code": null, "e": 538, "s": 477, "text": "Join the sorted words alphabetically to form a new Sentence." }, { "code": null, "e": 581, "s": 538, "text": "Below is the implementation of above idea." }, { "code": "# Function to sort the words# in ascending orderdef sortedSentence(Sentence): # Splitting the Sentence into words words = Sentence.split(\" \") # Sorting the words words.sort() # Making new Sentence by # joining the sorted words newSentence = \" \".join(words) # Return newSentence return newSentence # Driver's Code Sentence = \"to learn programming refer geeksforgeeks\"# Print the sortedSentenceprint(sortedSentence(Sentence)) Sentence = \"geeks for geeks\"# Print the sortedSentenceprint(sortedSentence(Sentence))", "e": 1146, "s": 581, "text": null }, { "code": null, "e": 1154, "s": 1146, "text": "Output:" }, { "code": null, "e": 1212, "s": 1154, "text": "geeksforgeeks learn programming refer to\nfor geeks geeks\n" }, { "code": null, "e": 1226, "s": 1212, "text": "shubham_singh" }, { "code": null, "e": 1240, "s": 1226, "text": "python-string" }, { "code": null, "e": 1247, "s": 1240, "text": "Python" }, { "code": null, "e": 1255, "s": 1247, "text": "Sorting" }, { "code": null, "e": 1263, "s": 1255, "text": "Sorting" } ]
Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
11 Jul, 2022 Given two values m and n, fill a matrix of size ‘m*n’ in a spiral (or circular) fashion (clockwise) with natural numbers from 1 to m*n. Examples: Input : m = 4, n = 4 Output : 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 Input : m = 3, n = 4 Output : 1 2 3 4 10 11 12 5 9 8 7 6 The idea is based on Print a given matrix in spiral form. We create a matrix of size m * n and traverse it in a spiral fashion. While traversing, we keep track of a variable “val” to fill the next value, we increment “val” one by one and put its values in the matrix. Implementation: C++ C Java Python3 C# PHP Javascript // C++ program to fill a matrix with values from// 1 to n*n in spiral fashion.#include <bits/stdc++.h>using namespace std; const int MAX = 100; // Fills a[m][n] with values from 1 to m*n in// spiral fashion.void spiralFill(int m, int n, int a[][MAX]){ // Initialize value to be filled in matrix int val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int k = 0, l = 0; while (k < m && l < n) { /* Print the first row from the remaining rows */ for (int i = l; i < n; ++i) a[k][i] = val++; k++; /* Print the last column from the remaining columns */ for (int i = k; i < m; ++i) a[i][n-1] = val++; n--; /* Print the last row from the remaining rows */ if (k < m) { for (int i = n-1; i >= l; --i) a[m-1][i] = val++; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= k; --i) a[i][l] = val++; l++; } }} /* Driver program to test above functions */int main(){ int m = 4, n = 4; int a[MAX][MAX]; spiralFill(m, n, a); for (int i=0; i<m; i++) { for (int j=0; j<n; j++) cout << a[i][j] << " "; cout << endl; } return 0;} // C program to fill a matrix with values from// 1 to n*n in spiral fashion.#include <stdio.h> const int MAX = 100; // Fills a[m][n] with values from 1 to m*n in// spiral fashion.void spiralFill(int m, int n, int a[][MAX]){ // Initialize value to be filled in matrix int val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int k = 0, l = 0; while (k < m && l < n) { /* Print the first row from the remaining rows */ for (int i = l; i < n; ++i) a[k][i] = val++; k++; /* Print the last column from the remaining columns */ for (int i = k; i < m; ++i) a[i][n-1] = val++; n--; /* Print the last row from the remaining rows */ if (k < m) { for (int i = n-1; i >= l; --i) a[m-1][i] = val++; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= k; --i) a[i][l] = val++; l++; } }} /* Driver program to test above functions */int main(){ int m = 4, n = 4; int a[MAX][MAX]; spiralFill(m, n, a); for (int i=0; i<m; i++) { for (int j=0; j<n; j++) printf("%d ",a[i][j]); printf("\n"); } return 0;} // This code is contributed by kothavvsaakash. // Java program to fill a matrix with values from// 1 to n*n in spiral fashion.class GFG { static int MAX = 100; // Fills a[m][n] with values from 1 to m*n in// spiral fashion. static void spiralFill(int m, int n, int a[][]) { // Initialize value to be filled in matrix int val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int k = 0, l = 0; while (k < m && l < n) { /* Print the first row from the remaining rows */ for (int i = l; i < n; ++i) { a[k][i] = val++; } k++; /* Print the last column from the remaining columns */ for (int i = k; i < m; ++i) { a[i][n - 1] = val++; } n--; /* Print the last row from the remaining rows */ if (k < m) { for (int i = n - 1; i >= l; --i) { a[m - 1][i] = val++; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (int i = m - 1; i >= k; --i) { a[i][l] = val++; } l++; } } } /* Driver program to test above functions */ public static void main(String[] args) { int m = 4, n = 4; int a[][] = new int[MAX][MAX]; spiralFill(m, n, a); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.print(a[i][j] + " "); } System.out.println(""); } }} /* This Java code is contributed by PrinciRaj1992*/ # Python program to fill a matrix with# values from 1 to n*n in spiral fashion. # Fills a[m][n] with values# from 1 to m*n in spiral fashion.def spiralFill(m, n, a): # Initialize value to be filled in matrix. val = 1 # k - starting row index # m - ending row index # l - starting column index # n - ending column index k, l = 0, 0 while (k < m and l < n): # Print the first row from the remaining rows. for i in range(l, n): a[k][i] = val val += 1 k += 1 # Print the last column from the remaining columns. for i in range(k, m): a[i][n - 1] = val val += 1 n -= 1 # Print the last row from the remaining rows. if (k < m): for i in range(n - 1, l - 1, -1): a[m - 1][i] = val val += 1 m -= 1 # Print the first column from the remaining columns. if (l < n): for i in range(m - 1, k - 1, -1): a[i][l] = val val += 1 l += 1 # Driver programif __name__ == '__main__': m, n = 4, 4 a = [[0 for j in range(n)] for i in range(m)] spiralFill(m, n, a) for i in range(m): for j in range(n): print(a[i][j], end=' ') print('') # This code is contributed by Parin Shah // C# program to fill a matrix with values from// 1 to n*n in spiral fashion. using System;class GFG { static int MAX = 100; // Fills a[m,n] with values from 1 to m*n in// spiral fashion. static void spiralFill(int m, int n, int[,] a) { // Initialize value to be filled in matrix int val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int k = 0, l = 0; while (k < m && l < n) { /* Print the first row from the remaining rows */ for (int i = l; i < n; ++i) { a[k,i] = val++; } k++; /* Print the last column from the remaining columns */ for (int i = k; i < m; ++i) { a[i,n - 1] = val++; } n--; /* Print the last row from the remaining rows */ if (k < m) { for (int i = n - 1; i >= l; --i) { a[m - 1,i] = val++; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (int i = m - 1; i >= k; --i) { a[i,l] = val++; } l++; } } } /* Driver program to test above functions */ public static void Main() { int m = 4, n = 4; int[,] a = new int[MAX,MAX]; spiralFill(m, n, a); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { Console.Write(a[i,j] + " "); } Console.Write("\n"); } }} <?php// PHP program to fill a matrix with values// from 1 to n*n in spiral fashion. // Fills a[m][n] with values from 1 to// m*n in spiral fashion.function spiralFill($m, $n, &$a){ // Initialize value to be filled // in matrix $val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ $k = 0; $l = 0; while ($k < $m && $l < $n) { /* Print the first row from the remaining rows */ for ($i = $l; $i < $n; ++$i) $a[$k][$i] = $val++; $k++; /* Print the last column from the remaining columns */ for ($i = $k; $i < $m; ++$i) $a[$i][$n - 1] = $val++; $n--; /* Print the last row from the remaining rows */ if ($k < $m) { for ($i = $n - 1; $i >= $l; --$i) $a[$m - 1][$i] = $val++; $m--; } /* Print the first column from the remaining columns */ if ($l < $n) { for ($i = $m - 1; $i >= $k; --$i) $a[$i][$l] = $val++; $l++; } }} // Driver Code$m = 4;$n = 4;spiralFill($m, $n, $a);for ($i = 0; $i < $m; $i++){ for ($j = 0; $j < $n; $j++) { echo ($a[$i][$j]); echo (" "); } echo ("\n");} // This code is contributed// by Shivi_Aggarwal?> <script>// Javascript program to fill a matrix with values from// 1 to n*n in spiral fashion. const MAX = 100; // Fills a[m][n] with values from 1 to m*n in// spiral fashion.function spiralFill(m, n, a){ // Initialize value to be filled in matrix let val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ let k = 0, l = 0; while (k < m && l < n) { /* Print the first row from the remaining rows */ for (let i = l; i < n; ++i) a[k][i] = val++; k++; /* Print the last column from the remaining columns */ for (let i = k; i < m; ++i) a[i][n-1] = val++; n--; /* Print the last row from the remaining rows */ if (k < m) { for (let i = n - 1; i >= l; --i) a[m-1][i] = val++; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (let i = m - 1; i >= k; --i) a[i][l] = val++; l++; } }} /* Driver program to test above functions */ let m = 4, n = 4; let a = Array.from(Array(MAX), () => new Array(MAX)); spiralFill(m, n, a); for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) document.write(a[i][j] + " "); document.write("<br>"); } // This code is contributed by souravmahato348.</script> 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 Time complexity: O(m * n) Space complexity: O(m * n) This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. princiraj1992 ukasp Shivi_Aggarwal gfg_sal_gfg ShahParin souravmahato348 avirenichandanchandu43657 kothavvsaakash hardikkoriintern spiral Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Jul, 2022" }, { "code": null, "e": 190, "s": 54, "text": "Given two values m and n, fill a matrix of size ‘m*n’ in a spiral (or circular) fashion (clockwise) with natural numbers from 1 to m*n." }, { "code": null, "e": 202, "s": 190, "text": "Examples: " }, { "code": null, "e": 398, "s": 202, "text": "Input : m = 4, n = 4\nOutput : 1 2 3 4\n 12 13 14 5\n 11 16 15 6\n 10 9 8 7 \n\nInput : m = 3, n = 4\nOutput : 1 2 3 4\n 10 11 12 5\n 9 8 7 6 " }, { "code": null, "e": 667, "s": 398, "text": "The idea is based on Print a given matrix in spiral form. We create a matrix of size m * n and traverse it in a spiral fashion. While traversing, we keep track of a variable “val” to fill the next value, we increment “val” one by one and put its values in the matrix. " }, { "code": null, "e": 683, "s": 667, "text": "Implementation:" }, { "code": null, "e": 687, "s": 683, "text": "C++" }, { "code": null, "e": 689, "s": 687, "text": "C" }, { "code": null, "e": 694, "s": 689, "text": "Java" }, { "code": null, "e": 702, "s": 694, "text": "Python3" }, { "code": null, "e": 705, "s": 702, "text": "C#" }, { "code": null, "e": 709, "s": 705, "text": "PHP" }, { "code": null, "e": 720, "s": 709, "text": "Javascript" }, { "code": "// C++ program to fill a matrix with values from// 1 to n*n in spiral fashion.#include <bits/stdc++.h>using namespace std; const int MAX = 100; // Fills a[m][n] with values from 1 to m*n in// spiral fashion.void spiralFill(int m, int n, int a[][MAX]){ // Initialize value to be filled in matrix int val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int k = 0, l = 0; while (k < m && l < n) { /* Print the first row from the remaining rows */ for (int i = l; i < n; ++i) a[k][i] = val++; k++; /* Print the last column from the remaining columns */ for (int i = k; i < m; ++i) a[i][n-1] = val++; n--; /* Print the last row from the remaining rows */ if (k < m) { for (int i = n-1; i >= l; --i) a[m-1][i] = val++; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= k; --i) a[i][l] = val++; l++; } }} /* Driver program to test above functions */int main(){ int m = 4, n = 4; int a[MAX][MAX]; spiralFill(m, n, a); for (int i=0; i<m; i++) { for (int j=0; j<n; j++) cout << a[i][j] << \" \"; cout << endl; } return 0;}", "e": 2160, "s": 720, "text": null }, { "code": "// C program to fill a matrix with values from// 1 to n*n in spiral fashion.#include <stdio.h> const int MAX = 100; // Fills a[m][n] with values from 1 to m*n in// spiral fashion.void spiralFill(int m, int n, int a[][MAX]){ // Initialize value to be filled in matrix int val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int k = 0, l = 0; while (k < m && l < n) { /* Print the first row from the remaining rows */ for (int i = l; i < n; ++i) a[k][i] = val++; k++; /* Print the last column from the remaining columns */ for (int i = k; i < m; ++i) a[i][n-1] = val++; n--; /* Print the last row from the remaining rows */ if (k < m) { for (int i = n-1; i >= l; --i) a[m-1][i] = val++; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= k; --i) a[i][l] = val++; l++; } }} /* Driver program to test above functions */int main(){ int m = 4, n = 4; int a[MAX][MAX]; spiralFill(m, n, a); for (int i=0; i<m; i++) { for (int j=0; j<n; j++) printf(\"%d \",a[i][j]); printf(\"\\n\"); } return 0;} // This code is contributed by kothavvsaakash.", "e": 3618, "s": 2160, "text": null }, { "code": "// Java program to fill a matrix with values from// 1 to n*n in spiral fashion.class GFG { static int MAX = 100; // Fills a[m][n] with values from 1 to m*n in// spiral fashion. static void spiralFill(int m, int n, int a[][]) { // Initialize value to be filled in matrix int val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int k = 0, l = 0; while (k < m && l < n) { /* Print the first row from the remaining rows */ for (int i = l; i < n; ++i) { a[k][i] = val++; } k++; /* Print the last column from the remaining columns */ for (int i = k; i < m; ++i) { a[i][n - 1] = val++; } n--; /* Print the last row from the remaining rows */ if (k < m) { for (int i = n - 1; i >= l; --i) { a[m - 1][i] = val++; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (int i = m - 1; i >= k; --i) { a[i][l] = val++; } l++; } } } /* Driver program to test above functions */ public static void main(String[] args) { int m = 4, n = 4; int a[][] = new int[MAX][MAX]; spiralFill(m, n, a); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.print(a[i][j] + \" \"); } System.out.println(\"\"); } }} /* This Java code is contributed by PrinciRaj1992*/", "e": 5376, "s": 3618, "text": null }, { "code": "# Python program to fill a matrix with# values from 1 to n*n in spiral fashion. # Fills a[m][n] with values# from 1 to m*n in spiral fashion.def spiralFill(m, n, a): # Initialize value to be filled in matrix. val = 1 # k - starting row index # m - ending row index # l - starting column index # n - ending column index k, l = 0, 0 while (k < m and l < n): # Print the first row from the remaining rows. for i in range(l, n): a[k][i] = val val += 1 k += 1 # Print the last column from the remaining columns. for i in range(k, m): a[i][n - 1] = val val += 1 n -= 1 # Print the last row from the remaining rows. if (k < m): for i in range(n - 1, l - 1, -1): a[m - 1][i] = val val += 1 m -= 1 # Print the first column from the remaining columns. if (l < n): for i in range(m - 1, k - 1, -1): a[i][l] = val val += 1 l += 1 # Driver programif __name__ == '__main__': m, n = 4, 4 a = [[0 for j in range(n)] for i in range(m)] spiralFill(m, n, a) for i in range(m): for j in range(n): print(a[i][j], end=' ') print('') # This code is contributed by Parin Shah", "e": 6713, "s": 5376, "text": null }, { "code": "// C# program to fill a matrix with values from// 1 to n*n in spiral fashion. using System;class GFG { static int MAX = 100; // Fills a[m,n] with values from 1 to m*n in// spiral fashion. static void spiralFill(int m, int n, int[,] a) { // Initialize value to be filled in matrix int val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int k = 0, l = 0; while (k < m && l < n) { /* Print the first row from the remaining rows */ for (int i = l; i < n; ++i) { a[k,i] = val++; } k++; /* Print the last column from the remaining columns */ for (int i = k; i < m; ++i) { a[i,n - 1] = val++; } n--; /* Print the last row from the remaining rows */ if (k < m) { for (int i = n - 1; i >= l; --i) { a[m - 1,i] = val++; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (int i = m - 1; i >= k; --i) { a[i,l] = val++; } l++; } } } /* Driver program to test above functions */ public static void Main() { int m = 4, n = 4; int[,] a = new int[MAX,MAX]; spiralFill(m, n, a); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { Console.Write(a[i,j] + \" \"); } Console.Write(\"\\n\"); } }}", "e": 8411, "s": 6713, "text": null }, { "code": "<?php// PHP program to fill a matrix with values// from 1 to n*n in spiral fashion. // Fills a[m][n] with values from 1 to// m*n in spiral fashion.function spiralFill($m, $n, &$a){ // Initialize value to be filled // in matrix $val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ $k = 0; $l = 0; while ($k < $m && $l < $n) { /* Print the first row from the remaining rows */ for ($i = $l; $i < $n; ++$i) $a[$k][$i] = $val++; $k++; /* Print the last column from the remaining columns */ for ($i = $k; $i < $m; ++$i) $a[$i][$n - 1] = $val++; $n--; /* Print the last row from the remaining rows */ if ($k < $m) { for ($i = $n - 1; $i >= $l; --$i) $a[$m - 1][$i] = $val++; $m--; } /* Print the first column from the remaining columns */ if ($l < $n) { for ($i = $m - 1; $i >= $k; --$i) $a[$i][$l] = $val++; $l++; } }} // Driver Code$m = 4;$n = 4;spiralFill($m, $n, $a);for ($i = 0; $i < $m; $i++){ for ($j = 0; $j < $n; $j++) { echo ($a[$i][$j]); echo (\" \"); } echo (\"\\n\");} // This code is contributed// by Shivi_Aggarwal?>", "e": 9790, "s": 8411, "text": null }, { "code": "<script>// Javascript program to fill a matrix with values from// 1 to n*n in spiral fashion. const MAX = 100; // Fills a[m][n] with values from 1 to m*n in// spiral fashion.function spiralFill(m, n, a){ // Initialize value to be filled in matrix let val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ let k = 0, l = 0; while (k < m && l < n) { /* Print the first row from the remaining rows */ for (let i = l; i < n; ++i) a[k][i] = val++; k++; /* Print the last column from the remaining columns */ for (let i = k; i < m; ++i) a[i][n-1] = val++; n--; /* Print the last row from the remaining rows */ if (k < m) { for (let i = n - 1; i >= l; --i) a[m-1][i] = val++; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (let i = m - 1; i >= k; --i) a[i][l] = val++; l++; } }} /* Driver program to test above functions */ let m = 4, n = 4; let a = Array.from(Array(MAX), () => new Array(MAX)); spiralFill(m, n, a); for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) document.write(a[i][j] + \" \"); document.write(\"<br>\"); } // This code is contributed by souravmahato348.</script>", "e": 11280, "s": 9790, "text": null }, { "code": null, "e": 11323, "s": 11280, "text": "1 2 3 4 \n12 13 14 5 \n11 16 15 6 \n10 9 8 7 " }, { "code": null, "e": 11376, "s": 11323, "text": "Time complexity: O(m * n) Space complexity: O(m * n)" }, { "code": null, "e": 11673, "s": 11376, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 11687, "s": 11673, "text": "princiraj1992" }, { "code": null, "e": 11693, "s": 11687, "text": "ukasp" }, { "code": null, "e": 11708, "s": 11693, "text": "Shivi_Aggarwal" }, { "code": null, "e": 11720, "s": 11708, "text": "gfg_sal_gfg" }, { "code": null, "e": 11730, "s": 11720, "text": "ShahParin" }, { "code": null, "e": 11746, "s": 11730, "text": "souravmahato348" }, { "code": null, "e": 11772, "s": 11746, "text": "avirenichandanchandu43657" }, { "code": null, "e": 11787, "s": 11772, "text": "kothavvsaakash" }, { "code": null, "e": 11804, "s": 11787, "text": "hardikkoriintern" }, { "code": null, "e": 11811, "s": 11804, "text": "spiral" }, { "code": null, "e": 11818, "s": 11811, "text": "Matrix" }, { "code": null, "e": 11825, "s": 11818, "text": "Matrix" } ]
QUOTE () function in MySQL - GeeksforGeeks
09 Dec, 2020 QUOTE() :This function in MySQL is used to return a result that can be used as a properly escaped data value in an SQL statement. The string is returned enclosed by single quotation marks and with each instance of backslash (\), single quote (‘), ASCII NULL, and Control+Z preceded by a backslash. If the argument is NULL, the return value is the word “NULL” without enclosing single quotation marks. Syntax : QUOTE(string) Parameters :This method accepts one parameter. string – The Input String. Returns :It returns a string with properly escaped data value in an SQL statement. Example-1 :Escaping single quotes in the string ‘geeks”for”geeks’ with the help of QUOTE Function. SELECT QUOTE('geeks''for''geeks' ) AS Escaped_String; Output : Example-2 :Escaping backslash in the string ‘geeks\for’\geeks’ with the help of QUOTE Function. SELECT QUOTE('geeks\for\geeks' ) AS Escaped_String; Output : Example-3 :QUOTE Function can also be used in column data. To demonstrate create a table named Student. CREATE TABLE Student ( Student_id INT AUTO_INCREMENT, Student_name VARCHAR(100) NOT NULL, Roll INT NOT NULL, Department VARCHAR(10) NOT NULL, PRIMARY KEY(Student_id ) ); Inserting some data to the Student table : INSERT INTO Student (Student_name, Roll, Department ) VALUES ('Anik Biswas ', 10100, 'CSE'), ('Bina Mallick', 11000, 'ECE' ), ('Aniket Sharma', 12000, 'IT' ), ('Sayani Samanta', 13000, 'ME' ), ('Riyanka Shah ', 14000, 'EE' ) ; So, the Student Table is as follows. SELECT * from Student ; Output : Now, we are going to use QUOTE Function on Department column. SELECT *, QUOTE (Department) FROM Student; Output : DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n09 Dec, 2020" }, { "code": null, "e": 25914, "s": 25513, "text": "QUOTE() :This function in MySQL is used to return a result that can be used as a properly escaped data value in an SQL statement. The string is returned enclosed by single quotation marks and with each instance of backslash (\\), single quote (‘), ASCII NULL, and Control+Z preceded by a backslash. If the argument is NULL, the return value is the word “NULL” without enclosing single quotation marks." }, { "code": null, "e": 25923, "s": 25914, "text": "Syntax :" }, { "code": null, "e": 25937, "s": 25923, "text": "QUOTE(string)" }, { "code": null, "e": 25984, "s": 25937, "text": "Parameters :This method accepts one parameter." }, { "code": null, "e": 26011, "s": 25984, "text": "string – The Input String." }, { "code": null, "e": 26094, "s": 26011, "text": "Returns :It returns a string with properly escaped data value in an SQL statement." }, { "code": null, "e": 26193, "s": 26094, "text": "Example-1 :Escaping single quotes in the string ‘geeks”for”geeks’ with the help of QUOTE Function." }, { "code": null, "e": 26248, "s": 26193, "text": "SELECT QUOTE('geeks''for''geeks' ) \nAS Escaped_String;" }, { "code": null, "e": 26257, "s": 26248, "text": "Output :" }, { "code": null, "e": 26353, "s": 26257, "text": "Example-2 :Escaping backslash in the string ‘geeks\\for’\\geeks’ with the help of QUOTE Function." }, { "code": null, "e": 26406, "s": 26353, "text": "SELECT QUOTE('geeks\\for\\geeks' ) \nAS Escaped_String;" }, { "code": null, "e": 26415, "s": 26406, "text": "Output :" }, { "code": null, "e": 26519, "s": 26415, "text": "Example-3 :QUOTE Function can also be used in column data. To demonstrate create a table named Student." }, { "code": null, "e": 26691, "s": 26519, "text": "CREATE TABLE Student\n(\nStudent_id INT AUTO_INCREMENT, \nStudent_name VARCHAR(100) NOT NULL,\nRoll INT NOT NULL,\nDepartment VARCHAR(10) NOT NULL,\nPRIMARY KEY(Student_id )\n);" }, { "code": null, "e": 26734, "s": 26691, "text": "Inserting some data to the Student table :" }, { "code": null, "e": 26962, "s": 26734, "text": "INSERT INTO Student\n(Student_name, Roll, Department )\nVALUES\n('Anik Biswas ', 10100, 'CSE'),\n('Bina Mallick', 11000, 'ECE' ),\n('Aniket Sharma', 12000, 'IT' ),\n('Sayani Samanta', 13000, 'ME' ),\n('Riyanka Shah ', 14000, 'EE' ) ;" }, { "code": null, "e": 26999, "s": 26962, "text": "So, the Student Table is as follows." }, { "code": null, "e": 27025, "s": 26999, "text": "SELECT * from Student ;\n" }, { "code": null, "e": 27034, "s": 27025, "text": "Output :" }, { "code": null, "e": 27096, "s": 27034, "text": "Now, we are going to use QUOTE Function on Department column." }, { "code": null, "e": 27139, "s": 27096, "text": "SELECT *, QUOTE (Department) FROM Student;" }, { "code": null, "e": 27148, "s": 27139, "text": "Output :" }, { "code": null, "e": 27157, "s": 27148, "text": "DBMS-SQL" }, { "code": null, "e": 27163, "s": 27157, "text": "mysql" }, { "code": null, "e": 27167, "s": 27163, "text": "SQL" }, { "code": null, "e": 27171, "s": 27167, "text": "SQL" }, { "code": null, "e": 27269, "s": 27171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27335, "s": 27269, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27350, "s": 27335, "text": "SQL | Subquery" }, { "code": null, "e": 27407, "s": 27350, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27439, "s": 27407, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27517, "s": 27439, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27553, "s": 27517, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27570, "s": 27553, "text": "SQL using Python" }, { "code": null, "e": 27636, "s": 27570, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 27698, "s": 27636, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
Wand local_contrast() function - Python - GeeksforGeeks
07 Jul, 2021 The local_contrast() function is an inbuilt function in the Python Wand ImageMagick library which is used to increase light-dark transitions within the image. Syntax: local_contrast(radius, strength) Parameters: This function accepts two parameters as mentioned above and defined below: radius: This parameter is used to store the size of the Gaussian operator. Default value is 10.0 strength: This parameter is used to store the percentage of blur mask to apply. Default value is 12.5 and it can range from 0 to 100. Return Value: This function returns the Wand ImageMagick object. Original Image: Example 1: Python3 # Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as local_contrast: # Invoke local_contrast function with radius 12 and sigma 3 local_contrast.local_contrast(12, 3) # Save the image local_contrast.save(filename ='local_contrast1.jpg') Output: Example 2: Python3 # Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke local_contrast function with radius 15 and sigma 78 pic.local_contrast(15, 78) # Save the image pic.save(filename ='local_contrast2.jpg') Output: sagartomar9927 Image-Processing Python-wand Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n07 Jul, 2021" }, { "code": null, "e": 25697, "s": 25537, "text": "The local_contrast() function is an inbuilt function in the Python Wand ImageMagick library which is used to increase light-dark transitions within the image. " }, { "code": null, "e": 25707, "s": 25697, "text": "Syntax: " }, { "code": null, "e": 25740, "s": 25707, "text": "local_contrast(radius, strength)" }, { "code": null, "e": 25829, "s": 25740, "text": "Parameters: This function accepts two parameters as mentioned above and defined below: " }, { "code": null, "e": 25926, "s": 25829, "text": "radius: This parameter is used to store the size of the Gaussian operator. Default value is 10.0" }, { "code": null, "e": 26060, "s": 25926, "text": "strength: This parameter is used to store the percentage of blur mask to apply. Default value is 12.5 and it can range from 0 to 100." }, { "code": null, "e": 26125, "s": 26060, "text": "Return Value: This function returns the Wand ImageMagick object." }, { "code": null, "e": 26143, "s": 26125, "text": "Original Image: " }, { "code": null, "e": 26156, "s": 26143, "text": "Example 1: " }, { "code": null, "e": 26164, "s": 26156, "text": "Python3" }, { "code": "# Import library from Imagefrom wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as local_contrast: # Invoke local_contrast function with radius 12 and sigma 3 local_contrast.local_contrast(12, 3) # Save the image local_contrast.save(filename ='local_contrast1.jpg')", "e": 26570, "s": 26164, "text": null }, { "code": null, "e": 26580, "s": 26570, "text": "Output: " }, { "code": null, "e": 26593, "s": 26580, "text": "Example 2: " }, { "code": null, "e": 26601, "s": 26593, "text": "Python3" }, { "code": "# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke local_contrast function with radius 15 and sigma 78 pic.local_contrast(15, 78) # Save the image pic.save(filename ='local_contrast2.jpg')", "e": 27644, "s": 26601, "text": null }, { "code": null, "e": 27654, "s": 27644, "text": "Output: " }, { "code": null, "e": 27671, "s": 27656, "text": "sagartomar9927" }, { "code": null, "e": 27688, "s": 27671, "text": "Image-Processing" }, { "code": null, "e": 27700, "s": 27688, "text": "Python-wand" }, { "code": null, "e": 27707, "s": 27700, "text": "Python" }, { "code": null, "e": 27805, "s": 27707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27837, "s": 27805, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27879, "s": 27837, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27921, "s": 27879, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27977, "s": 27921, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28004, "s": 27977, "text": "Python Classes and Objects" }, { "code": null, "e": 28035, "s": 28004, "text": "Python | os.path.join() method" }, { "code": null, "e": 28074, "s": 28035, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28103, "s": 28074, "text": "Create a directory in Python" }, { "code": null, "e": 28125, "s": 28103, "text": "Defaultdict in Python" } ]
Intersection of n sets - GeeksforGeeks
23 Feb, 2022 Given n sets of integers of different sizes. Each set may contain duplicates also. How to find the intersection of all the sets. If an element is present multiple times in all the sets, it should be added that many times in the result.For example, consider there are three sets {1,2,2,3,4} {2,2,3,5,6} {1,3,2,2,6}. The intersection of the given sets should be {2,2,3}The following is an efficient approach to solve this problem.1. Sort all the sets. 2. Take the smallest set, and insert all the elements, and their frequencies into a map. 3. For each element in the map do the following .....a. If the element is not present in any set, ignore it .....b. Find the frequency of the element in each set (using binary search). If it less than the frequency in the map, update the frequency .....c. If the element is found in all the sets, add it to the result.Here is the C++ implementation of the above approach. CPP // C++ program to find intersection of n sets#include <iostream>#include <vector>#include <algorithm>#include <map>using namespace std; // The main function that receives a set of sets as parameter and// returns a set containing intersection of all setsvector <int> getIntersection(vector < vector <int> > &sets){ vector <int> result; // To store the resultant set int smallSetInd = 0; // Initialize index of smallest set int minSize = sets[0].size(); // Initialize size of smallest set // sort all the sets, and also find the smallest set for (int i = 1 ; i < sets.size() ; i++) { // sort this set sort(sets[i].begin(), sets[i].end()); // update minSize, if needed if (minSize > sets[i].size()) { minSize = sets[i].size(); smallSetInd = i; } } map<int,int> elementsMap; // Add all the elements of smallest set to a map, if already present, // update the frequency for (int i = 0; i < sets[smallSetInd].size(); i++) { if (elementsMap.find( sets[smallSetInd][i] ) == elementsMap.end()) elementsMap[ sets[smallSetInd][i] ] = 1; else elementsMap[ sets[smallSetInd][i] ]++; } // iterate through the map elements to see if they are present in // remaining sets map<int,int>::iterator it; for (it = elementsMap.begin(); it != elementsMap.end(); ++it) { int elem = it->first; int freq = it->second; bool bFound = true; // Iterate through all sets for (int j = 0 ; j < sets.size() ; j++) { // If this set is not the smallest set, then do binary search in it if (j != smallSetInd) { // If the element is found in this set, then find its frequency if (binary_search( sets[j].begin(), sets[j].end(), elem )) { int lInd = lower_bound(sets[j].begin(), sets[j].end(), elem) - sets[j].begin(); int rInd = upper_bound(sets[j].begin(), sets[j].end(), elem) - sets[j].begin(); // Update the minimum frequency, if needed if ((rInd - lInd) < freq) freq = rInd - lInd; } // If the element is not present in any set, then no need // to proceed for this element. else { bFound = false; break; } } } // If element was found in all sets, then add it to result 'freq' times if (bFound) { for (int k = 0; k < freq; k++) result.push_back(elem); } } return result;} // A utility function to print a set of elementsvoid printset(vector <int> set){ for (int i = 0 ; i < set.size() ; i++) cout<<set[i]<<" ";} // Test casevoid TestCase1(){ vector < vector <int> > sets; vector <int> set1; set1.push_back(1); set1.push_back(1); set1.push_back(2); set1.push_back(2); set1.push_back(5); sets.push_back(set1); vector <int> set2; set2.push_back(1); set2.push_back(1); set2.push_back(4); set2.push_back(3); set2.push_back(5); set2.push_back(9); sets.push_back(set2); vector <int> set3; set3.push_back(1); set3.push_back(1); set3.push_back(2); set3.push_back(3); set3.push_back(5); set3.push_back(6); sets.push_back(set3); vector <int> r = getIntersection(sets); printset(r); } // Driver program to test above functionsint main(){ TestCase1(); return 0;} Output: 1 1 5 Time Complexity: Let there be ‘n’ lists, and average size of lists be ‘m’. Sorting phase takes O( n* m *log m) time (Sorting n lists with average length m). Searching phase takes O( m * n * log m) time . ( for each element in a list, we are searching n lists with log m time). So the overall time complexity is O( n*m*log m ).Auxiliary Space: O(m) space for storing the map.This article is compiled by Ravi Chandra Enaganti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. simmytarika5 Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Activation Functions Characteristics of Internet of Things Advantages and Disadvantages of OOP Sensors in Internet of Things(IoT) Challenges in Internet of things (IoT) Election algorithm and distributed processing Introduction to Internet of Things (IoT) | Set 1 Introduction to Electronic Mail Communication Models in IoT (Internet of Things )
[ { "code": null, "e": 25919, "s": 25891, "text": "\n23 Feb, 2022" }, { "code": null, "e": 26831, "s": 25919, "text": "Given n sets of integers of different sizes. Each set may contain duplicates also. How to find the intersection of all the sets. If an element is present multiple times in all the sets, it should be added that many times in the result.For example, consider there are three sets {1,2,2,3,4} {2,2,3,5,6} {1,3,2,2,6}. The intersection of the given sets should be {2,2,3}The following is an efficient approach to solve this problem.1. Sort all the sets. 2. Take the smallest set, and insert all the elements, and their frequencies into a map. 3. For each element in the map do the following .....a. If the element is not present in any set, ignore it .....b. Find the frequency of the element in each set (using binary search). If it less than the frequency in the map, update the frequency .....c. If the element is found in all the sets, add it to the result.Here is the C++ implementation of the above approach. " }, { "code": null, "e": 26835, "s": 26831, "text": "CPP" }, { "code": "// C++ program to find intersection of n sets#include <iostream>#include <vector>#include <algorithm>#include <map>using namespace std; // The main function that receives a set of sets as parameter and// returns a set containing intersection of all setsvector <int> getIntersection(vector < vector <int> > &sets){ vector <int> result; // To store the resultant set int smallSetInd = 0; // Initialize index of smallest set int minSize = sets[0].size(); // Initialize size of smallest set // sort all the sets, and also find the smallest set for (int i = 1 ; i < sets.size() ; i++) { // sort this set sort(sets[i].begin(), sets[i].end()); // update minSize, if needed if (minSize > sets[i].size()) { minSize = sets[i].size(); smallSetInd = i; } } map<int,int> elementsMap; // Add all the elements of smallest set to a map, if already present, // update the frequency for (int i = 0; i < sets[smallSetInd].size(); i++) { if (elementsMap.find( sets[smallSetInd][i] ) == elementsMap.end()) elementsMap[ sets[smallSetInd][i] ] = 1; else elementsMap[ sets[smallSetInd][i] ]++; } // iterate through the map elements to see if they are present in // remaining sets map<int,int>::iterator it; for (it = elementsMap.begin(); it != elementsMap.end(); ++it) { int elem = it->first; int freq = it->second; bool bFound = true; // Iterate through all sets for (int j = 0 ; j < sets.size() ; j++) { // If this set is not the smallest set, then do binary search in it if (j != smallSetInd) { // If the element is found in this set, then find its frequency if (binary_search( sets[j].begin(), sets[j].end(), elem )) { int lInd = lower_bound(sets[j].begin(), sets[j].end(), elem) - sets[j].begin(); int rInd = upper_bound(sets[j].begin(), sets[j].end(), elem) - sets[j].begin(); // Update the minimum frequency, if needed if ((rInd - lInd) < freq) freq = rInd - lInd; } // If the element is not present in any set, then no need // to proceed for this element. else { bFound = false; break; } } } // If element was found in all sets, then add it to result 'freq' times if (bFound) { for (int k = 0; k < freq; k++) result.push_back(elem); } } return result;} // A utility function to print a set of elementsvoid printset(vector <int> set){ for (int i = 0 ; i < set.size() ; i++) cout<<set[i]<<\" \";} // Test casevoid TestCase1(){ vector < vector <int> > sets; vector <int> set1; set1.push_back(1); set1.push_back(1); set1.push_back(2); set1.push_back(2); set1.push_back(5); sets.push_back(set1); vector <int> set2; set2.push_back(1); set2.push_back(1); set2.push_back(4); set2.push_back(3); set2.push_back(5); set2.push_back(9); sets.push_back(set2); vector <int> set3; set3.push_back(1); set3.push_back(1); set3.push_back(2); set3.push_back(3); set3.push_back(5); set3.push_back(6); sets.push_back(set3); vector <int> r = getIntersection(sets); printset(r); } // Driver program to test above functionsint main(){ TestCase1(); return 0;}", "e": 30555, "s": 26835, "text": null }, { "code": null, "e": 30564, "s": 30555, "text": "Output: " }, { "code": null, "e": 30570, "s": 30564, "text": "1 1 5" }, { "code": null, "e": 31121, "s": 30570, "text": "Time Complexity: Let there be ‘n’ lists, and average size of lists be ‘m’. Sorting phase takes O( n* m *log m) time (Sorting n lists with average length m). Searching phase takes O( m * n * log m) time . ( for each element in a list, we are searching n lists with log m time). So the overall time complexity is O( n*m*log m ).Auxiliary Space: O(m) space for storing the map.This article is compiled by Ravi Chandra Enaganti. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 31134, "s": 31121, "text": "simmytarika5" }, { "code": null, "e": 31139, "s": 31134, "text": "Misc" }, { "code": null, "e": 31144, "s": 31139, "text": "Misc" }, { "code": null, "e": 31149, "s": 31144, "text": "Misc" }, { "code": null, "e": 31247, "s": 31149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31268, "s": 31247, "text": "Activation Functions" }, { "code": null, "e": 31306, "s": 31268, "text": "Characteristics of Internet of Things" }, { "code": null, "e": 31342, "s": 31306, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 31377, "s": 31342, "text": "Sensors in Internet of Things(IoT)" }, { "code": null, "e": 31416, "s": 31377, "text": "Challenges in Internet of things (IoT)" }, { "code": null, "e": 31462, "s": 31416, "text": "Election algorithm and distributed processing" }, { "code": null, "e": 31511, "s": 31462, "text": "Introduction to Internet of Things (IoT) | Set 1" }, { "code": null, "e": 31543, "s": 31511, "text": "Introduction to Electronic Mail" } ]
Python Pillow - Blur an Image - GeeksforGeeks
28 Apr, 2022 Blurring an image is a process of reducing the level of noise in the image, and it is one of the important aspects of image processing. In this article, we will learn to blur an image using a pillow library. To blur an image we make use of some methods of ImageFilter class of this library on image objects. Note: The image used to blur in all different methods is given below: 1. PIL.ImageFilter.BoxBlur(): Blurs the image by setting each pixel to the average value of the pixels in a square box extending radius pixels in each direction. Supports float radius of arbitrary size. Uses an optimized implementation that runs in linear time relative to the size of the image for any radius value. Syntax: PIL.ImageFilter.BoxBlur(radius) Parameters: radius: Size of the box in one direction. Radius 0 does not blur, returns an identical image. Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total. Python3 # Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"geek.jpg") # Blurring the imageim1 = im.filter(ImageFilter.BoxBlur(4)) # Shows the image in image viewerim1.show() Output : 2. PIL.ImageFilter.GaussianBlur(): This method creates a Gaussian blur filter. The filter uses radius as a parameter and by changing the value of this radius, the intensity of the blur over the image gets changed. The parameter radius in the function is responsible for the blur intensity. By changing the value of the radius, the intensity of GaussianBlur is changed. Syntax: PIL.ImageFilter.GaussianBlur(radius=5) Parameters: radius – blur radius. Changing value of radius the different intensity of GaussianBlur image were obtain. Returns type: An image. Python3 # Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"geek.jpg") # Blurring the imageim1 = im.filter(ImageFilter.GaussianBlur(4)) # Shows the image in image viewerim1.show() Output : 3. Simple blur: It applies a blurring effect to the image as specified through a specific kernel or a convolution matrix. It does not require any parameters. Syntax: filter(ImageFilter.BLUR) Python3 # Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"geek.jpg") # Blurring the imageim1 = im.filter(ImageFilter.BLUR) # Shows the image in image viewerim1.show() Output : simranarora5sos kalrap615 simmytarika5 Picked Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n28 Apr, 2022" }, { "code": null, "e": 25845, "s": 25537, "text": "Blurring an image is a process of reducing the level of noise in the image, and it is one of the important aspects of image processing. In this article, we will learn to blur an image using a pillow library. To blur an image we make use of some methods of ImageFilter class of this library on image objects." }, { "code": null, "e": 25915, "s": 25845, "text": "Note: The image used to blur in all different methods is given below:" }, { "code": null, "e": 26232, "s": 25915, "text": "1. PIL.ImageFilter.BoxBlur(): Blurs the image by setting each pixel to the average value of the pixels in a square box extending radius pixels in each direction. Supports float radius of arbitrary size. Uses an optimized implementation that runs in linear time relative to the size of the image for any radius value." }, { "code": null, "e": 26272, "s": 26232, "text": "Syntax: PIL.ImageFilter.BoxBlur(radius)" }, { "code": null, "e": 26286, "s": 26272, "text": "Parameters: " }, { "code": null, "e": 26446, "s": 26286, "text": "radius: Size of the box in one direction. Radius 0 does not blur, returns an identical image. Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total." }, { "code": null, "e": 26454, "s": 26446, "text": "Python3" }, { "code": "# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r\"geek.jpg\") # Blurring the imageim1 = im.filter(ImageFilter.BoxBlur(4)) # Shows the image in image viewerim1.show()", "e": 26675, "s": 26454, "text": null }, { "code": null, "e": 26686, "s": 26675, "text": "Output : " }, { "code": null, "e": 27056, "s": 26686, "text": " 2. PIL.ImageFilter.GaussianBlur(): This method creates a Gaussian blur filter. The filter uses radius as a parameter and by changing the value of this radius, the intensity of the blur over the image gets changed. The parameter radius in the function is responsible for the blur intensity. By changing the value of the radius, the intensity of GaussianBlur is changed." }, { "code": null, "e": 27103, "s": 27056, "text": "Syntax: PIL.ImageFilter.GaussianBlur(radius=5)" }, { "code": null, "e": 27115, "s": 27103, "text": "Parameters:" }, { "code": null, "e": 27221, "s": 27115, "text": "radius – blur radius. Changing value of radius the different intensity of GaussianBlur image were obtain." }, { "code": null, "e": 27245, "s": 27221, "text": "Returns type: An image." }, { "code": null, "e": 27253, "s": 27245, "text": "Python3" }, { "code": "# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r\"geek.jpg\") # Blurring the imageim1 = im.filter(ImageFilter.GaussianBlur(4)) # Shows the image in image viewerim1.show()", "e": 27479, "s": 27253, "text": null }, { "code": null, "e": 27489, "s": 27479, "text": "Output : " }, { "code": null, "e": 27647, "s": 27489, "text": "3. Simple blur: It applies a blurring effect to the image as specified through a specific kernel or a convolution matrix. It does not require any parameters." }, { "code": null, "e": 27680, "s": 27647, "text": "Syntax: filter(ImageFilter.BLUR)" }, { "code": null, "e": 27688, "s": 27680, "text": "Python3" }, { "code": "# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r\"geek.jpg\") # Blurring the imageim1 = im.filter(ImageFilter.BLUR) # Shows the image in image viewerim1.show()", "e": 27903, "s": 27688, "text": null }, { "code": null, "e": 27912, "s": 27903, "text": "Output :" }, { "code": null, "e": 27928, "s": 27912, "text": "simranarora5sos" }, { "code": null, "e": 27938, "s": 27928, "text": "kalrap615" }, { "code": null, "e": 27951, "s": 27938, "text": "simmytarika5" }, { "code": null, "e": 27958, "s": 27951, "text": "Picked" }, { "code": null, "e": 27969, "s": 27958, "text": "Python-pil" }, { "code": null, "e": 27976, "s": 27969, "text": "Python" }, { "code": null, "e": 28074, "s": 27976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28106, "s": 28074, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28148, "s": 28106, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28190, "s": 28148, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28246, "s": 28190, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28273, "s": 28246, "text": "Python Classes and Objects" }, { "code": null, "e": 28312, "s": 28273, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28343, "s": 28312, "text": "Python | os.path.join() method" }, { "code": null, "e": 28372, "s": 28343, "text": "Create a directory in Python" }, { "code": null, "e": 28394, "s": 28372, "text": "Defaultdict in Python" } ]
Pattern compile(String) method in Java with Examples - GeeksforGeeks
31 Aug, 2021 The compile(String) method of the Pattern class in Java is used to create a pattern from the regular expression passed as parameter to method. Whenever you need to match a text against a regular expression pattern more than one time, create a Pattern instance using the Pattern.compile() method.Syntax: public static Pattern compile(String regex) Parameters: This method accepts one single parameter regex which represents the given regular expression compiled into a pattern.Return Value: This method returns the pattern compiled from the regex passed to the method as a parameter.Exception: This method throws following exception: PatternSyntaxException: This exception is thrown if the expression’s syntax is invalid. Below programs illustrate the compile(String) method: Program 1: Java // Java program to demonstrate// Pattern.compile() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // create a REGEX String String REGEX = ".*www.*"; // creare the string // in which you want to search String actualString = "www.geeksforgeeks.org"; // compile the regex to create pattern // using compile() method Pattern pattern = Pattern.compile(REGEX); // get a matcher object from pattern Matcher matcher = pattern.matcher(actualString); // check whether Regex string is // found in actualString or not boolean matches = matcher.matches(); System.out.println("actualString " + "contains REGEX = " + matches); }} actualString contains REGEX = true Program 2: Java // Java program to demonstrate// Pattern.compile method import java.util.regex.*; public class GFG { public static void main(String[] args) { // create a REGEX String String REGEX = "brave"; // creare the string // in which you want to search String actualString = "Cat is cute"; // compile the regex to create pattern // using compile() method Pattern pattern = Pattern.compile(REGEX); // check whether Regex string is // found in actualString or not boolean matches = pattern .matcher(actualString) .matches(); System.out.println("actualString " + "contains REGEX = " + matches); }} actualString contains REGEX = false Reference: https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#compile(java.lang.String) badjatiyaanimesh singghakshay Java 8 Java-Functions Java-Pattern Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Collections in Java Queue Interface In Java
[ { "code": null, "e": 25645, "s": 25617, "text": "\n31 Aug, 2021" }, { "code": null, "e": 25949, "s": 25645, "text": "The compile(String) method of the Pattern class in Java is used to create a pattern from the regular expression passed as parameter to method. Whenever you need to match a text against a regular expression pattern more than one time, create a Pattern instance using the Pattern.compile() method.Syntax: " }, { "code": null, "e": 25993, "s": 25949, "text": "public static Pattern compile(String regex)" }, { "code": null, "e": 26281, "s": 25993, "text": "Parameters: This method accepts one single parameter regex which represents the given regular expression compiled into a pattern.Return Value: This method returns the pattern compiled from the regex passed to the method as a parameter.Exception: This method throws following exception: " }, { "code": null, "e": 26369, "s": 26281, "text": "PatternSyntaxException: This exception is thrown if the expression’s syntax is invalid." }, { "code": null, "e": 26436, "s": 26369, "text": "Below programs illustrate the compile(String) method: Program 1: " }, { "code": null, "e": 26441, "s": 26436, "text": "Java" }, { "code": "// Java program to demonstrate// Pattern.compile() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // create a REGEX String String REGEX = \".*www.*\"; // creare the string // in which you want to search String actualString = \"www.geeksforgeeks.org\"; // compile the regex to create pattern // using compile() method Pattern pattern = Pattern.compile(REGEX); // get a matcher object from pattern Matcher matcher = pattern.matcher(actualString); // check whether Regex string is // found in actualString or not boolean matches = matcher.matches(); System.out.println(\"actualString \" + \"contains REGEX = \" + matches); }}", "e": 27277, "s": 26441, "text": null }, { "code": null, "e": 27312, "s": 27277, "text": "actualString contains REGEX = true" }, { "code": null, "e": 27326, "s": 27314, "text": "Program 2: " }, { "code": null, "e": 27331, "s": 27326, "text": "Java" }, { "code": "// Java program to demonstrate// Pattern.compile method import java.util.regex.*; public class GFG { public static void main(String[] args) { // create a REGEX String String REGEX = \"brave\"; // creare the string // in which you want to search String actualString = \"Cat is cute\"; // compile the regex to create pattern // using compile() method Pattern pattern = Pattern.compile(REGEX); // check whether Regex string is // found in actualString or not boolean matches = pattern .matcher(actualString) .matches(); System.out.println(\"actualString \" + \"contains REGEX = \" + matches); }}", "e": 28134, "s": 27331, "text": null }, { "code": null, "e": 28170, "s": 28134, "text": "actualString contains REGEX = false" }, { "code": null, "e": 28281, "s": 28172, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#compile(java.lang.String)" }, { "code": null, "e": 28298, "s": 28281, "text": "badjatiyaanimesh" }, { "code": null, "e": 28311, "s": 28298, "text": "singghakshay" }, { "code": null, "e": 28318, "s": 28311, "text": "Java 8" }, { "code": null, "e": 28333, "s": 28318, "text": "Java-Functions" }, { "code": null, "e": 28346, "s": 28333, "text": "Java-Pattern" }, { "code": null, "e": 28351, "s": 28346, "text": "Java" }, { "code": null, "e": 28356, "s": 28351, "text": "Java" }, { "code": null, "e": 28454, "s": 28356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28473, "s": 28454, "text": "Interfaces in Java" }, { "code": null, "e": 28488, "s": 28473, "text": "Stream In Java" }, { "code": null, "e": 28506, "s": 28488, "text": "ArrayList in Java" }, { "code": null, "e": 28538, "s": 28506, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28558, "s": 28538, "text": "Stack Class in Java" }, { "code": null, "e": 28590, "s": 28558, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28614, "s": 28590, "text": "Singleton Class in Java" }, { "code": null, "e": 28626, "s": 28614, "text": "Set in Java" }, { "code": null, "e": 28646, "s": 28626, "text": "Collections in Java" } ]
Type Conversion in Python - GeeksforGeeks
13 May, 2022 Python defines type conversion functions to directly convert one data type to another which is useful in day-to-day and competitive programming. This article is aimed at providing information about certain conversion functions. There are two types of Type Conversion in Python: Implicit Type ConversionExplicit Type Conversion Implicit Type Conversion Explicit Type Conversion Let’s discuss them in detail. In Implicit type conversion of data types in Python, the Python interpreter automatically converts one data type to another without any user involvement. To get a more clear view of the topic see the below examples. Example: Python3 x = 10 print("x is of type:",type(x)) y = 10.6print("y is of type:",type(y)) x = x + y print(x)print("x is of type:",type(x)) Output: x is of type: <class 'int'> y is of type: <class 'float'> 20.6 x is of type: <class 'float'> As we can see the type of ‘x’ got automatically changed to the “float” type from the “integer” type. this is a simple case of Implicit type conversion in python. In Explicit Type Conversion in Python, the data type is manually changed by the user as per their requirement. Various forms of explicit type conversion are explained below: 1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base in which string is if the data type is a string.2. float(): This function is used to convert any data type to a floating-point number Python3 # Python code to demonstrate Type conversion# using int(), float() # initializing strings = "10010" # printing string converting to int base 2c = int(s,2)print ("After converting to integer base 2 : ", end="")print (c) # printing string converting to floate = float(s)print ("After converting to float : ", end="")print (e) Output: After converting to integer base 2 : 18 After converting to float : 10010.0 3. ord() : This function is used to convert a character to integer.4. hex() : This function is to convert integer to hexadecimal string.5. oct() : This function is to convert integer to octal string. Python3 # Python code to demonstrate Type conversion# using ord(), hex(), oct() # initializing integers = '4' # printing character converting to integerc = ord(s)print ("After converting character to integer : ",end="")print (c) # printing integer converting to hexadecimal stringc = hex(56)print ("After converting 56 to hexadecimal string : ",end="")print (c) # printing integer converting to octal stringc = oct(56)print ("After converting 56 to octal string : ",end="")print (c) Output: After converting character to integer : 52 After converting 56 to hexadecimal string : 0x38 After converting 56 to octal string : 0o70 6. tuple() : This function is used to convert to a tuple.7. set() : This function returns the type after converting to set.8. list() : This function is used to convert any data type to a list type. Python3 # Python code to demonstrate Type conversion# using tuple(), set(), list() # initializing strings = 'geeks' # printing string converting to tuplec = tuple(s)print ("After converting string to tuple : ",end="")print (c) # printing string converting to setc = set(s)print ("After converting string to set : ",end="")print (c) # printing string converting to listc = list(s)print ("After converting string to list : ",end="")print (c) Output: After converting string to tuple : ('g', 'e', 'e', 'k', 's') After converting string to set : {'k', 'e', 's', 'g'} After converting string to list : ['g', 'e', 'e', 'k', 's'] 9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary.10. str() : Used to convert integer into a string.11. complex(real,imag) : This function converts real numbers to complex(real,imag) number. Python3 # Python code to demonstrate Type conversion# using dict(), complex(), str() # initializing integersa = 1b = 2 # initializing tupletup = (('a', 1) ,('f', 2), ('g', 3)) # printing integer converting to complex numberc = complex(1,2)print ("After converting integer to complex number : ",end="")print (c) # printing integer converting to stringc = str(a)print ("After converting integer to string : ",end="")print (c) # printing tuple converting to expression dictionaryc = dict(tup)print ("After converting tuple to dictionary : ",end="")print (c) Output: After converting integer to complex number : (1+2j) After converting integer to string : 1 After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3} 12. chr(number): This function converts number to its corresponding ASCII character. Python3 # Convert ASCII value to charactersa = chr(76)b = chr(77) print(a)print(b) Output: L M YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial - Type Conversion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=clF_Saane-I" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> SivaSukumarReddy RajuKumar19 dj8264 base-conversion Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python
[ { "code": null, "e": 24971, "s": 24943, "text": "\n13 May, 2022" }, { "code": null, "e": 25199, "s": 24971, "text": "Python defines type conversion functions to directly convert one data type to another which is useful in day-to-day and competitive programming. This article is aimed at providing information about certain conversion functions." }, { "code": null, "e": 25249, "s": 25199, "text": "There are two types of Type Conversion in Python:" }, { "code": null, "e": 25298, "s": 25249, "text": "Implicit Type ConversionExplicit Type Conversion" }, { "code": null, "e": 25323, "s": 25298, "text": "Implicit Type Conversion" }, { "code": null, "e": 25348, "s": 25323, "text": "Explicit Type Conversion" }, { "code": null, "e": 25378, "s": 25348, "text": "Let’s discuss them in detail." }, { "code": null, "e": 25594, "s": 25378, "text": "In Implicit type conversion of data types in Python, the Python interpreter automatically converts one data type to another without any user involvement. To get a more clear view of the topic see the below examples." }, { "code": null, "e": 25603, "s": 25594, "text": "Example:" }, { "code": null, "e": 25611, "s": 25603, "text": "Python3" }, { "code": "x = 10 print(\"x is of type:\",type(x)) y = 10.6print(\"y is of type:\",type(y)) x = x + y print(x)print(\"x is of type:\",type(x))", "e": 25741, "s": 25611, "text": null }, { "code": null, "e": 25749, "s": 25741, "text": "Output:" }, { "code": null, "e": 25842, "s": 25749, "text": "x is of type: <class 'int'>\ny is of type: <class 'float'>\n20.6\nx is of type: <class 'float'>" }, { "code": null, "e": 26004, "s": 25842, "text": "As we can see the type of ‘x’ got automatically changed to the “float” type from the “integer” type. this is a simple case of Implicit type conversion in python." }, { "code": null, "e": 26179, "s": 26004, "text": "In Explicit Type Conversion in Python, the data type is manually changed by the user as per their requirement. Various forms of explicit type conversion are explained below: " }, { "code": null, "e": 26406, "s": 26179, "text": "1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base in which string is if the data type is a string.2. float(): This function is used to convert any data type to a floating-point number " }, { "code": null, "e": 26414, "s": 26406, "text": "Python3" }, { "code": "# Python code to demonstrate Type conversion# using int(), float() # initializing strings = \"10010\" # printing string converting to int base 2c = int(s,2)print (\"After converting to integer base 2 : \", end=\"\")print (c) # printing string converting to floate = float(s)print (\"After converting to float : \", end=\"\")print (e)", "e": 26741, "s": 26414, "text": null }, { "code": null, "e": 26750, "s": 26741, "text": "Output: " }, { "code": null, "e": 26826, "s": 26750, "text": "After converting to integer base 2 : 18\nAfter converting to float : 10010.0" }, { "code": null, "e": 27026, "s": 26826, "text": "3. ord() : This function is used to convert a character to integer.4. hex() : This function is to convert integer to hexadecimal string.5. oct() : This function is to convert integer to octal string." }, { "code": null, "e": 27034, "s": 27026, "text": "Python3" }, { "code": "# Python code to demonstrate Type conversion# using ord(), hex(), oct() # initializing integers = '4' # printing character converting to integerc = ord(s)print (\"After converting character to integer : \",end=\"\")print (c) # printing integer converting to hexadecimal stringc = hex(56)print (\"After converting 56 to hexadecimal string : \",end=\"\")print (c) # printing integer converting to octal stringc = oct(56)print (\"After converting 56 to octal string : \",end=\"\")print (c)", "e": 27514, "s": 27034, "text": null }, { "code": null, "e": 27523, "s": 27514, "text": "Output: " }, { "code": null, "e": 27658, "s": 27523, "text": "After converting character to integer : 52\nAfter converting 56 to hexadecimal string : 0x38\nAfter converting 56 to octal string : 0o70" }, { "code": null, "e": 27856, "s": 27658, "text": "6. tuple() : This function is used to convert to a tuple.7. set() : This function returns the type after converting to set.8. list() : This function is used to convert any data type to a list type." }, { "code": null, "e": 27864, "s": 27856, "text": "Python3" }, { "code": "# Python code to demonstrate Type conversion# using tuple(), set(), list() # initializing strings = 'geeks' # printing string converting to tuplec = tuple(s)print (\"After converting string to tuple : \",end=\"\")print (c) # printing string converting to setc = set(s)print (\"After converting string to set : \",end=\"\")print (c) # printing string converting to listc = list(s)print (\"After converting string to list : \",end=\"\")print (c)", "e": 28301, "s": 27864, "text": null }, { "code": null, "e": 28310, "s": 28301, "text": "Output: " }, { "code": null, "e": 28485, "s": 28310, "text": "After converting string to tuple : ('g', 'e', 'e', 'k', 's')\nAfter converting string to set : {'k', 'e', 's', 'g'}\nAfter converting string to list : ['g', 'e', 'e', 'k', 's']" }, { "code": null, "e": 28718, "s": 28485, "text": "9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary.10. str() : Used to convert integer into a string.11. complex(real,imag) : This function converts real numbers to complex(real,imag) number." }, { "code": null, "e": 28726, "s": 28718, "text": "Python3" }, { "code": "# Python code to demonstrate Type conversion# using dict(), complex(), str() # initializing integersa = 1b = 2 # initializing tupletup = (('a', 1) ,('f', 2), ('g', 3)) # printing integer converting to complex numberc = complex(1,2)print (\"After converting integer to complex number : \",end=\"\")print (c) # printing integer converting to stringc = str(a)print (\"After converting integer to string : \",end=\"\")print (c) # printing tuple converting to expression dictionaryc = dict(tup)print (\"After converting tuple to dictionary : \",end=\"\")print (c)", "e": 29279, "s": 28726, "text": null }, { "code": null, "e": 29288, "s": 29279, "text": "Output: " }, { "code": null, "e": 29443, "s": 29288, "text": "After converting integer to complex number : (1+2j)\nAfter converting integer to string : 1\nAfter converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}" }, { "code": null, "e": 29529, "s": 29443, "text": "12. chr(number): This function converts number to its corresponding ASCII character. " }, { "code": null, "e": 29537, "s": 29529, "text": "Python3" }, { "code": "# Convert ASCII value to charactersa = chr(76)b = chr(77) print(a)print(b)", "e": 29613, "s": 29537, "text": null }, { "code": null, "e": 29622, "s": 29613, "text": "Output: " }, { "code": null, "e": 29628, "s": 29622, "text": "L\nM\n " }, { "code": null, "e": 30472, "s": 29628, "text": "YouTubeGeeksforGeeks507K subscribersPython Programming Tutorial - Type Conversion | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:53•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=clF_Saane-I\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 30489, "s": 30472, "text": "SivaSukumarReddy" }, { "code": null, "e": 30501, "s": 30489, "text": "RajuKumar19" }, { "code": null, "e": 30508, "s": 30501, "text": "dj8264" }, { "code": null, "e": 30524, "s": 30508, "text": "base-conversion" }, { "code": null, "e": 30531, "s": 30524, "text": "Python" }, { "code": null, "e": 30629, "s": 30531, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30657, "s": 30629, "text": "Read JSON file using Python" }, { "code": null, "e": 30707, "s": 30657, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 30729, "s": 30707, "text": "Python map() function" }, { "code": null, "e": 30773, "s": 30729, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 30791, "s": 30773, "text": "Python Dictionary" }, { "code": null, "e": 30826, "s": 30791, "text": "Read a file line by line in Python" }, { "code": null, "e": 30858, "s": 30826, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30880, "s": 30858, "text": "Enumerate() in Python" }, { "code": null, "e": 30922, "s": 30880, "text": "Different ways to create Pandas Dataframe" } ]
Make an area plot in Python using Bokeh - GeeksforGeeks
22 Jun, 2020 Bokeh is a Python interactive data visualization. Unlike Matplotlib and Seaborn, Bokeh renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Area plots are defined as the filled regions between two series that share a common areas. Bokeh Figure class has two methods which are given below: varea() harea() 1. varea() method: varea() method is a vertical directed area which has one x coordinate array and two y coordinate arrays, y1 and y2, that will be filled between. Syntax: varea(x, y1, y2, **kwargs) Parameter:This method accept the following parameters that are described below: x: This parameter is the x-coordinates for the points of the area. y1: This parameter is the y-coordinates for the points of one side of the area. y2: This parameter is the y-coordinates for the points of other side of the area. Example: Python3 # Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show x = [1, 2, 3, 4, 5]y1 = [2, 4, 5, 2, 4]y2 = [1, 2, 2, 3, 6] output_file("geeksforgeeks.html") p = figure(plot_width=300, plot_height=300) # area plotp.varea(x=x, y1=y1, y2=y2,fill_color="green") show(p) Output: 2. harea() method: harea() method is a horizontal directed area which has one x coordinate array and two y coordinate arrays, y1 and y2, that will be filled between. Syntax: harea(x1, x2, y, **kwargs) Parameter:This method accept the following parameters that are described below: x1: This parameter is the x-coordinates for the points of one side of the area. x2: This parameter is the x-coordinates for the points of other side of the area. y: This parameter is the y-coordinates for the points of the area. Example: Python3 # Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show y = [1, 2, 3, 4, 5]x1 = [2, 4, 5, 2, 4]x2 = [1, 2, 2, 3, 6] output_file("geeksforgeeks.html") p = figure(plot_width=300, plot_height=300) # area plotp.harea(x1=x1, x2=x2, y=y,fill_color="green") show(p) Output: Python-Bokeh Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 25565, "s": 25537, "text": "\n22 Jun, 2020" }, { "code": null, "e": 25840, "s": 25565, "text": "Bokeh is a Python interactive data visualization. Unlike Matplotlib and Seaborn, Bokeh renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity." }, { "code": null, "e": 25989, "s": 25840, "text": "Area plots are defined as the filled regions between two series that share a common areas. Bokeh Figure class has two methods which are given below:" }, { "code": null, "e": 25997, "s": 25989, "text": "varea()" }, { "code": null, "e": 26005, "s": 25997, "text": "harea()" }, { "code": null, "e": 26170, "s": 26005, "text": "1. varea() method: varea() method is a vertical directed area which has one x coordinate array and two y coordinate arrays, y1 and y2, that will be filled between." }, { "code": null, "e": 26205, "s": 26170, "text": "Syntax: varea(x, y1, y2, **kwargs)" }, { "code": null, "e": 26285, "s": 26205, "text": "Parameter:This method accept the following parameters that are described below:" }, { "code": null, "e": 26352, "s": 26285, "text": "x: This parameter is the x-coordinates for the points of the area." }, { "code": null, "e": 26432, "s": 26352, "text": "y1: This parameter is the y-coordinates for the points of one side of the area." }, { "code": null, "e": 26514, "s": 26432, "text": "y2: This parameter is the y-coordinates for the points of other side of the area." }, { "code": null, "e": 26523, "s": 26514, "text": "Example:" }, { "code": null, "e": 26531, "s": 26523, "text": "Python3" }, { "code": "# Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show x = [1, 2, 3, 4, 5]y1 = [2, 4, 5, 2, 4]y2 = [1, 2, 2, 3, 6] output_file(\"geeksforgeeks.html\") p = figure(plot_width=300, plot_height=300) # area plotp.varea(x=x, y1=y1, y2=y2,fill_color=\"green\") show(p)", "e": 26855, "s": 26531, "text": null }, { "code": null, "e": 26863, "s": 26855, "text": "Output:" }, { "code": null, "e": 27030, "s": 26863, "text": "2. harea() method: harea() method is a horizontal directed area which has one x coordinate array and two y coordinate arrays, y1 and y2, that will be filled between." }, { "code": null, "e": 27065, "s": 27030, "text": "Syntax: harea(x1, x2, y, **kwargs)" }, { "code": null, "e": 27145, "s": 27065, "text": "Parameter:This method accept the following parameters that are described below:" }, { "code": null, "e": 27225, "s": 27145, "text": "x1: This parameter is the x-coordinates for the points of one side of the area." }, { "code": null, "e": 27307, "s": 27225, "text": "x2: This parameter is the x-coordinates for the points of other side of the area." }, { "code": null, "e": 27374, "s": 27307, "text": "y: This parameter is the y-coordinates for the points of the area." }, { "code": null, "e": 27383, "s": 27374, "text": "Example:" }, { "code": null, "e": 27391, "s": 27383, "text": "Python3" }, { "code": "# Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show y = [1, 2, 3, 4, 5]x1 = [2, 4, 5, 2, 4]x2 = [1, 2, 2, 3, 6] output_file(\"geeksforgeeks.html\") p = figure(plot_width=300, plot_height=300) # area plotp.harea(x1=x1, x2=x2, y=y,fill_color=\"green\") show(p)", "e": 27715, "s": 27391, "text": null }, { "code": null, "e": 27723, "s": 27715, "text": "Output:" }, { "code": null, "e": 27736, "s": 27723, "text": "Python-Bokeh" }, { "code": null, "e": 27743, "s": 27736, "text": "Python" }, { "code": null, "e": 27841, "s": 27743, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27869, "s": 27841, "text": "Read JSON file using Python" }, { "code": null, "e": 27919, "s": 27869, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27941, "s": 27919, "text": "Python map() function" }, { "code": null, "e": 27985, "s": 27941, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 28003, "s": 27985, "text": "Python Dictionary" }, { "code": null, "e": 28026, "s": 28003, "text": "Taking input in Python" }, { "code": null, "e": 28061, "s": 28026, "text": "Read a file line by line in Python" }, { "code": null, "e": 28093, "s": 28061, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28115, "s": 28093, "text": "Enumerate() in Python" } ]
Python | Program to implement Jumbled word game - GeeksforGeeks
13 Sep, 2021 Python is a multipurpose language and one can do literally anything with it. Python can also be used for game development. Let’s create a simple Jumbled word game without using any external game libraries like PyGame. Jumbled word game: Jumbled word is given to player, player has to rearrange the characters of the word to make a correct meaningful word. Example : Input: erwta Output: water Input: mehtatasmci Output: mathematics Input: keseg Output: geeks This is a two players game, firstly program pick a random word from the given list of words using choice() method of random module. After shuffling the characters of picked word using sample method of random module and shows the jumbled word on the screen. Current player should give the answer; if it gives the correct answer after rearranging the characters then player’s score is incremented by one otherwise not. After quitting the game, winner is decided on the basis of scores. Using Inbuilt functions : choice() method randomly choose any word from the list. sample() method shuffling the characters of the word. User-defined functions : choose() : Choosing random word from the list . jumble() : Shuffling the characters of the chosen word. we have to pass a chosen word as an argument. thank() : Showing the final scores of both players. Pass a player1 name, player2 name and score of player1, player2 as an argument. check_win() : Declaring the winner. Pass a player1 name, player2 name, and score of player1 and player2 as argument. play() : Starting the game. Below is the implementation : Python3 # Python program for jumbled words game. # import random moduleimport random # function for choosing random word.def choose(): # list of word words = ['rainbow', 'computer', 'science', 'programming', 'mathematics', 'player', 'condition', 'reverse', 'water', 'board', 'geeks'] # choice() method randomly choose # any word from the list. pick = random.choice(words) return pick # Function for shuffling the# characters of the chosen word.def jumble(word): # sample() method shuffling the characters of the word random_word = random.sample(word, len(word)) # join() method join the elements # of the iterator(e.g. list) with particular character . jumbled = ''.join(random_word) return jumbled # Function for showing final score.def thank(p1n, p2n, p1, p2): print(p1n, 'Your score is :', p1) print(p2n, 'Your score is :', p2) # check_win() function calling check_win(p1n, p2n, p1, p2) print('Thanks for playing...') # Function for declaring winnerdef check_win(player1, player2, p1score, p2score): if p1score > p2score: print("winner is :", player1) elif p2score > p1score: print("winner is :", player2) else: print("Draw..Well Played guys..") # Function for playing the game.def play(): # enter player1 and player2 name p1name = input("player 1, Please enter your name :") p2name = input("Player 2 , Please enter your name: ") # variable for counting score. pp1 = 0 pp2 = 0 # variable for counting turn turn = 0 # keep looping while True: # choose() function calling picked_word = choose() # jumble() function calling qn = jumble(picked_word) print("jumbled word is :", qn) # checking turn is odd or even if turn % 2 == 0: # if turn no. is even # player1 turn print(p1name, 'Your Turn.') ans = input("what is in your mind? ") # checking ans is equal to picked_word or not if ans == picked_word: # incremented by 1 pp1 += 1 print('Your score is :', pp1) turn += 1 else: print("Better luck next time ..") # player 2 turn print(p2name, 'Your turn.') ans = input('what is in your mind? ') if ans == picked_word: pp2 += 1 print("Your Score is :", pp2) else: print("Better luck next time...correct word is :", picked_word) c = int(input("press 1 to continue and 0 to quit :")) # checking the c is equal to 0 or not # if c is equal to 0 then break out # of the while loop o/w keep looping. if c == 0: # thank() function calling thank(p1name, p2name, pp1, pp2) break else: # if turn no. is odd # player2 turn print(p2name, 'Your turn.') ans = input('what is in your mind? ') if ans == picked_word: pp2 += 1 print("Your Score is :", pp2) turn += 1 else: print("Better luck next time.. :") print(p1name, 'Your turn.') ans = input('what is in your mind? ') if ans == picked_word: pp1 += 1 print("Your Score is :", pp1) else: print("Better luck next time...correct word is :", picked_word) c = int(input("press 1 to continue and 0 to quit :")) if c == 0: # thank() function calling thank(p1name, p2name, pp1, pp2) break c = int(input("press 1 to continue and 0 to quit :")) if c == 0: # thank() function calling thank(p1name, p2name, pp1, pp2) break # Driver codeif __name__ == '__main__': # play() function calling play() Output: player 1, Please enter your name :Ankit Player 2 , Please enter your name: John jumbled word is : abiwrno Ankit Your Turn. what is in your mind? rainbow Your score is : 1 jumbled word is : rbado John Your turn. what is in your mind? borad Better luck next time.. : Ankit Your turn. what is in your mind? board Your Score is : 2 press 1 to continue and 0 to quit :1 jumbled word is : wbrinao John Your turn. what is in your mind? rainbow Your Score is : 1 press 1 to continue and 0 to quit :1 jumbled word is : bnrawio Ankit Your Turn. what is in your mind? rainbow Your score is : 3 jumbled word is : enecsic John Your turn. what is in your mind? science Your Score is : 2 press 1 to continue and 0 to quit :0 Ankit Your score is : 3 John Your score is : 2 winner is : Ankit Thanks for playing... Shivam_k sweetyty sooda367 Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25949, "s": 25921, "text": "\n13 Sep, 2021" }, { "code": null, "e": 26167, "s": 25949, "text": "Python is a multipurpose language and one can do literally anything with it. Python can also be used for game development. Let’s create a simple Jumbled word game without using any external game libraries like PyGame." }, { "code": null, "e": 26305, "s": 26167, "text": "Jumbled word game: Jumbled word is given to player, player has to rearrange the characters of the word to make a correct meaningful word." }, { "code": null, "e": 26316, "s": 26305, "text": "Example : " }, { "code": null, "e": 26411, "s": 26316, "text": "Input: erwta\nOutput: water\n\nInput: mehtatasmci\nOutput: mathematics\n\nInput: keseg\nOutput: geeks" }, { "code": null, "e": 26895, "s": 26411, "text": "This is a two players game, firstly program pick a random word from the given list of words using choice() method of random module. After shuffling the characters of picked word using sample method of random module and shows the jumbled word on the screen. Current player should give the answer; if it gives the correct answer after rearranging the characters then player’s score is incremented by one otherwise not. After quitting the game, winner is decided on the basis of scores." }, { "code": null, "e": 26923, "s": 26895, "text": "Using Inbuilt functions : " }, { "code": null, "e": 27033, "s": 26923, "text": "choice() method randomly choose any word from the list.\nsample() method shuffling the characters of the word." }, { "code": null, "e": 27058, "s": 27033, "text": "User-defined functions :" }, { "code": null, "e": 27485, "s": 27058, "text": "choose() : Choosing random word from the list . jumble() : Shuffling the characters of the chosen word. we have to pass a chosen word as an argument. thank() : Showing the final scores of both players. Pass a player1 name, player2 name and score of player1, player2 as an argument. check_win() : Declaring the winner. Pass a player1 name, player2 name, and score of player1 and player2 as argument. play() : Starting the game." }, { "code": null, "e": 27517, "s": 27485, "text": "Below is the implementation : " }, { "code": null, "e": 27525, "s": 27517, "text": "Python3" }, { "code": "# Python program for jumbled words game. # import random moduleimport random # function for choosing random word.def choose(): # list of word words = ['rainbow', 'computer', 'science', 'programming', 'mathematics', 'player', 'condition', 'reverse', 'water', 'board', 'geeks'] # choice() method randomly choose # any word from the list. pick = random.choice(words) return pick # Function for shuffling the# characters of the chosen word.def jumble(word): # sample() method shuffling the characters of the word random_word = random.sample(word, len(word)) # join() method join the elements # of the iterator(e.g. list) with particular character . jumbled = ''.join(random_word) return jumbled # Function for showing final score.def thank(p1n, p2n, p1, p2): print(p1n, 'Your score is :', p1) print(p2n, 'Your score is :', p2) # check_win() function calling check_win(p1n, p2n, p1, p2) print('Thanks for playing...') # Function for declaring winnerdef check_win(player1, player2, p1score, p2score): if p1score > p2score: print(\"winner is :\", player1) elif p2score > p1score: print(\"winner is :\", player2) else: print(\"Draw..Well Played guys..\") # Function for playing the game.def play(): # enter player1 and player2 name p1name = input(\"player 1, Please enter your name :\") p2name = input(\"Player 2 , Please enter your name: \") # variable for counting score. pp1 = 0 pp2 = 0 # variable for counting turn turn = 0 # keep looping while True: # choose() function calling picked_word = choose() # jumble() function calling qn = jumble(picked_word) print(\"jumbled word is :\", qn) # checking turn is odd or even if turn % 2 == 0: # if turn no. is even # player1 turn print(p1name, 'Your Turn.') ans = input(\"what is in your mind? \") # checking ans is equal to picked_word or not if ans == picked_word: # incremented by 1 pp1 += 1 print('Your score is :', pp1) turn += 1 else: print(\"Better luck next time ..\") # player 2 turn print(p2name, 'Your turn.') ans = input('what is in your mind? ') if ans == picked_word: pp2 += 1 print(\"Your Score is :\", pp2) else: print(\"Better luck next time...correct word is :\", picked_word) c = int(input(\"press 1 to continue and 0 to quit :\")) # checking the c is equal to 0 or not # if c is equal to 0 then break out # of the while loop o/w keep looping. if c == 0: # thank() function calling thank(p1name, p2name, pp1, pp2) break else: # if turn no. is odd # player2 turn print(p2name, 'Your turn.') ans = input('what is in your mind? ') if ans == picked_word: pp2 += 1 print(\"Your Score is :\", pp2) turn += 1 else: print(\"Better luck next time.. :\") print(p1name, 'Your turn.') ans = input('what is in your mind? ') if ans == picked_word: pp1 += 1 print(\"Your Score is :\", pp1) else: print(\"Better luck next time...correct word is :\", picked_word) c = int(input(\"press 1 to continue and 0 to quit :\")) if c == 0: # thank() function calling thank(p1name, p2name, pp1, pp2) break c = int(input(\"press 1 to continue and 0 to quit :\")) if c == 0: # thank() function calling thank(p1name, p2name, pp1, pp2) break # Driver codeif __name__ == '__main__': # play() function calling play()", "e": 31707, "s": 27525, "text": null }, { "code": null, "e": 31716, "s": 31707, "text": "Output: " }, { "code": null, "e": 32515, "s": 31716, "text": "player 1, Please enter your name :Ankit\nPlayer 2 , Please enter your name: John\njumbled word is : abiwrno\nAnkit Your Turn.\nwhat is in your mind? rainbow\nYour score is : 1\njumbled word is : rbado\nJohn Your turn.\nwhat is in your mind? borad\nBetter luck next time.. :\nAnkit Your turn.\nwhat is in your mind? board\nYour Score is : 2\npress 1 to continue and 0 to quit :1\njumbled word is : wbrinao\nJohn Your turn.\nwhat is in your mind? rainbow\nYour Score is : 1\n\npress 1 to continue and 0 to quit :1\n\njumbled word is : bnrawio\nAnkit Your Turn.\nwhat is in your mind? rainbow\nYour score is : 3\njumbled word is : enecsic\nJohn Your turn.\nwhat is in your mind? science\nYour Score is : 2\npress 1 to continue and 0 to quit :0\nAnkit Your score is : 3\nJohn Your score is : 2\nwinner is : Ankit\nThanks for playing..." }, { "code": null, "e": 32526, "s": 32517, "text": "Shivam_k" }, { "code": null, "e": 32535, "s": 32526, "text": "sweetyty" }, { "code": null, "e": 32544, "s": 32535, "text": "sooda367" }, { "code": null, "e": 32551, "s": 32544, "text": "Python" }, { "code": null, "e": 32567, "s": 32551, "text": "Python Programs" }, { "code": null, "e": 32665, "s": 32567, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32697, "s": 32665, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32719, "s": 32697, "text": "Enumerate() in Python" }, { "code": null, "e": 32761, "s": 32719, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32787, "s": 32761, "text": "Python String | replace()" }, { "code": null, "e": 32816, "s": 32787, "text": "*args and **kwargs in Python" }, { "code": null, "e": 32838, "s": 32816, "text": "Defaultdict in Python" }, { "code": null, "e": 32877, "s": 32838, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 32923, "s": 32877, "text": "Python | Split string into list of characters" }, { "code": null, "e": 32961, "s": 32923, "text": "Python | Convert a list to dictionary" } ]
Node.js process.abort() Method - GeeksforGeeks
10 May, 2021 The process.abort() property is an inbuilt application programming interface of the process module which is used to abort a running NodeJS process immediately. It also generates a core file. Syntax: process.abort() Parameter: This function does not accept any parameter. Return Type: It has a void return type. Below examples illustrate the use of the process.abort() property in Node.js: Example 1: index.js // Function to illustrate abort methodconst RunWithAbort = () => { console.log('Start...'); // It prints GeeksForGeeks after every 1 second setInterval((function() { return console.log('GeeksForGeeks'); }), 1000); // It calls process.abort() after 5 seconds setTimeout((function() { return process.abort(); }), 5000);}; // Function to illustrate working of above function // without abort methodconst RunWithoutAbort = () => { console.log('Start...'); // It prints GeeksForGeeks after every 1 second setInterval((function() { return console.log('GeeksForGeeks'); }), 1000);}; // Uncomment below line to call RunWithoutAbort// function it will run in infinitely// RunWithoutAbort(); // Call RunWithAbort function// it will abort after 5 secondsRunWithAbort(); Run index.js file using below command: node index.js Output: We will see the following output on the console screen. Start... GeeksForGeeks GeeksForGeeks GeeksForGeeks GeeksForGeeks Abort trap: 6 Example 2: index.js // Function to illustrate abort methodconst RunWithAbort = () => { console.log('Start...'); // It prints GeeksForGeeks after every 1 second setInterval((function() { return console.log('GeeksForGeeks : 1 second'); }), 1000); // It prints GeeksForGeeks after every 2 seconds setInterval((function() { return console.log('GeeksForGeeks : 2 second'); }), 2000); // It calls process.abort() after 5 seconds setTimeout((function() { return process.abort(); }), 5000);}; const RunWithoutAbort = () => { console.log('Start...'); // It prints GeeksForGeeks after every 1 second setInterval((function() { return console.log('GeeksForGeeks'); }), 1000);}; // Uncomment below line to call RunWithoutAbort// function it will run in infinitely// RunWithoutAbort(); // Call RunWithAbort function// it will abort after 5 secondsRunWithAbort(); Run index.js file using below command: node index.js Output: We will see the following output on the console screen. Start... GeeksForGeeks : 1 second GeeksForGeeks : 2 second GeeksForGeeks : 1 second GeeksForGeeks : 1 second GeeksForGeeks : 2 second GeeksForGeeks : 1 second Abort trap: 6 Reference: https://nodejs.org/api/process.html#process_process_abort Node.js-Methods Node.js-process-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies How to connect Node.js with React.js ? Node.js Export Module Mongoose Populate() Method Mongoose find() Function Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26267, "s": 26239, "text": "\n10 May, 2021" }, { "code": null, "e": 26458, "s": 26267, "text": "The process.abort() property is an inbuilt application programming interface of the process module which is used to abort a running NodeJS process immediately. It also generates a core file." }, { "code": null, "e": 26466, "s": 26458, "text": "Syntax:" }, { "code": null, "e": 26482, "s": 26466, "text": "process.abort()" }, { "code": null, "e": 26538, "s": 26482, "text": "Parameter: This function does not accept any parameter." }, { "code": null, "e": 26578, "s": 26538, "text": "Return Type: It has a void return type." }, { "code": null, "e": 26656, "s": 26578, "text": "Below examples illustrate the use of the process.abort() property in Node.js:" }, { "code": null, "e": 26667, "s": 26656, "text": "Example 1:" }, { "code": null, "e": 26676, "s": 26667, "text": "index.js" }, { "code": "// Function to illustrate abort methodconst RunWithAbort = () => { console.log('Start...'); // It prints GeeksForGeeks after every 1 second setInterval((function() { return console.log('GeeksForGeeks'); }), 1000); // It calls process.abort() after 5 seconds setTimeout((function() { return process.abort(); }), 5000);}; // Function to illustrate working of above function // without abort methodconst RunWithoutAbort = () => { console.log('Start...'); // It prints GeeksForGeeks after every 1 second setInterval((function() { return console.log('GeeksForGeeks'); }), 1000);}; // Uncomment below line to call RunWithoutAbort// function it will run in infinitely// RunWithoutAbort(); // Call RunWithAbort function// it will abort after 5 secondsRunWithAbort();", "e": 27498, "s": 26676, "text": null }, { "code": null, "e": 27537, "s": 27498, "text": "Run index.js file using below command:" }, { "code": null, "e": 27551, "s": 27537, "text": "node index.js" }, { "code": null, "e": 27615, "s": 27551, "text": "Output: We will see the following output on the console screen." }, { "code": null, "e": 27694, "s": 27615, "text": "Start...\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nAbort trap: 6" }, { "code": null, "e": 27705, "s": 27694, "text": "Example 2:" }, { "code": null, "e": 27714, "s": 27705, "text": "index.js" }, { "code": "// Function to illustrate abort methodconst RunWithAbort = () => { console.log('Start...'); // It prints GeeksForGeeks after every 1 second setInterval((function() { return console.log('GeeksForGeeks : 1 second'); }), 1000); // It prints GeeksForGeeks after every 2 seconds setInterval((function() { return console.log('GeeksForGeeks : 2 second'); }), 2000); // It calls process.abort() after 5 seconds setTimeout((function() { return process.abort(); }), 5000);}; const RunWithoutAbort = () => { console.log('Start...'); // It prints GeeksForGeeks after every 1 second setInterval((function() { return console.log('GeeksForGeeks'); }), 1000);}; // Uncomment below line to call RunWithoutAbort// function it will run in infinitely// RunWithoutAbort(); // Call RunWithAbort function// it will abort after 5 secondsRunWithAbort();", "e": 28624, "s": 27714, "text": null }, { "code": null, "e": 28663, "s": 28624, "text": "Run index.js file using below command:" }, { "code": null, "e": 28677, "s": 28663, "text": "node index.js" }, { "code": null, "e": 28741, "s": 28677, "text": "Output: We will see the following output on the console screen." }, { "code": null, "e": 28914, "s": 28741, "text": "Start...\nGeeksForGeeks : 1 second\nGeeksForGeeks : 2 second\nGeeksForGeeks : 1 second\nGeeksForGeeks : 1 second\nGeeksForGeeks : 2 second\nGeeksForGeeks : 1 second\nAbort trap: 6" }, { "code": null, "e": 28983, "s": 28914, "text": "Reference: https://nodejs.org/api/process.html#process_process_abort" }, { "code": null, "e": 28999, "s": 28983, "text": "Node.js-Methods" }, { "code": null, "e": 29022, "s": 28999, "text": "Node.js-process-module" }, { "code": null, "e": 29029, "s": 29022, "text": "Picked" }, { "code": null, "e": 29037, "s": 29029, "text": "Node.js" }, { "code": null, "e": 29054, "s": 29037, "text": "Web Technologies" }, { "code": null, "e": 29152, "s": 29054, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29222, "s": 29152, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 29261, "s": 29222, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 29283, "s": 29261, "text": "Node.js Export Module" }, { "code": null, "e": 29310, "s": 29283, "text": "Mongoose Populate() Method" }, { "code": null, "e": 29335, "s": 29310, "text": "Mongoose find() Function" }, { "code": null, "e": 29375, "s": 29335, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29420, "s": 29375, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29463, "s": 29420, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29513, "s": 29463, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
What is a use of DSNTIAR? How will you implement it in a COBOLDB2 program?
We use fields of SQLCA to enquire about the status of the most recently executed SQL query. The SQLCODE is one such field which can take the various values and each value indicates specific error code. For example, -180 error code represents incorrect timestamp format. However, in the logs we only get the error code and every time we have to refer to the IBM documentation to check the description of the error code. To overcome this problem, we use DSNTIAR. The DSNTIAR is an inbuilt utility which is provided by IBM to be used in a COBOL-DB2 program.This utility displays the error code and its description in the logs in a well formatted manner, which saves time. The DSNTIAR utility can be called using SQLCA as below. CALL ‘DSNTIAR’ USING SQLCA, ERROR-MESSAGE The DSNTIAR utility populates the error description in the ERROR-MESSAGE variable.
[ { "code": null, "e": 1481, "s": 1062, "text": "We use fields of SQLCA to enquire about the status of the most recently executed SQL query. The SQLCODE is one such field which can take the various values and each value indicates specific error code. For example, -180 error code represents incorrect timestamp format. However, in the logs we only get the error code and every time we have to refer to the IBM documentation to check the description of the error code." }, { "code": null, "e": 1787, "s": 1481, "text": "To overcome this problem, we use DSNTIAR. The DSNTIAR is an inbuilt utility which is provided by IBM to be used in a COBOL-DB2 program.This utility displays the error code\nand its description in the logs in a well formatted manner, which saves time. The DSNTIAR utility can be called using SQLCA as below." }, { "code": null, "e": 1829, "s": 1787, "text": "CALL ‘DSNTIAR’ USING SQLCA,\nERROR-MESSAGE" }, { "code": null, "e": 1912, "s": 1829, "text": "The DSNTIAR utility populates the error description in the ERROR-MESSAGE variable." } ]
Can a Machine Learning Model Read Stock Charts and Predict Prices? | by Viraf | Towards Data Science
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. Most of the ML models out there are trying to predict stock prices (or the changes in stock prices) using historical price data and other technical indicators — i.e., NUMERIC INPUTS. But, I asked myself, why can’t an ML model replicate precisely how a human trades in the stock markets? Any average person would open up the stock price charts (candlestick charts), and try to find some patterns in the price data. Maybe next, apply some technical indicators, peek a look at the company fundamentals, and finally make a decision on the next movement of the stock price as a combined output of all the charted and numeric inputs. What if an ML model could also make these conclusions from visual information? So let’s pass the price history time series as visual information to a CNN model as input. Will the model recognize the patterns in the visual data like a human does? Will this model perform better than a model that takes numeric data as input? Well, let’s find out! Before we start, in my last article, we explore why using LSTMs blindly to predict stock prices is going to land you in trouble. You can read that here. Already read that? Good, now we can proceed. And next, a disclaimer. None of this is financial advice, nor should you implement it directly in practice. Consider this as an experiment and nothing more. Cool, now this aside, we can get on with our experimenting! Instead of predicting stock prices, we shall predict the direction of price movement for the next day, i.e., whether the stock price will go up or down or sideways. Let’s get started! The flow of this article is as follows: Get historical stock data in python. Convert the price data to a visual representation Build and train a model with Tensorflow Keras. Predict and interpret the results. There are multiple options to get access to historical stock prices in python, but one of the most straightforward libraries is yfinance. Quite convenient and free, it gets the job done by scraping data from yahoo finance. !pip install yfinance## Import the required librariesimport yfinance as yfimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom pandas.plotting import register_matplotlib_convertersregister_matplotlib_converters() For this article, I will take up the stock prices of ‘Reliance,’ the largest corporation in the Indian stock markets, but feel free to try this out for any other instrument as well. The following piece of code downloads stock price data for Reliance a period of around 18 years (I am intentionally avoiding the COVID period) with a resolution of 1 day and stores it in a pandas dataframe. You can vary these parameters as you deem fit for your experiments. Printing out the head of the pandas dataframe, you can see the various parameters like ‘Open’, ‘Close’, ‘High’, ‘Low’, ‘Volume’ available for the stock data. Plotting out the ‘Close’ price to visualize the data, see how nicely the stock has risen in the last few years. Now we shall add some additional features to our data. First, calculate the percentage change from the previous day close. Next based this change, generate a signal which is: 0 (if the change is lesser than -2.5%) 1 (if the change is between -2.5% and -1%) 2 (if the change is between -1% and 1%) 3 (if the change is between 1% and 2.5%) 4 (if the change is greater than 2.5%) The dataframe now looks like: Now, this is completely arbitrary, you can vary it as you please. You can break the change into an even more/lesser number of parts (adjust the last layer of the model accordingly). Now, this step is very important, since it will decide what the model sees. For this article, I want to keep the images as close as possible to the candlestick charts a human trader sees. A constraint is that every input image has to be of the same dimensions and must contain sufficient information for the model to make conclusions from. We shall have a lookback period, for example, the past 50 days (10 trading weeks), which shall be represented. For simplicity, for each of these 50 days, the open and close, and the direction of the price movement will be encoded. Since images of the same dimension will be fed to the neural network, it might not understand where this image stands in the entirety of the 15 years. For example, in 2002, the prices are at ~80–90 whereas they slowly rise with time to ~1800. Although price patterns may (or may not) be independent of the absolute stock prices, I wanted to encode some of this information as well in the images. So, to give the image some context to the past prices and their absolute price levels, the 50-day price representations will be scaled in a bigger time window which considers additional previous price values. The code for generating this visual representation is: Note: This is a visual representation very close to what we see on the candlestick charts (that was the whole point). However, you can use your imagination (and some discretion) to create a completely different visual representation with other encoded parameters as well. Because the way a CNN model sees and learns from an image might (or might not) be very different from how we do! Next, let’s create a data generator that will iterate through the 15 years of data and create pairs of images and the corresponding next-day-predictions. This data generates image-prediction batches like Since we have inputs as images and require outputs as one of three classes (up, down, no movement), our model will have a few convolutional layers, followed by a few dense layers and finally a softmax function. Let’s initiate the generator objects and start the training. Post-training, the losses can be plotted as: plt.plot(history.history['loss'], label='train')plt.plot(history.history['val_loss'], label='val')plt.legend()plt.show() Let’s now see the accuracy on the test data. ## Evaluating the performance of the modelprint(model.evaluate(test_gen,steps = (len(data)-split_test)//batch_size))>>> loss: 1.3830 - accuracy: 0.4375 Well, given 5 possible outcomes, the accuracy of randomly guessing one would be 0.2. So this model seems to have performed quite well comparatively. Or has it? Plotting out the predicted outputs, it’s clear what has happened. The model has not learned anything useful yet, so it ends up predicting “2” as every output resulting in relatively high accuracy. Let’s train the model some more then. But now, the validation loss increases greatly. Plus, testing gives an accuracy of less than 0.3. Not very encouraging, the model has probably overfitted on the training data. A very clear reason for this is the small size of training data compared to the model size. Although the performance was not extremely encouraging, this was quite an innovative approach of looking at the age-old problem of predicting stock prices. A few more ideas on these lines are giving multi-timeframe inputs (say, weekly data as inputs as well), or additionally providing technical indicators as numeric data (in parallel with visual charts), or transform the price data into other visual domains (doesn’t have to be the charts as we see them), etc. What else do you think we can do to improve this model? Do you have any other interesting ideas? After trying out all these ideas, the question remains — is feeding visual data providing any edge that numeric data cannot? What do you think? You can find the entire code in my GitHub repository. Finally, I am not saying I am an expert in these fields — I am just putting forward my explorations on this topic, so feel free to point out my errors or add anything I missed. I would love to hear your feedback. Do you want to be rich overnight using ML in stocks? This article is (NOT) for you! towardsdatascience.com Or check out some of my other machine learning articles. I’m sure you’ll find them useful...
[ { "code": null, "e": 471, "s": 171, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 758, "s": 471, "text": "Most of the ML models out there are trying to predict stock prices (or the changes in stock prices) using historical price data and other technical indicators — i.e., NUMERIC INPUTS. But, I asked myself, why can’t an ML model replicate precisely how a human trades in the stock markets?" }, { "code": null, "e": 1178, "s": 758, "text": "Any average person would open up the stock price charts (candlestick charts), and try to find some patterns in the price data. Maybe next, apply some technical indicators, peek a look at the company fundamentals, and finally make a decision on the next movement of the stock price as a combined output of all the charted and numeric inputs. What if an ML model could also make these conclusions from visual information?" }, { "code": null, "e": 1445, "s": 1178, "text": "So let’s pass the price history time series as visual information to a CNN model as input. Will the model recognize the patterns in the visual data like a human does? Will this model perform better than a model that takes numeric data as input? Well, let’s find out!" }, { "code": null, "e": 1643, "s": 1445, "text": "Before we start, in my last article, we explore why using LSTMs blindly to predict stock prices is going to land you in trouble. You can read that here. Already read that? Good, now we can proceed." }, { "code": null, "e": 1860, "s": 1643, "text": "And next, a disclaimer. None of this is financial advice, nor should you implement it directly in practice. Consider this as an experiment and nothing more. Cool, now this aside, we can get on with our experimenting!" }, { "code": null, "e": 2044, "s": 1860, "text": "Instead of predicting stock prices, we shall predict the direction of price movement for the next day, i.e., whether the stock price will go up or down or sideways. Let’s get started!" }, { "code": null, "e": 2084, "s": 2044, "text": "The flow of this article is as follows:" }, { "code": null, "e": 2121, "s": 2084, "text": "Get historical stock data in python." }, { "code": null, "e": 2171, "s": 2121, "text": "Convert the price data to a visual representation" }, { "code": null, "e": 2218, "s": 2171, "text": "Build and train a model with Tensorflow Keras." }, { "code": null, "e": 2253, "s": 2218, "text": "Predict and interpret the results." }, { "code": null, "e": 2476, "s": 2253, "text": "There are multiple options to get access to historical stock prices in python, but one of the most straightforward libraries is yfinance. Quite convenient and free, it gets the job done by scraping data from yahoo finance." }, { "code": null, "e": 2709, "s": 2476, "text": "!pip install yfinance## Import the required librariesimport yfinance as yfimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom pandas.plotting import register_matplotlib_convertersregister_matplotlib_converters()" }, { "code": null, "e": 2891, "s": 2709, "text": "For this article, I will take up the stock prices of ‘Reliance,’ the largest corporation in the Indian stock markets, but feel free to try this out for any other instrument as well." }, { "code": null, "e": 3166, "s": 2891, "text": "The following piece of code downloads stock price data for Reliance a period of around 18 years (I am intentionally avoiding the COVID period) with a resolution of 1 day and stores it in a pandas dataframe. You can vary these parameters as you deem fit for your experiments." }, { "code": null, "e": 3324, "s": 3166, "text": "Printing out the head of the pandas dataframe, you can see the various parameters like ‘Open’, ‘Close’, ‘High’, ‘Low’, ‘Volume’ available for the stock data." }, { "code": null, "e": 3436, "s": 3324, "text": "Plotting out the ‘Close’ price to visualize the data, see how nicely the stock has risen in the last few years." }, { "code": null, "e": 3611, "s": 3436, "text": "Now we shall add some additional features to our data. First, calculate the percentage change from the previous day close. Next based this change, generate a signal which is:" }, { "code": null, "e": 3650, "s": 3611, "text": "0 (if the change is lesser than -2.5%)" }, { "code": null, "e": 3693, "s": 3650, "text": "1 (if the change is between -2.5% and -1%)" }, { "code": null, "e": 3733, "s": 3693, "text": "2 (if the change is between -1% and 1%)" }, { "code": null, "e": 3774, "s": 3733, "text": "3 (if the change is between 1% and 2.5%)" }, { "code": null, "e": 3813, "s": 3774, "text": "4 (if the change is greater than 2.5%)" }, { "code": null, "e": 3843, "s": 3813, "text": "The dataframe now looks like:" }, { "code": null, "e": 4025, "s": 3843, "text": "Now, this is completely arbitrary, you can vary it as you please. You can break the change into an even more/lesser number of parts (adjust the last layer of the model accordingly)." }, { "code": null, "e": 4365, "s": 4025, "text": "Now, this step is very important, since it will decide what the model sees. For this article, I want to keep the images as close as possible to the candlestick charts a human trader sees. A constraint is that every input image has to be of the same dimensions and must contain sufficient information for the model to make conclusions from." }, { "code": null, "e": 4596, "s": 4365, "text": "We shall have a lookback period, for example, the past 50 days (10 trading weeks), which shall be represented. For simplicity, for each of these 50 days, the open and close, and the direction of the price movement will be encoded." }, { "code": null, "e": 5201, "s": 4596, "text": "Since images of the same dimension will be fed to the neural network, it might not understand where this image stands in the entirety of the 15 years. For example, in 2002, the prices are at ~80–90 whereas they slowly rise with time to ~1800. Although price patterns may (or may not) be independent of the absolute stock prices, I wanted to encode some of this information as well in the images. So, to give the image some context to the past prices and their absolute price levels, the 50-day price representations will be scaled in a bigger time window which considers additional previous price values." }, { "code": null, "e": 5256, "s": 5201, "text": "The code for generating this visual representation is:" }, { "code": null, "e": 5641, "s": 5256, "text": "Note: This is a visual representation very close to what we see on the candlestick charts (that was the whole point). However, you can use your imagination (and some discretion) to create a completely different visual representation with other encoded parameters as well. Because the way a CNN model sees and learns from an image might (or might not) be very different from how we do!" }, { "code": null, "e": 5795, "s": 5641, "text": "Next, let’s create a data generator that will iterate through the 15 years of data and create pairs of images and the corresponding next-day-predictions." }, { "code": null, "e": 5845, "s": 5795, "text": "This data generates image-prediction batches like" }, { "code": null, "e": 6056, "s": 5845, "text": "Since we have inputs as images and require outputs as one of three classes (up, down, no movement), our model will have a few convolutional layers, followed by a few dense layers and finally a softmax function." }, { "code": null, "e": 6117, "s": 6056, "text": "Let’s initiate the generator objects and start the training." }, { "code": null, "e": 6162, "s": 6117, "text": "Post-training, the losses can be plotted as:" }, { "code": null, "e": 6283, "s": 6162, "text": "plt.plot(history.history['loss'], label='train')plt.plot(history.history['val_loss'], label='val')plt.legend()plt.show()" }, { "code": null, "e": 6328, "s": 6283, "text": "Let’s now see the accuracy on the test data." }, { "code": null, "e": 6480, "s": 6328, "text": "## Evaluating the performance of the modelprint(model.evaluate(test_gen,steps = (len(data)-split_test)//batch_size))>>> loss: 1.3830 - accuracy: 0.4375" }, { "code": null, "e": 6640, "s": 6480, "text": "Well, given 5 possible outcomes, the accuracy of randomly guessing one would be 0.2. So this model seems to have performed quite well comparatively. Or has it?" }, { "code": null, "e": 6837, "s": 6640, "text": "Plotting out the predicted outputs, it’s clear what has happened. The model has not learned anything useful yet, so it ends up predicting “2” as every output resulting in relatively high accuracy." }, { "code": null, "e": 7143, "s": 6837, "text": "Let’s train the model some more then. But now, the validation loss increases greatly. Plus, testing gives an accuracy of less than 0.3. Not very encouraging, the model has probably overfitted on the training data. A very clear reason for this is the small size of training data compared to the model size." }, { "code": null, "e": 7704, "s": 7143, "text": "Although the performance was not extremely encouraging, this was quite an innovative approach of looking at the age-old problem of predicting stock prices. A few more ideas on these lines are giving multi-timeframe inputs (say, weekly data as inputs as well), or additionally providing technical indicators as numeric data (in parallel with visual charts), or transform the price data into other visual domains (doesn’t have to be the charts as we see them), etc. What else do you think we can do to improve this model? Do you have any other interesting ideas?" }, { "code": null, "e": 7848, "s": 7704, "text": "After trying out all these ideas, the question remains — is feeding visual data providing any edge that numeric data cannot? What do you think?" }, { "code": null, "e": 7902, "s": 7848, "text": "You can find the entire code in my GitHub repository." }, { "code": null, "e": 8115, "s": 7902, "text": "Finally, I am not saying I am an expert in these fields — I am just putting forward my explorations on this topic, so feel free to point out my errors or add anything I missed. I would love to hear your feedback." }, { "code": null, "e": 8199, "s": 8115, "text": "Do you want to be rich overnight using ML in stocks? This article is (NOT) for you!" }, { "code": null, "e": 8222, "s": 8199, "text": "towardsdatascience.com" } ]
Bits manipulation (Important tactics) - GeeksforGeeks
07 Feb, 2022 Prerequisites : Bitwise operators in C, Bitwise Hacks for Competitive Programming, Bit Tricks for Competitive Programming Compute XOR from 1 to n (direct method) : Compute XOR from 1 to n (direct method) : CPP Javascript // Direct XOR of all numbers from 1 to nint computeXOR(int n){ if (n % 4 == 0) return n; if (n % 4 == 1) return 1; if (n % 4 == 2) return n + 1; else return 0;} <script> // Direct XOR of all numbers from 1 to nfunction computeXOR(n){ if (n % 4 == 0) return n; if (n % 4 == 1) return 1; if (n % 4 == 2) return n + 1; else return 0;} // This code is contributed by Shubham Singh </script> Input: 6 Output: 7 Refer Compute XOR from 1 to n for details.We can quickly calculate the total number of combinations with numbers smaller than or equal to a number whose sum and XOR are equal. Instead of using looping (Brute force method), we can directly find it by a mathematical trick i.e. Refer Compute XOR from 1 to n for details. We can quickly calculate the total number of combinations with numbers smaller than or equal to a number whose sum and XOR are equal. Instead of using looping (Brute force method), we can directly find it by a mathematical trick i.e. // Refer Equal Sum and XOR for details. Answer = pow(2, count of zero bits) How to know if a number is a power of 2? How to know if a number is a power of 2? CPP // Function to check if x is power of 2bool isPowerOfTwo(int x){ // First x in the below expression is // for the case when x is 0 return x && (!(x & (x - 1)));} Refer check if a number is power of two for details.Find XOR of all subsets of a set. We can do it in O(1) time. The answer is always 0 if the given set has more than one element. For sets with a single element, the answer is the value of single element. Refer XOR of the XOR’s of all subsets for details.We can quickly find number of leading, trailing zeroes and number of 1’s in a binary code of an integer in C++ using GCC. It can be done by using inbuilt function i.e. Refer check if a number is power of two for details. Find XOR of all subsets of a set. We can do it in O(1) time. The answer is always 0 if the given set has more than one element. For sets with a single element, the answer is the value of single element. Refer XOR of the XOR’s of all subsets for details. We can quickly find number of leading, trailing zeroes and number of 1’s in a binary code of an integer in C++ using GCC. It can be done by using inbuilt function i.e. Number of leading zeroes: builtin_clz(x) Number of trailing zeroes : builtin_ctz(x) Number of 1-bits: __builtin_popcount(x) Refer GCC inbuilt functions for details.Convert binary code directly into an integer in C++. Refer GCC inbuilt functions for details. Convert binary code directly into an integer in C++. CPP // Conversion into Binary code//#include <iostream>using namespace std; int main(){ auto number = 0b011; cout << number; return 0;} Output: 3 The Quickest way to swap two numbers: The Quickest way to swap two numbers: a ^= b; b ^= a; a ^= b; Refer swap two numbers for details. Simple approach to flip the bits of a number: It can be done in a simple way, just simply subtract the number from the value obtained when all the bits are equal to 1. For example: Refer swap two numbers for details. Simple approach to flip the bits of a number: It can be done in a simple way, just simply subtract the number from the value obtained when all the bits are equal to 1. For example: Number : Given Number Value : A number with all bits set in given number. Flipped number = Value – Number. Example : Number = 23, Binary form: 10111; After flipping digits number will be: 01000; Value: 11111 = 31; We can find the most significant set bit in O(1) time for a fixed size integer. For example below code is for 32-bit integer. We can find the most significant set bit in O(1) time for a fixed size integer. For example below code is for 32-bit integer. C int setBitNumber(int n){ // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n>>1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n>>2; n |= n>>4; n |= n>>8; n |= n>>16; // Increment n by 1 so that // there is only one set bit // which is just before original // MSB. n now becomes 1000000000 n = n + 1; // Return original MSB after shifting. // n now becomes 100000000 return (n >> 1);} Refer Find most significant set bit of a number for details. We can quickly check if bits in a number are in alternate pattern (like 101010). We compute n ^ (n >> 1). If n has an alternate pattern, then n ^ (n >> 1) operation will produce a number having set bits only. ‘^’ is a bitwise XOR operation. Refer check if a number has bits in alternate pattern for details. Refer Find most significant set bit of a number for details. We can quickly check if bits in a number are in alternate pattern (like 101010). We compute n ^ (n >> 1). If n has an alternate pattern, then n ^ (n >> 1) operation will produce a number having set bits only. ‘^’ is a bitwise XOR operation. Refer check if a number has bits in alternate pattern for details. This article is contributed by Sanchit Garg 1. 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. kkvanonymous SHUBHAMSINGH10 Bit Magic Competitive Programming Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bit Fields in C Set, Clear and Toggle a given bit of a number in C 1's and 2's complement of a Binary Number Divide two integers without using multiplication, division and mod operator Check whether K-th bit is set or not Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Top 10 Algorithms and Data Structures for Competitive Programming Modulo 10^9+7 (1000000007)
[ { "code": null, "e": 24710, "s": 24682, "text": "\n07 Feb, 2022" }, { "code": null, "e": 24833, "s": 24710, "text": "Prerequisites : Bitwise operators in C, Bitwise Hacks for Competitive Programming, Bit Tricks for Competitive Programming " }, { "code": null, "e": 24877, "s": 24833, "text": "Compute XOR from 1 to n (direct method) : " }, { "code": null, "e": 24921, "s": 24877, "text": "Compute XOR from 1 to n (direct method) : " }, { "code": null, "e": 24925, "s": 24921, "text": "CPP" }, { "code": null, "e": 24936, "s": 24925, "text": "Javascript" }, { "code": "// Direct XOR of all numbers from 1 to nint computeXOR(int n){ if (n % 4 == 0) return n; if (n % 4 == 1) return 1; if (n % 4 == 2) return n + 1; else return 0;}", "e": 25137, "s": 24936, "text": null }, { "code": "<script> // Direct XOR of all numbers from 1 to nfunction computeXOR(n){ if (n % 4 == 0) return n; if (n % 4 == 1) return 1; if (n % 4 == 2) return n + 1; else return 0;} // This code is contributed by Shubham Singh </script>", "e": 25403, "s": 25137, "text": null }, { "code": null, "e": 25426, "s": 25407, "text": "Input: 6\nOutput: 7" }, { "code": null, "e": 25704, "s": 25426, "text": "Refer Compute XOR from 1 to n for details.We can quickly calculate the total number of combinations with numbers smaller than or equal to a number whose sum and XOR are equal. Instead of using looping (Brute force method), we can directly find it by a mathematical trick i.e. " }, { "code": null, "e": 25747, "s": 25704, "text": "Refer Compute XOR from 1 to n for details." }, { "code": null, "e": 25983, "s": 25747, "text": "We can quickly calculate the total number of combinations with numbers smaller than or equal to a number whose sum and XOR are equal. Instead of using looping (Brute force method), we can directly find it by a mathematical trick i.e. " }, { "code": null, "e": 26059, "s": 25983, "text": "// Refer Equal Sum and XOR for details.\nAnswer = pow(2, count of zero bits)" }, { "code": null, "e": 26102, "s": 26059, "text": "How to know if a number is a power of 2? " }, { "code": null, "e": 26145, "s": 26102, "text": "How to know if a number is a power of 2? " }, { "code": null, "e": 26149, "s": 26145, "text": "CPP" }, { "code": "// Function to check if x is power of 2bool isPowerOfTwo(int x){ // First x in the below expression is // for the case when x is 0 return x && (!(x & (x - 1)));}", "e": 26325, "s": 26149, "text": null }, { "code": null, "e": 26798, "s": 26325, "text": "Refer check if a number is power of two for details.Find XOR of all subsets of a set. We can do it in O(1) time. The answer is always 0 if the given set has more than one element. For sets with a single element, the answer is the value of single element. Refer XOR of the XOR’s of all subsets for details.We can quickly find number of leading, trailing zeroes and number of 1’s in a binary code of an integer in C++ using GCC. It can be done by using inbuilt function i.e." }, { "code": null, "e": 26851, "s": 26798, "text": "Refer check if a number is power of two for details." }, { "code": null, "e": 27105, "s": 26851, "text": "Find XOR of all subsets of a set. We can do it in O(1) time. The answer is always 0 if the given set has more than one element. For sets with a single element, the answer is the value of single element. Refer XOR of the XOR’s of all subsets for details." }, { "code": null, "e": 27273, "s": 27105, "text": "We can quickly find number of leading, trailing zeroes and number of 1’s in a binary code of an integer in C++ using GCC. It can be done by using inbuilt function i.e." }, { "code": null, "e": 27404, "s": 27273, "text": " Number of leading zeroes: builtin_clz(x)\n Number of trailing zeroes : builtin_ctz(x)\n Number of 1-bits: __builtin_popcount(x) " }, { "code": null, "e": 27499, "s": 27404, "text": "Refer GCC inbuilt functions for details.Convert binary code directly into an integer in C++. " }, { "code": null, "e": 27540, "s": 27499, "text": "Refer GCC inbuilt functions for details." }, { "code": null, "e": 27595, "s": 27540, "text": "Convert binary code directly into an integer in C++. " }, { "code": null, "e": 27599, "s": 27595, "text": "CPP" }, { "code": "// Conversion into Binary code//#include <iostream>using namespace std; int main(){ auto number = 0b011; cout << number; return 0;}", "e": 27740, "s": 27599, "text": null }, { "code": null, "e": 27754, "s": 27744, "text": "Output: 3" }, { "code": null, "e": 27794, "s": 27754, "text": "The Quickest way to swap two numbers: " }, { "code": null, "e": 27834, "s": 27794, "text": "The Quickest way to swap two numbers: " }, { "code": null, "e": 27859, "s": 27834, "text": "a ^= b;\nb ^= a; \na ^= b;" }, { "code": null, "e": 28079, "s": 27859, "text": "Refer swap two numbers for details. Simple approach to flip the bits of a number: It can be done in a simple way, just simply subtract the number from the value obtained when all the bits are equal to 1. For example: " }, { "code": null, "e": 28117, "s": 28079, "text": "Refer swap two numbers for details. " }, { "code": null, "e": 28300, "s": 28117, "text": "Simple approach to flip the bits of a number: It can be done in a simple way, just simply subtract the number from the value obtained when all the bits are equal to 1. For example: " }, { "code": null, "e": 28517, "s": 28300, "text": "Number : Given Number\nValue : A number with all bits set in given number.\nFlipped number = Value – Number.\n\nExample : \nNumber = 23,\nBinary form: 10111;\nAfter flipping digits number will be: 01000;\nValue: 11111 = 31;" }, { "code": null, "e": 28645, "s": 28517, "text": "We can find the most significant set bit in O(1) time for a fixed size integer. For example below code is for 32-bit integer. " }, { "code": null, "e": 28773, "s": 28645, "text": "We can find the most significant set bit in O(1) time for a fixed size integer. For example below code is for 32-bit integer. " }, { "code": null, "e": 28775, "s": 28773, "text": "C" }, { "code": "int setBitNumber(int n){ // Below steps set bits after // MSB (including MSB) // Suppose n is 273 (binary // is 100010001). It does following // 100010001 | 010001000 = 110011001 n |= n>>1; // This makes sure 4 bits // (From MSB and including MSB) // are set. It does following // 110011001 | 001100110 = 111111111 n |= n>>2; n |= n>>4; n |= n>>8; n |= n>>16; // Increment n by 1 so that // there is only one set bit // which is just before original // MSB. n now becomes 1000000000 n = n + 1; // Return original MSB after shifting. // n now becomes 100000000 return (n >> 1);}", "e": 29436, "s": 28775, "text": null }, { "code": null, "e": 29806, "s": 29436, "text": "Refer Find most significant set bit of a number for details. We can quickly check if bits in a number are in alternate pattern (like 101010). We compute n ^ (n >> 1). If n has an alternate pattern, then n ^ (n >> 1) operation will produce a number having set bits only. ‘^’ is a bitwise XOR operation. Refer check if a number has bits in alternate pattern for details." }, { "code": null, "e": 29869, "s": 29806, "text": "Refer Find most significant set bit of a number for details. " }, { "code": null, "e": 30177, "s": 29869, "text": "We can quickly check if bits in a number are in alternate pattern (like 101010). We compute n ^ (n >> 1). If n has an alternate pattern, then n ^ (n >> 1) operation will produce a number having set bits only. ‘^’ is a bitwise XOR operation. Refer check if a number has bits in alternate pattern for details." }, { "code": null, "e": 30600, "s": 30177, "text": "This article is contributed by Sanchit Garg 1. 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": 30613, "s": 30600, "text": "kkvanonymous" }, { "code": null, "e": 30628, "s": 30613, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 30638, "s": 30628, "text": "Bit Magic" }, { "code": null, "e": 30662, "s": 30638, "text": "Competitive Programming" }, { "code": null, "e": 30672, "s": 30662, "text": "Bit Magic" }, { "code": null, "e": 30770, "s": 30672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30786, "s": 30770, "text": "Bit Fields in C" }, { "code": null, "e": 30837, "s": 30786, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 30879, "s": 30837, "text": "1's and 2's complement of a Binary Number" }, { "code": null, "e": 30955, "s": 30879, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 30992, "s": 30955, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 31035, "s": 30992, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 31078, "s": 31035, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 31119, "s": 31078, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31185, "s": 31119, "text": "Top 10 Algorithms and Data Structures for Competitive Programming" } ]
Check if given string can be made Palindrome by removing only single type of character | Set-2 - GeeksforGeeks
06 Jan, 2022 Given a string S, the task is to whether a string can be made palindrome after removing the occurrences of the same character, any number of times Examples: Input: S = “abczdzacb“Output: YesExplanation: Remove first and second occurrence of character ‘a’. String S becomes “bczdzcb”, which is a palindrome. Input: S = “madem”Output: NoExplanation: Since only we can remove 1 character of any frequency only once. There is no such character removing which a palindrome can be made. Approach: This problem can be solved by using the property of palindrome. It is obvious that removing the occurrences of the same character from the entire does not affect the palindromic nature. So the entire occurrences of that character can also be removed. So check the string from both the ends if they are not the same then check the string after the removal of entire occurrences of the character at both the ends. If any of the removals satisfies the palindromic condition then the answer is Yes else No. Follow the steps below to solve the problem: Iterate using a loop in the range of (0, N/2) Now check if characters from both the ends are equal or notIf the characters are not the sameCheck if it is Palindrome after removing the entire occurrence of character from both ends.If removing entire occurrences of a character from any end is a palindrome print “YES” and stop iteration. If the characters are not the sameCheck if it is Palindrome after removing the entire occurrence of character from both ends.If removing entire occurrences of a character from any end is a palindrome print “YES” and stop iteration. Check if it is Palindrome after removing the entire occurrence of character from both ends. If removing entire occurrences of a character from any end is a palindrome print “YES” and stop iteration. If after the whole traversal, no such palindrome found print “NO”. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether the string// is palindrome after removal or// neglecting character cbool check_palindrome(string str, char c){ int n = str.length(), i = 0, j = n - 1; while (i < j) { // If it is same as c neglect // this and move front if (str[i] == c) i++; // If it is same as c neglect // this and move back else if (str[j] == c) j--; // If they are not same it is // not a palindrome so return 0 else if (str[i] != str[j]) return 0; // It can be a palindrome so move // and check for remaining string else i++, j--; } return 1;} // Function to check if it is possible to// form a palindrome after removal of// any number of same characters oncestring make_palindrome(string str){ bool is_palindrome = 1; int n = str.length(); // If n==1 || n==2 it is always possible if (n == 1 || n == 2) { return "YES"; } // Check the character from both the ends // of the string for (int i = 0; i < n / 2; ++i) { // If the characters are not equal if (str[i] != str[n - 1 - i]) { // Remove str[i] and check if // it is a palindrome or // Remove str[n-i-1] and check // if it is a palindrome is_palindrome = check_palindrome(str, str[i]) || check_palindrome( str, str[n - 1 - i]); break; } } if (is_palindrome) return "Yes"; else return "No";} // Driver Codeint main(){ string S = "madem"; string res = make_palindrome(S); cout << (res); return 0;} // Java program for the above approachimport java.util.*;public class GFG{ // Function to check whether the string// is palindrome after removal or// neglecting character cstatic boolean check_palindrome(String str, char c){ int n = str.length(), i = 0, j = n - 1; while (i < j) { // If it is same as c neglect // this and move front if (str.charAt(i) == c) i++; // If it is same as c neglect // this and move back else if (str.charAt(j) == c) j--; // If they are not same it is // not a palindrome so return 0 else if (str.charAt(i) != str.charAt(j)) return false; // It can be a palindrome so move // and check for remaining string else { i++; j--; } } return true;} // Function to check if it is possible to// form a palindrome after removal of// any number of same characters oncestatic String make_palindrome(String str){ boolean is_palindrome = true; int n = str.length(); // If n==1 || n==2 it is always possible if (n == 1 || n == 2) { return "YES"; } // Check the character from both the ends // of the string for (int i = 0; i < n / 2; ++i) { // If the characters are not equal if (str.charAt(i) != str.charAt(n - 1 - i)) { // Remove str[i] and check if // it is a palindrome or // Remove str[n-i-1] and check // if it is a palindrome is_palindrome = check_palindrome(str, str.charAt(i)) || check_palindrome( str, str.charAt(n - 1 - i)); break; } } if (is_palindrome) return "Yes"; else return "No";} // Driver Codepublic static void main(String args[]){ String S = "madem"; String res = make_palindrome(S); System.out.println(res);}} // This code is contributed by Samim Hossain Mondal. # Python code for the above approach # Function to check whether the string# is palindrome after removal or# neglecting character cdef check_palindrome (str, c): n = len(str) i = 0 j = n - 1 while (i < j): # If it is same as c neglect # this and move front if (str[i] == c): i += 1 # If it is same as c neglect # this and move back elif (str[j] == c): j -= 1 # If they are not same it is # not a palindrome so return 0 elif (str[i] != str[j]): return 0 # It can be a palindrome so move # and check for remaining string else: i += 1 j -= 1 return 1 # Function to check if it is possible to# form a palindrome after removal of# any number of same characters oncedef make_palindrome (str): is_palindrome = 1 n = len(str) # If n==1 || n==2 it is always possible if (n == 1 or n == 2): return "YES" # Check the character from both the ends # of the string for i in range(n // 2): # If the characters are not equal if (str[i] != str[n - 1 - i]): # Remove str[i] and check if # it is a palindrome or # Remove str[n-i-1] and check # if it is a palindrome is_palindrome = check_palindrome(str, str[i]) or check_palindrome(str, str[n - 1 - i]) break if (is_palindrome): return "Yes" else: return "No" # Driver CodeS = "madem"res = make_palindrome(S)print(res) # This code is contributed by gfgking // C# program for the above approachusing System;class GFG{ // Function to check whether the string// is palindrome after removal or// neglecting character cstatic bool check_palindrome(string str, char c){ int n = str.Length, i = 0, j = n - 1; while (i < j) { // If it is same as c neglect // this and move front if (str[i] == c) i++; // If it is same as c neglect // this and move back else if (str[j] == c) j--; // If they are not same it is // not a palindrome so return 0 else if (str[i] != str[j]) return false; // It can be a palindrome so move // and check for remaining string else { i++; j--; } } return true;} // Function to check if it is possible to// form a palindrome after removal of// any number of same characters oncestatic string make_palindrome(string str){ bool is_palindrome = true; int n = str.Length; // If n==1 || n==2 it is always possible if (n == 1 || n == 2) { return "YES"; } // Check the character from both the ends // of the string for (int i = 0; i < n / 2; ++i) { // If the characters are not equal if (str[i] != str[n - 1 - i]) { // Remove str[i] and check if // it is a palindrome or // Remove str[n-i-1] and check // if it is a palindrome is_palindrome = check_palindrome(str, str[i]) || check_palindrome( str, str[n - 1 - i]); break; } } if (is_palindrome) return "Yes"; else return "No";} // Driver Codepublic static void Main(){ string S = "madem"; string res = make_palindrome(S); Console.Write(res);}} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Function to check whether the string // is palindrome after removal or // neglecting character c const check_palindrome = (str, c) => { let n = str.length, i = 0, j = n - 1; while (i < j) { // If it is same as c neglect // this and move front if (str[i] == c) i++; // If it is same as c neglect // this and move back else if (str[j] == c) j--; // If they are not same it is // not a palindrome so return 0 else if (str[i] != str[j]) return 0; // It can be a palindrome so move // and check for remaining string else i++, j--; } return 1; } // Function to check if it is possible to // form a palindrome after removal of // any number of same characters once const make_palindrome = (str) => { let is_palindrome = 1; let n = str.length; // If n==1 || n==2 it is always possible if (n == 1 || n == 2) { return "YES"; } // Check the character from both the ends // of the string for (let i = 0; i < parseInt(n / 2); ++i) { // If the characters are not equal if (str[i] != str[n - 1 - i]) { // Remove str[i] and check if // it is a palindrome or // Remove str[n-i-1] and check // if it is a palindrome is_palindrome = check_palindrome(str, str[i]) || check_palindrome( str, str[n - 1 - i]); break; } } if (is_palindrome) return "Yes"; else return "No"; } // Driver Code let S = "madem"; let res = make_palindrome(S); document.write(res); // This code is contributed by rakeshsahni </script> No Time Complexity: O(N), Where N is the length of the string.Space Complexity: O(1) rakeshsahni gfgking samim2000 Algo-Geek 2021 Algo Geek Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of operation required to water all the plants Sort strings on the basis of their numeric part Encode given String by inserting in Matrix column-wise and printing it row-wise Check if the given string is valid English word or not Divide given number into two even parts Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 26250, "s": 26222, "text": "\n06 Jan, 2022" }, { "code": null, "e": 26397, "s": 26250, "text": "Given a string S, the task is to whether a string can be made palindrome after removing the occurrences of the same character, any number of times" }, { "code": null, "e": 26407, "s": 26397, "text": "Examples:" }, { "code": null, "e": 26557, "s": 26407, "text": "Input: S = “abczdzacb“Output: YesExplanation: Remove first and second occurrence of character ‘a’. String S becomes “bczdzcb”, which is a palindrome." }, { "code": null, "e": 26731, "s": 26557, "text": "Input: S = “madem”Output: NoExplanation: Since only we can remove 1 character of any frequency only once. There is no such character removing which a palindrome can be made." }, { "code": null, "e": 27245, "s": 26731, "text": "Approach: This problem can be solved by using the property of palindrome. It is obvious that removing the occurrences of the same character from the entire does not affect the palindromic nature. So the entire occurrences of that character can also be removed. So check the string from both the ends if they are not the same then check the string after the removal of entire occurrences of the character at both the ends. If any of the removals satisfies the palindromic condition then the answer is Yes else No. " }, { "code": null, "e": 27290, "s": 27245, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 27336, "s": 27290, "text": "Iterate using a loop in the range of (0, N/2)" }, { "code": null, "e": 27627, "s": 27336, "text": "Now check if characters from both the ends are equal or notIf the characters are not the sameCheck if it is Palindrome after removing the entire occurrence of character from both ends.If removing entire occurrences of a character from any end is a palindrome print “YES” and stop iteration." }, { "code": null, "e": 27859, "s": 27627, "text": "If the characters are not the sameCheck if it is Palindrome after removing the entire occurrence of character from both ends.If removing entire occurrences of a character from any end is a palindrome print “YES” and stop iteration." }, { "code": null, "e": 27951, "s": 27859, "text": "Check if it is Palindrome after removing the entire occurrence of character from both ends." }, { "code": null, "e": 28058, "s": 27951, "text": "If removing entire occurrences of a character from any end is a palindrome print “YES” and stop iteration." }, { "code": null, "e": 28125, "s": 28058, "text": "If after the whole traversal, no such palindrome found print “NO”." }, { "code": null, "e": 28176, "s": 28125, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28180, "s": 28176, "text": "C++" }, { "code": null, "e": 28185, "s": 28180, "text": "Java" }, { "code": null, "e": 28193, "s": 28185, "text": "Python3" }, { "code": null, "e": 28196, "s": 28193, "text": "C#" }, { "code": null, "e": 28207, "s": 28196, "text": "Javascript" }, { "code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether the string// is palindrome after removal or// neglecting character cbool check_palindrome(string str, char c){ int n = str.length(), i = 0, j = n - 1; while (i < j) { // If it is same as c neglect // this and move front if (str[i] == c) i++; // If it is same as c neglect // this and move back else if (str[j] == c) j--; // If they are not same it is // not a palindrome so return 0 else if (str[i] != str[j]) return 0; // It can be a palindrome so move // and check for remaining string else i++, j--; } return 1;} // Function to check if it is possible to// form a palindrome after removal of// any number of same characters oncestring make_palindrome(string str){ bool is_palindrome = 1; int n = str.length(); // If n==1 || n==2 it is always possible if (n == 1 || n == 2) { return \"YES\"; } // Check the character from both the ends // of the string for (int i = 0; i < n / 2; ++i) { // If the characters are not equal if (str[i] != str[n - 1 - i]) { // Remove str[i] and check if // it is a palindrome or // Remove str[n-i-1] and check // if it is a palindrome is_palindrome = check_palindrome(str, str[i]) || check_palindrome( str, str[n - 1 - i]); break; } } if (is_palindrome) return \"Yes\"; else return \"No\";} // Driver Codeint main(){ string S = \"madem\"; string res = make_palindrome(S); cout << (res); return 0;}", "e": 29998, "s": 28207, "text": null }, { "code": "// Java program for the above approachimport java.util.*;public class GFG{ // Function to check whether the string// is palindrome after removal or// neglecting character cstatic boolean check_palindrome(String str, char c){ int n = str.length(), i = 0, j = n - 1; while (i < j) { // If it is same as c neglect // this and move front if (str.charAt(i) == c) i++; // If it is same as c neglect // this and move back else if (str.charAt(j) == c) j--; // If they are not same it is // not a palindrome so return 0 else if (str.charAt(i) != str.charAt(j)) return false; // It can be a palindrome so move // and check for remaining string else { i++; j--; } } return true;} // Function to check if it is possible to// form a palindrome after removal of// any number of same characters oncestatic String make_palindrome(String str){ boolean is_palindrome = true; int n = str.length(); // If n==1 || n==2 it is always possible if (n == 1 || n == 2) { return \"YES\"; } // Check the character from both the ends // of the string for (int i = 0; i < n / 2; ++i) { // If the characters are not equal if (str.charAt(i) != str.charAt(n - 1 - i)) { // Remove str[i] and check if // it is a palindrome or // Remove str[n-i-1] and check // if it is a palindrome is_palindrome = check_palindrome(str, str.charAt(i)) || check_palindrome( str, str.charAt(n - 1 - i)); break; } } if (is_palindrome) return \"Yes\"; else return \"No\";} // Driver Codepublic static void main(String args[]){ String S = \"madem\"; String res = make_palindrome(S); System.out.println(res);}} // This code is contributed by Samim Hossain Mondal.", "e": 31977, "s": 29998, "text": null }, { "code": "# Python code for the above approach # Function to check whether the string# is palindrome after removal or# neglecting character cdef check_palindrome (str, c): n = len(str) i = 0 j = n - 1 while (i < j): # If it is same as c neglect # this and move front if (str[i] == c): i += 1 # If it is same as c neglect # this and move back elif (str[j] == c): j -= 1 # If they are not same it is # not a palindrome so return 0 elif (str[i] != str[j]): return 0 # It can be a palindrome so move # and check for remaining string else: i += 1 j -= 1 return 1 # Function to check if it is possible to# form a palindrome after removal of# any number of same characters oncedef make_palindrome (str): is_palindrome = 1 n = len(str) # If n==1 || n==2 it is always possible if (n == 1 or n == 2): return \"YES\" # Check the character from both the ends # of the string for i in range(n // 2): # If the characters are not equal if (str[i] != str[n - 1 - i]): # Remove str[i] and check if # it is a palindrome or # Remove str[n-i-1] and check # if it is a palindrome is_palindrome = check_palindrome(str, str[i]) or check_palindrome(str, str[n - 1 - i]) break if (is_palindrome): return \"Yes\" else: return \"No\" # Driver CodeS = \"madem\"res = make_palindrome(S)print(res) # This code is contributed by gfgking", "e": 33572, "s": 31977, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to check whether the string// is palindrome after removal or// neglecting character cstatic bool check_palindrome(string str, char c){ int n = str.Length, i = 0, j = n - 1; while (i < j) { // If it is same as c neglect // this and move front if (str[i] == c) i++; // If it is same as c neglect // this and move back else if (str[j] == c) j--; // If they are not same it is // not a palindrome so return 0 else if (str[i] != str[j]) return false; // It can be a palindrome so move // and check for remaining string else { i++; j--; } } return true;} // Function to check if it is possible to// form a palindrome after removal of// any number of same characters oncestatic string make_palindrome(string str){ bool is_palindrome = true; int n = str.Length; // If n==1 || n==2 it is always possible if (n == 1 || n == 2) { return \"YES\"; } // Check the character from both the ends // of the string for (int i = 0; i < n / 2; ++i) { // If the characters are not equal if (str[i] != str[n - 1 - i]) { // Remove str[i] and check if // it is a palindrome or // Remove str[n-i-1] and check // if it is a palindrome is_palindrome = check_palindrome(str, str[i]) || check_palindrome( str, str[n - 1 - i]); break; } } if (is_palindrome) return \"Yes\"; else return \"No\";} // Driver Codepublic static void Main(){ string S = \"madem\"; string res = make_palindrome(S); Console.Write(res);}} // This code is contributed by Samim Hossain Mondal.", "e": 35452, "s": 33572, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to check whether the string // is palindrome after removal or // neglecting character c const check_palindrome = (str, c) => { let n = str.length, i = 0, j = n - 1; while (i < j) { // If it is same as c neglect // this and move front if (str[i] == c) i++; // If it is same as c neglect // this and move back else if (str[j] == c) j--; // If they are not same it is // not a palindrome so return 0 else if (str[i] != str[j]) return 0; // It can be a palindrome so move // and check for remaining string else i++, j--; } return 1; } // Function to check if it is possible to // form a palindrome after removal of // any number of same characters once const make_palindrome = (str) => { let is_palindrome = 1; let n = str.length; // If n==1 || n==2 it is always possible if (n == 1 || n == 2) { return \"YES\"; } // Check the character from both the ends // of the string for (let i = 0; i < parseInt(n / 2); ++i) { // If the characters are not equal if (str[i] != str[n - 1 - i]) { // Remove str[i] and check if // it is a palindrome or // Remove str[n-i-1] and check // if it is a palindrome is_palindrome = check_palindrome(str, str[i]) || check_palindrome( str, str[n - 1 - i]); break; } } if (is_palindrome) return \"Yes\"; else return \"No\"; } // Driver Code let S = \"madem\"; let res = make_palindrome(S); document.write(res); // This code is contributed by rakeshsahni </script>", "e": 37468, "s": 35452, "text": null }, { "code": null, "e": 37474, "s": 37471, "text": "No" }, { "code": null, "e": 37558, "s": 37476, "text": "Time Complexity: O(N), Where N is the length of the string.Space Complexity: O(1)" }, { "code": null, "e": 37572, "s": 37560, "text": "rakeshsahni" }, { "code": null, "e": 37580, "s": 37572, "text": "gfgking" }, { "code": null, "e": 37590, "s": 37580, "text": "samim2000" }, { "code": null, "e": 37605, "s": 37590, "text": "Algo-Geek 2021" }, { "code": null, "e": 37615, "s": 37605, "text": "Algo Geek" }, { "code": null, "e": 37623, "s": 37615, "text": "Strings" }, { "code": null, "e": 37631, "s": 37623, "text": "Strings" }, { "code": null, "e": 37729, "s": 37631, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37781, "s": 37729, "text": "Count of operation required to water all the plants" }, { "code": null, "e": 37829, "s": 37781, "text": "Sort strings on the basis of their numeric part" }, { "code": null, "e": 37909, "s": 37829, "text": "Encode given String by inserting in Matrix column-wise and printing it row-wise" }, { "code": null, "e": 37964, "s": 37909, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 38004, "s": 37964, "text": "Divide given number into two even parts" }, { "code": null, "e": 38029, "s": 38004, "text": "Reverse a string in Java" }, { "code": null, "e": 38075, "s": 38029, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 38109, "s": 38075, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 38169, "s": 38109, "text": "Write a program to print all permutations of a given string" } ]
Python - Index Frequency Alphabet List - GeeksforGeeks
11 Sep, 2021 Create a String list with each character repeated as much as its position number. Method #1 : Using ascii_lowercase + ord() + loop In this, task of getting index is done using ord(), and ascii lowercase() is used for extracting alphabets. Loop is used to perform task for each letter. Python3 # Python3 code to demonstrate working of# Index Frequency Alphabet List# Using ascii_lowercase + ord() + loopfrom string import ascii_lowercase # extracting start indexstrt_idx = ord('a') - 1 res = []for ele in ascii_lowercase: # multiplying Frequency res.append(ele * (ord(ele) - strt_idx)) # printing resultprint("The constructed list : " + str(res)) The constructed list : ['a', 'bb', 'ccc', 'dddd', 'eeeee', 'ffffff', 'ggggggg', 'hhhhhhhh', 'iiiiiiiii', 'jjjjjjjjjj', 'kkkkkkkkkkk', 'llllllllllll', 'mmmmmmmmmmmmm', 'nnnnnnnnnnnnnn', 'ooooooooooooooo', 'pppppppppppppppp', 'qqqqqqqqqqqqqqqqq', 'rrrrrrrrrrrrrrrrrr', 'sssssssssssssssssss', 'tttttttttttttttttttt', 'uuuuuuuuuuuuuuuuuuuuu', 'vvvvvvvvvvvvvvvvvvvvvv', 'wwwwwwwwwwwwwwwwwwwwwww', 'xxxxxxxxxxxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzzzzzzzzzzzz'] Method #2 : Using list comprehension + ascii_lowercase + ord() In this, list comprehension is used to solve this problem. This is shorthand of above method. Python3 # Python3 code to demonstrate working of# Index Frequency Alphabet List# Using list comprehension + ascii_lowercase + ord()from string import ascii_lowercase # extracting start indexstrt_idx = ord('a') - 1 # list comprehension to solve as one linerres = [ele * (ord(ele) - strt_idx) for ele in ascii_lowercase] # printing resultprint("The constructed list : " + str(res)) The constructed list : ['a', 'bb', 'ccc', 'dddd', 'eeeee', 'ffffff', 'ggggggg', 'hhhhhhhh', 'iiiiiiiii', 'jjjjjjjjjj', 'kkkkkkkkkkk', 'llllllllllll', 'mmmmmmmmmmmmm', 'nnnnnnnnnnnnnn', 'ooooooooooooooo', 'pppppppppppppppp', 'qqqqqqqqqqqqqqqqq', 'rrrrrrrrrrrrrrrrrr', 'sssssssssssssssssss', 'tttttttttttttttttttt', 'uuuuuuuuuuuuuuuuuuuuu', 'vvvvvvvvvvvvvvvvvvvvvv', 'wwwwwwwwwwwwwwwwwwwwwww', 'xxxxxxxxxxxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzzzzzzzzzzzz'] akshaysingh98088 Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Read a file line by line in Python Defaultdict in Python Different ways to create Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 24475, "s": 24447, "text": "\n11 Sep, 2021" }, { "code": null, "e": 24557, "s": 24475, "text": "Create a String list with each character repeated as much as its position number." }, { "code": null, "e": 24606, "s": 24557, "text": "Method #1 : Using ascii_lowercase + ord() + loop" }, { "code": null, "e": 24760, "s": 24606, "text": "In this, task of getting index is done using ord(), and ascii lowercase() is used for extracting alphabets. Loop is used to perform task for each letter." }, { "code": null, "e": 24768, "s": 24760, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Index Frequency Alphabet List# Using ascii_lowercase + ord() + loopfrom string import ascii_lowercase # extracting start indexstrt_idx = ord('a') - 1 res = []for ele in ascii_lowercase: # multiplying Frequency res.append(ele * (ord(ele) - strt_idx)) # printing resultprint(\"The constructed list : \" + str(res))", "e": 25132, "s": 24768, "text": null }, { "code": null, "e": 25611, "s": 25132, "text": "The constructed list : ['a', 'bb', 'ccc', 'dddd', 'eeeee', 'ffffff', 'ggggggg', 'hhhhhhhh', 'iiiiiiiii', 'jjjjjjjjjj', 'kkkkkkkkkkk', 'llllllllllll', 'mmmmmmmmmmmmm', 'nnnnnnnnnnnnnn', 'ooooooooooooooo', 'pppppppppppppppp', 'qqqqqqqqqqqqqqqqq', 'rrrrrrrrrrrrrrrrrr', 'sssssssssssssssssss', 'tttttttttttttttttttt', 'uuuuuuuuuuuuuuuuuuuuu', 'vvvvvvvvvvvvvvvvvvvvvv', 'wwwwwwwwwwwwwwwwwwwwwww', 'xxxxxxxxxxxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzzzzzzzzzzzz']" }, { "code": null, "e": 25674, "s": 25611, "text": "Method #2 : Using list comprehension + ascii_lowercase + ord()" }, { "code": null, "e": 25768, "s": 25674, "text": "In this, list comprehension is used to solve this problem. This is shorthand of above method." }, { "code": null, "e": 25776, "s": 25768, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Index Frequency Alphabet List# Using list comprehension + ascii_lowercase + ord()from string import ascii_lowercase # extracting start indexstrt_idx = ord('a') - 1 # list comprehension to solve as one linerres = [ele * (ord(ele) - strt_idx) for ele in ascii_lowercase] # printing resultprint(\"The constructed list : \" + str(res))", "e": 26148, "s": 25776, "text": null }, { "code": null, "e": 26627, "s": 26148, "text": "The constructed list : ['a', 'bb', 'ccc', 'dddd', 'eeeee', 'ffffff', 'ggggggg', 'hhhhhhhh', 'iiiiiiiii', 'jjjjjjjjjj', 'kkkkkkkkkkk', 'llllllllllll', 'mmmmmmmmmmmmm', 'nnnnnnnnnnnnnn', 'ooooooooooooooo', 'pppppppppppppppp', 'qqqqqqqqqqqqqqqqq', 'rrrrrrrrrrrrrrrrrr', 'sssssssssssssssssss', 'tttttttttttttttttttt', 'uuuuuuuuuuuuuuuuuuuuu', 'vvvvvvvvvvvvvvvvvvvvvv', 'wwwwwwwwwwwwwwwwwwwwwww', 'xxxxxxxxxxxxxxxxxxxxxxxx', 'yyyyyyyyyyyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzzzzzzzzzzzz']" }, { "code": null, "e": 26644, "s": 26627, "text": "akshaysingh98088" }, { "code": null, "e": 26667, "s": 26644, "text": "Python string-programs" }, { "code": null, "e": 26674, "s": 26667, "text": "Python" }, { "code": null, "e": 26690, "s": 26674, "text": "Python Programs" }, { "code": null, "e": 26788, "s": 26690, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26797, "s": 26788, "text": "Comments" }, { "code": null, "e": 26810, "s": 26797, "text": "Old Comments" }, { "code": null, "e": 26828, "s": 26810, "text": "Python Dictionary" }, { "code": null, "e": 26850, "s": 26828, "text": "Enumerate() in Python" }, { "code": null, "e": 26885, "s": 26850, "text": "Read a file line by line in Python" }, { "code": null, "e": 26907, "s": 26885, "text": "Defaultdict in Python" }, { "code": null, "e": 26949, "s": 26907, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26971, "s": 26949, "text": "Defaultdict in Python" }, { "code": null, "e": 27010, "s": 26971, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27056, "s": 27010, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27094, "s": 27056, "text": "Python | Convert a list to dictionary" } ]
Python | Numpy matrix.astype() - GeeksforGeeks
10 Apr, 2019 With the help of Numpy matrix.astype() method, we are able to convert the type of matrix but the problem is data loss if we want to convert float to int then some of the data will loss. This method helps in type conversion of a matrix. Syntax : matrix.astype() Return : Return the matrix after type conversion. Example #1 :In this example we can see that how we convert the floating type matrix to int type matrix using matrix.astype() method. # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1.2, 2.8, 3.1, 4.5]') # applying matrix.astype() methodgeeks = gfg.astype(int) print(geeks) [[1 2 3 4]] Example #2 : # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1.1, 2, 3.5; 4.2, 5.5, 6; 7, 8, 9.3]') # applying matrix.astype() methodgeeks = gfg.astype(int) print(geeks) [[1 2 3] [4 5 6] [7 8 9]] Python numpy-Matrix Function 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 | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n10 Apr, 2019" }, { "code": null, "e": 25883, "s": 25647, "text": "With the help of Numpy matrix.astype() method, we are able to convert the type of matrix but the problem is data loss if we want to convert float to int then some of the data will loss. This method helps in type conversion of a matrix." }, { "code": null, "e": 25908, "s": 25883, "text": "Syntax : matrix.astype()" }, { "code": null, "e": 25958, "s": 25908, "text": "Return : Return the matrix after type conversion." }, { "code": null, "e": 26091, "s": 25958, "text": "Example #1 :In this example we can see that how we convert the floating type matrix to int type matrix using matrix.astype() method." }, { "code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1.2, 2.8, 3.1, 4.5]') # applying matrix.astype() methodgeeks = gfg.astype(int) print(geeks)", "e": 26312, "s": 26091, "text": null }, { "code": null, "e": 26325, "s": 26312, "text": "[[1 2 3 4]]\n" }, { "code": null, "e": 26338, "s": 26325, "text": "Example #2 :" }, { "code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1.1, 2, 3.5; 4.2, 5.5, 6; 7, 8, 9.3]') # applying matrix.astype() methodgeeks = gfg.astype(int) print(geeks)", "e": 26576, "s": 26338, "text": null }, { "code": null, "e": 26605, "s": 26576, "text": "[[1 2 3]\n [4 5 6]\n [7 8 9]]\n" }, { "code": null, "e": 26634, "s": 26605, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 26647, "s": 26634, "text": "Python-numpy" }, { "code": null, "e": 26654, "s": 26647, "text": "Python" }, { "code": null, "e": 26752, "s": 26654, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26784, "s": 26752, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26826, "s": 26784, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26868, "s": 26826, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26924, "s": 26868, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26951, "s": 26924, "text": "Python Classes and Objects" }, { "code": null, "e": 26982, "s": 26951, "text": "Python | os.path.join() method" }, { "code": null, "e": 27011, "s": 26982, "text": "Create a directory in Python" }, { "code": null, "e": 27033, "s": 27011, "text": "Defaultdict in Python" }, { "code": null, "e": 27069, "s": 27033, "text": "Python | Pandas dataframe.groupby()" } ]
Tutorial: Google Vision API with Python and Heroku | by Evan Fang | Towards Data Science
As we learned before, Google Vision AI could be divided into two parts, AutoML Vision and Vision API. For the Vision API reference, here is the previous post talking about what could Vision API does, how to create an API key, and then query it with curl. towardsdatascience.com Today, we are going to learn how to use it with Python. Then we could use it in our projects in the future. Before we get started, I would like to share the official tutorial with you. codelabs.developers.google.com There is a quick tutorial in the following paragraph, but if you want to know more detail after reading it, you still can learn it from the Google Codelabs. Great, now let’s begin. Establish a Vision API project.Enable the Vision API.Authenticate API requests and download the keyFile.json.Set GOOGLE_APPLICATION_CREDENTIALS with keyFile.json.Install the Google Client Vision API client library.Write Python code to query the Vision API.Push the code to Heroku. Establish a Vision API project. Enable the Vision API. Authenticate API requests and download the keyFile.json. Set GOOGLE_APPLICATION_CREDENTIALS with keyFile.json. Install the Google Client Vision API client library. Write Python code to query the Vision API. Push the code to Heroku. Sign-in to Google Cloud Platform Console and create a new project. Sign-in to Google Cloud Platform Console and create a new project. 2. Name the project and click the CREATE button. 3. Click Active Cloud Shell. 4. Then a console shell will appear at the bottom.Run $ gcloud auth list to confirm that you are authenticated.And also run $ gcloud config list project to confirm the project id. Run command line $ gcloud services enable vision.googleapis.com According to the Google Codelabs tutorial, we need to create a Service Account and a key for accessing the Vision API. In order to make requests to the Vision API, you need to use a Service Account. A Service Account is an account, belonging to your project, that is used by the Google Client Python library to make Vision API requests. Click the link below and follow the Setting up authentication GCP CONSOLE steps. cloud.google.com GO TO THE CREATE SERVICE ACCOUNT KEY PAGEFrom the Service account list, select New service account.In the Service account name field, enter a name.Don’t select a value from the Role list. No role is required to access this service. GO TO THE CREATE SERVICE ACCOUNT KEY PAGE From the Service account list, select New service account. In the Service account name field, enter a name. Don’t select a value from the Role list. No role is required to access this service. If all the settings are correctly set up, the UI would be like this: 5. Click Create. A note appears, warning that this service account has no role. 6. Click Create without role. A JSON file that contains your key downloads to your computer. Rename the JSON file as keyFile.json. Then set GOOGLE_APPLICATION_CREDENTIALS with the file. export GOOGLE_APPLICATION_CREDENTIALS=~/Desktop/keyFile.json Run pip freeze | grep google-cloud-vision to check if the library is already installed. Run pip freeze | grep google-cloud-vision to check if the library is already installed. 2. If you’re not setting the environment, please run pip install --upgrade google-cloud-vision. Copy and save the following code as a Python file. Run the Python file to test if all the environment settings are correctly set up. /usr/local/opt/python/bin/python3.7 [path/to/your/filename.py] We upload two superstar’s photos and use Face Detection in Vision API to get their face bounds and emotion. The input data: Here is the output: =========================================================File: {pic}Face surprised: VERY_UNLIKELYFace bounds: (207,54),(632,54),(632,547),(207,547)=========================================================File: {pic}Face surprised: LIKELYFace bounds: (16,38),(323,38),(323,394),(16,394) Congratulations! It means we have queried the Vision API successfully. Try other Vision APIs from the official tutorials. cloud.google.com Note: As the suggestion from Mandar Vaze, we should not upload our personal keyFile.json to the public space. If you have concern about the security issue, please refer to this post for the solution. If you still don’t know much about Heroku, please read the previous post first. medium.com In Step 6, the project is running well locally, but we need to build it as an online service for apps or web to use. Here is the code sample, please download it and learn how to push it online in the following steps. Here is the code sample, please download it and learn how to push it online in the following steps. https://github.com/mutant0113/Google_Vision_API_sample/blob/master/medium-google-vision-api.zip 2. Add your own Google Service Account keyFile.json to folder medium-google-vision-api/config/ 3. Create a new Heroku project. heroku loginheroku create [your/project/name] --buildpack heroku/python 4. Link the project and push code to the master branch. cd [path/to/your/local/project/download/from/step1]heroku git:remote -a [your/project/name]git push heroku master 5. Set GOOGLE_APPLICATION_CREDENTIALS with keyFile.json on Heroku. heroku config:set GOOGLE_APPLICATION_CREDENTIALS='config/keyFile.json' 6. Ensure that at least one instance of the app is running. heroku ps:scale web=1 7. Open Heroku website heroku open If everything is set properly, you should see the website with content like the image. 8. You can edit the code in hello/views.py and hello/vision_api.py That’s all for today. We can now start to write code using Google Vision API. Hope this post helps you to know more about the Google Vision API. If you have any questions or suggestions, welcome to leave a comment under this article. See you. Cloud Vision API pricing cloud.google.com Our Heroku code is based on the official sample code. devcenter.heroku.com Another tutorial for Node.js version.
[ { "code": null, "e": 427, "s": 172, "text": "As we learned before, Google Vision AI could be divided into two parts, AutoML Vision and Vision API. For the Vision API reference, here is the previous post talking about what could Vision API does, how to create an API key, and then query it with curl." }, { "code": null, "e": 450, "s": 427, "text": "towardsdatascience.com" }, { "code": null, "e": 558, "s": 450, "text": "Today, we are going to learn how to use it with Python. Then we could use it in our projects in the future." }, { "code": null, "e": 635, "s": 558, "text": "Before we get started, I would like to share the official tutorial with you." }, { "code": null, "e": 666, "s": 635, "text": "codelabs.developers.google.com" }, { "code": null, "e": 847, "s": 666, "text": "There is a quick tutorial in the following paragraph, but if you want to know more detail after reading it, you still can learn it from the Google Codelabs. Great, now let’s begin." }, { "code": null, "e": 1128, "s": 847, "text": "Establish a Vision API project.Enable the Vision API.Authenticate API requests and download the keyFile.json.Set GOOGLE_APPLICATION_CREDENTIALS with keyFile.json.Install the Google Client Vision API client library.Write Python code to query the Vision API.Push the code to Heroku." }, { "code": null, "e": 1160, "s": 1128, "text": "Establish a Vision API project." }, { "code": null, "e": 1183, "s": 1160, "text": "Enable the Vision API." }, { "code": null, "e": 1240, "s": 1183, "text": "Authenticate API requests and download the keyFile.json." }, { "code": null, "e": 1294, "s": 1240, "text": "Set GOOGLE_APPLICATION_CREDENTIALS with keyFile.json." }, { "code": null, "e": 1347, "s": 1294, "text": "Install the Google Client Vision API client library." }, { "code": null, "e": 1390, "s": 1347, "text": "Write Python code to query the Vision API." }, { "code": null, "e": 1415, "s": 1390, "text": "Push the code to Heroku." }, { "code": null, "e": 1482, "s": 1415, "text": "Sign-in to Google Cloud Platform Console and create a new project." }, { "code": null, "e": 1549, "s": 1482, "text": "Sign-in to Google Cloud Platform Console and create a new project." }, { "code": null, "e": 1598, "s": 1549, "text": "2. Name the project and click the CREATE button." }, { "code": null, "e": 1627, "s": 1598, "text": "3. Click Active Cloud Shell." }, { "code": null, "e": 1807, "s": 1627, "text": "4. Then a console shell will appear at the bottom.Run $ gcloud auth list to confirm that you are authenticated.And also run $ gcloud config list project to confirm the project id." }, { "code": null, "e": 1871, "s": 1807, "text": "Run command line $ gcloud services enable vision.googleapis.com" }, { "code": null, "e": 1990, "s": 1871, "text": "According to the Google Codelabs tutorial, we need to create a Service Account and a key for accessing the Vision API." }, { "code": null, "e": 2208, "s": 1990, "text": "In order to make requests to the Vision API, you need to use a Service Account. A Service Account is an account, belonging to your project, that is used by the Google Client Python library to make Vision API requests." }, { "code": null, "e": 2289, "s": 2208, "text": "Click the link below and follow the Setting up authentication GCP CONSOLE steps." }, { "code": null, "e": 2306, "s": 2289, "text": "cloud.google.com" }, { "code": null, "e": 2538, "s": 2306, "text": "GO TO THE CREATE SERVICE ACCOUNT KEY PAGEFrom the Service account list, select New service account.In the Service account name field, enter a name.Don’t select a value from the Role list. No role is required to access this service." }, { "code": null, "e": 2580, "s": 2538, "text": "GO TO THE CREATE SERVICE ACCOUNT KEY PAGE" }, { "code": null, "e": 2639, "s": 2580, "text": "From the Service account list, select New service account." }, { "code": null, "e": 2688, "s": 2639, "text": "In the Service account name field, enter a name." }, { "code": null, "e": 2773, "s": 2688, "text": "Don’t select a value from the Role list. No role is required to access this service." }, { "code": null, "e": 2842, "s": 2773, "text": "If all the settings are correctly set up, the UI would be like this:" }, { "code": null, "e": 2922, "s": 2842, "text": "5. Click Create. A note appears, warning that this service account has no role." }, { "code": null, "e": 3015, "s": 2922, "text": "6. Click Create without role. A JSON file that contains your key downloads to your computer." }, { "code": null, "e": 3108, "s": 3015, "text": "Rename the JSON file as keyFile.json. Then set GOOGLE_APPLICATION_CREDENTIALS with the file." }, { "code": null, "e": 3169, "s": 3108, "text": "export GOOGLE_APPLICATION_CREDENTIALS=~/Desktop/keyFile.json" }, { "code": null, "e": 3257, "s": 3169, "text": "Run pip freeze | grep google-cloud-vision to check if the library is already installed." }, { "code": null, "e": 3345, "s": 3257, "text": "Run pip freeze | grep google-cloud-vision to check if the library is already installed." }, { "code": null, "e": 3441, "s": 3345, "text": "2. If you’re not setting the environment, please run pip install --upgrade google-cloud-vision." }, { "code": null, "e": 3492, "s": 3441, "text": "Copy and save the following code as a Python file." }, { "code": null, "e": 3574, "s": 3492, "text": "Run the Python file to test if all the environment settings are correctly set up." }, { "code": null, "e": 3637, "s": 3574, "text": "/usr/local/opt/python/bin/python3.7 [path/to/your/filename.py]" }, { "code": null, "e": 3745, "s": 3637, "text": "We upload two superstar’s photos and use Face Detection in Vision API to get their face bounds and emotion." }, { "code": null, "e": 3761, "s": 3745, "text": "The input data:" }, { "code": null, "e": 3781, "s": 3761, "text": "Here is the output:" }, { "code": null, "e": 4067, "s": 3781, "text": "=========================================================File: {pic}Face surprised: VERY_UNLIKELYFace bounds: (207,54),(632,54),(632,547),(207,547)=========================================================File: {pic}Face surprised: LIKELYFace bounds: (16,38),(323,38),(323,394),(16,394)" }, { "code": null, "e": 4189, "s": 4067, "text": "Congratulations! It means we have queried the Vision API successfully. Try other Vision APIs from the official tutorials." }, { "code": null, "e": 4206, "s": 4189, "text": "cloud.google.com" }, { "code": null, "e": 4406, "s": 4206, "text": "Note: As the suggestion from Mandar Vaze, we should not upload our personal keyFile.json to the public space. If you have concern about the security issue, please refer to this post for the solution." }, { "code": null, "e": 4486, "s": 4406, "text": "If you still don’t know much about Heroku, please read the previous post first." }, { "code": null, "e": 4497, "s": 4486, "text": "medium.com" }, { "code": null, "e": 4614, "s": 4497, "text": "In Step 6, the project is running well locally, but we need to build it as an online service for apps or web to use." }, { "code": null, "e": 4714, "s": 4614, "text": "Here is the code sample, please download it and learn how to push it online in the following steps." }, { "code": null, "e": 4814, "s": 4714, "text": "Here is the code sample, please download it and learn how to push it online in the following steps." }, { "code": null, "e": 4910, "s": 4814, "text": "https://github.com/mutant0113/Google_Vision_API_sample/blob/master/medium-google-vision-api.zip" }, { "code": null, "e": 5005, "s": 4910, "text": "2. Add your own Google Service Account keyFile.json to folder medium-google-vision-api/config/" }, { "code": null, "e": 5037, "s": 5005, "text": "3. Create a new Heroku project." }, { "code": null, "e": 5109, "s": 5037, "text": "heroku loginheroku create [your/project/name] --buildpack heroku/python" }, { "code": null, "e": 5165, "s": 5109, "text": "4. Link the project and push code to the master branch." }, { "code": null, "e": 5279, "s": 5165, "text": "cd [path/to/your/local/project/download/from/step1]heroku git:remote -a [your/project/name]git push heroku master" }, { "code": null, "e": 5346, "s": 5279, "text": "5. Set GOOGLE_APPLICATION_CREDENTIALS with keyFile.json on Heroku." }, { "code": null, "e": 5417, "s": 5346, "text": "heroku config:set GOOGLE_APPLICATION_CREDENTIALS='config/keyFile.json'" }, { "code": null, "e": 5477, "s": 5417, "text": "6. Ensure that at least one instance of the app is running." }, { "code": null, "e": 5499, "s": 5477, "text": "heroku ps:scale web=1" }, { "code": null, "e": 5522, "s": 5499, "text": "7. Open Heroku website" }, { "code": null, "e": 5534, "s": 5522, "text": "heroku open" }, { "code": null, "e": 5621, "s": 5534, "text": "If everything is set properly, you should see the website with content like the image." }, { "code": null, "e": 5688, "s": 5621, "text": "8. You can edit the code in hello/views.py and hello/vision_api.py" }, { "code": null, "e": 5833, "s": 5688, "text": "That’s all for today. We can now start to write code using Google Vision API. Hope this post helps you to know more about the Google Vision API." }, { "code": null, "e": 5931, "s": 5833, "text": "If you have any questions or suggestions, welcome to leave a comment under this article. See you." }, { "code": null, "e": 5956, "s": 5931, "text": "Cloud Vision API pricing" }, { "code": null, "e": 5973, "s": 5956, "text": "cloud.google.com" }, { "code": null, "e": 6027, "s": 5973, "text": "Our Heroku code is based on the official sample code." }, { "code": null, "e": 6048, "s": 6027, "text": "devcenter.heroku.com" } ]
How MySQL LEFT JOIN can be used to simulate the MySQL MINUS query?
Since we cannot use MINUS query in MySQL, we will use LEFT JOIN to simulate the MINUS query. It can be understood with the help of the following example: In this example, we are two tables namely Student_detail and Student_info having the following data − mysql> Select * from Student_detail; +-----------+---------+------------+------------+ | studentid | Name | Address | Subject | +-----------+---------+------------+------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Chandigarh | Literature | | 130 | Ram | Jhansi | Computers | | 132 | Shyam | Chandigarh | Economics | | 133 | Mohan | Delhi | Computers | | 150 | Rajesh | Jaipur | Yoga | | 160 | Pradeep | Kochi | Hindi | +-----------+---------+------------+------------+ 7 rows in set (0.00 sec) mysql> Select * from Student_info; +-----------+-----------+------------+-------------+ | studentid | Name | Address | Subject | +-----------+-----------+------------+-------------+ | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Chandigarh | Literature | | 130 | Ram | Jhansi | Computers | | 132 | Shyam | Chandigarh | Economics | | 133 | Mohan | Delhi | Computers | | 165 | Abhimanyu | Calcutta | Electronics | +-----------+-----------+------------+-------------+ 6 rows in set (0.00 sec) Now, the following query using LEFT JOIN will simulate MINUS to return the ‘studentid’ values in student_info but not in Student_detail table. mysql> SELECT studentid from student_info LEFT JOIN Student_detail USING(studentid) WHERE student_detail.studentid IS NULL; +-----------+ | studentid | +-----------+ | 165 | +-----------+ 1 row in set (0.07 sec) Now, the following query will give us the opposite result of above query i.e. it will return the ‘studentid’ values in student_detail but not in Student_info table. mysql> SELECT studentid from student_detail LEFT JOIN Student_info USING(studentid) WHERE student_info.studentid IS NULL; +-----------+ | studentid | +-----------+ | 150 | | 160 | +-----------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1216, "s": 1062, "text": "Since we cannot use MINUS query in MySQL, we will use LEFT JOIN to simulate the MINUS query. It can be understood with the help of the following example:" }, { "code": null, "e": 1318, "s": 1216, "text": "In this example, we are two tables namely Student_detail and Student_info having the following data −" }, { "code": null, "e": 2521, "s": 1318, "text": "mysql> Select * from Student_detail;\n+-----------+---------+------------+------------+\n| studentid | Name | Address | Subject |\n+-----------+---------+------------+------------+\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Chandigarh | Literature |\n| 130 | Ram | Jhansi | Computers |\n| 132 | Shyam | Chandigarh | Economics |\n| 133 | Mohan | Delhi | Computers |\n| 150 | Rajesh | Jaipur | Yoga |\n| 160 | Pradeep | Kochi | Hindi |\n+-----------+---------+------------+------------+\n7 rows in set (0.00 sec)\n\nmysql> Select * from Student_info;\n+-----------+-----------+------------+-------------+\n| studentid | Name | Address | Subject |\n+-----------+-----------+------------+-------------+\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Chandigarh | Literature |\n| 130 | Ram | Jhansi | Computers |\n| 132 | Shyam | Chandigarh | Economics |\n| 133 | Mohan | Delhi | Computers |\n| 165 | Abhimanyu | Calcutta | Electronics |\n+-----------+-----------+------------+-------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2664, "s": 2521, "text": "Now, the following query using LEFT JOIN will simulate MINUS to return the ‘studentid’ values in student_info but not in Student_detail table." }, { "code": null, "e": 2882, "s": 2664, "text": "mysql> SELECT studentid from student_info LEFT JOIN Student_detail USING(studentid) WHERE student_detail.studentid IS NULL;\n+-----------+\n| studentid |\n+-----------+\n| 165 |\n+-----------+\n1 row in set (0.07 sec)" }, { "code": null, "e": 3047, "s": 2882, "text": "Now, the following query will give us the opposite result of above query i.e. it will return the ‘studentid’ values in student_detail but not in Student_info table." }, { "code": null, "e": 3278, "s": 3047, "text": "mysql> SELECT studentid from student_detail LEFT JOIN Student_info USING(studentid) WHERE student_info.studentid IS NULL;\n+-----------+\n| studentid |\n+-----------+\n| 150 |\n| 160 |\n+-----------+\n2 rows in set (0.00 sec)" } ]
JavaScript - Date getMinutes() Method
Javascript date getMinutes() method returns the minutes in the specified date according to local time. The value returned by getMinutes() is an integer between 0 and 59. Its syntax is as follows − Date.getMinutes() Returns the minutes in the specified date according to local time. Try the following example. <html> <head> <title>JavaScript getMinutes Method</title> </head> <body> <script type = "text/javascript"> var dt = new Date( "December 25, 1995 23:15:00" ); document.write("getMinutes() : " + dt.getMinutes() ); </script> </body> </html> getMinutes() : 15 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2636, "s": 2466, "text": "Javascript date getMinutes() method returns the minutes in the specified date according to local time. The value returned by getMinutes() is an integer between 0 and 59." }, { "code": null, "e": 2663, "s": 2636, "text": "Its syntax is as follows −" }, { "code": null, "e": 2682, "s": 2663, "text": "Date.getMinutes()\n" }, { "code": null, "e": 2749, "s": 2682, "text": "Returns the minutes in the specified date according to local time." }, { "code": null, "e": 2776, "s": 2749, "text": "Try the following example." }, { "code": null, "e": 3076, "s": 2776, "text": "<html>\n <head>\n <title>JavaScript getMinutes Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var dt = new Date( \"December 25, 1995 23:15:00\" );\n document.write(\"getMinutes() : \" + dt.getMinutes() ); \n </script> \n </body>\n</html>" }, { "code": null, "e": 3096, "s": 3076, "text": "getMinutes() : 15 \n" }, { "code": null, "e": 3131, "s": 3096, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3145, "s": 3131, "text": " Anadi Sharma" }, { "code": null, "e": 3179, "s": 3145, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3193, "s": 3179, "text": " Lets Kode It" }, { "code": null, "e": 3228, "s": 3193, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3245, "s": 3228, "text": " Frahaan Hussain" }, { "code": null, "e": 3280, "s": 3245, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3297, "s": 3280, "text": " Frahaan Hussain" }, { "code": null, "e": 3330, "s": 3297, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3358, "s": 3330, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3392, "s": 3358, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3420, "s": 3392, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3427, "s": 3420, "text": " Print" }, { "code": null, "e": 3438, "s": 3427, "text": " Add Notes" } ]
How to import other Python files?
To use any package in your code, you must first make it accessible. You have to import it. You can't use anything in Python before it is defined. Some things are built in, for example the basic types (like int, float, etc) can be used whenever you want. But most things you will want to do will need a little more than that. For example, if you want to calculate cosine of 1 radian, if you run math.cos(0), you'll get a NameError as math is not defined. You need to tell python to first import that module in your code so that you can use it. >>> math.cos(0) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'math' is not defined >>> import math >>> math.cos(0) 1.0 If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory. # For files in other directories, provide path to that file, absolute or relative.
[ { "code": null, "e": 1516, "s": 1062, "text": "To use any package in your code, you must first make it accessible. You have to import it. You can't use anything in Python before it is defined. Some things are built in, for example the basic types (like int, float, etc) can be used whenever you want. But most things you will want to do will need a little more than that. For example, if you want to calculate cosine of 1 radian, if you run math.cos(0), you'll get a NameError as math is not defined." }, { "code": null, "e": 1605, "s": 1516, "text": "You need to tell python to first import that module in your code so that you can use it." }, { "code": null, "e": 1768, "s": 1605, "text": ">>> math.cos(0)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'math' is not defined\n>>> import math\n>>> math.cos(0)\n1.0" }, { "code": null, "e": 1867, "s": 1768, "text": "If you have your own python files you want to import, you can use the import statement as follows:" }, { "code": null, "e": 2055, "s": 1867, "text": ">>> import my_file # assuming you have the file, my_file.py in the current directory.\n # For files in other directories, provide path to that file, absolute or relative." } ]
Feature Engineering Techniques. Mapping raw data to machine learning... | by Samuel Ozechi | Towards Data Science
Feature engineering is one of the key steps in developing machine learning models. This involves any of the processes of selecting, aggregating, or extracting features from raw data with the aim of mapping the raw data to machine learning features. The type of feature engineering process that is applied to a data depends on its datatype. Numerical and non-numerical data are the two basic datatypes that can be present in a raw dat; These can be subdivided into discrete, continuous, categorical, text, image and temporal data types. This post focuses on feature engineering numerical, categorical and text data. It also considers ways of handling missing data and deriving new features to improve model performance. The numerical and non-numerical columns of a data that has been read into a Pandas dataframe can be differentiated according to the datatypes of its columns thus: Numerical data is a general term for the features data that hold numerical values that can be arranged in a logical order. It is often easier to work with numerical features in machine learning as numerical data formats (integer, floats, etc.) are ingestible by machine learning algorithms. For example, Let’s look at some of the numerical data of the popular Housing price dataset. The numerical data of a raw data are often expressed in different scales. Like in the example above, some columns such as the “FullBath” and “HalfBath” have lower scales (<10) while others such as “1stFlrSF” and “2ndFlrSF” have higher scales ( >1000). It is often a good practice to standardize the scales of the input numerical data to have a similar range in order to avoid the algorithms from assigning more weights to the features with larger scales during training. Numerical data can be scaled using Sklearn’s MinMaxScaler or StandardScaler. The MinMaxScaler scales all the numerical data to have a range of 0 to 1 while the StandardScaler scales the numerical data to a have a unit variance and mean of 0, thereby standardizing the numerical input. Non-numerical data include categorical and text data that are often encoded into numerals before being ingested into machine learning models. Categorical data could be sometimes expressed as numbers but are not to be confused as numerical data as they show the relationship between different classes of a data. Below is a dataframe of some categorical columns of the Housing price dataset. To avoid making assumptions that categorical data that are expressed as numerical values are numerical features during training, it’s often preferable to one-hot encode categorical features as against label encoding them, which may trick machine learning algorithms to assume algebraic relationships among categories. Unlike in label encoding where numerical values are simply assigned to represent respective categories, With one-hot encoding, each categorical value is converted into a new categorical column and assigned a binary value of 1 or 0, thereby representing each value as a binary vector. This prevents the algorithm from assuming numerical ordering or relationships among categories (like assuming that a boy > a girl, if they are label encoded with 1 and 0 respectively), thereby improving the performance of the model in learning the relationship within the data. Following the previous example, below is subpart of sample categorial columns from the Housing price dataset. Rather than represent each of the categories in these columns with a numerical value (0, 1, 2, 3,...) as in label encoding for model ingestion, it is rather optimal to one-hot encode the features in the dataframe, such that the presence of a category in a datapoint is denoted with one (1) while an absence is denoted with zero (0). This can be easily done using using Scikit Learn’s oneHotEncoder. The results show one-hot encoded features that could be ingested into models for efficient performance. Notice that the output dataframe now contains more dimensions (columns) which have numerical values (1.0, 0.0) that are representative of the presence or absence of that category in each datapoint. Thus, each column has been expanded into separate columns according to the number of categories in that column, for all the categorical columns. For text data, it is necessary to represent them as numerical values which are recognized by machine learning algorithms through a process known as vectorization. Some common text vectorization techniques are word count, term frequency–inverse document frequency (TF–IDF) and word embeddings. Word count is a simple vectorization technique of representing text data as numerical values according to the frequency of their occurrence in the data. Consider a list of texts below for example: text_data = ['Today is a good day for battle', 'Battle of good against evil', 'For the day after today is Monday', 'Monday is a good day for good'] To vectorize the text data above using the word count technique, a sparse matrix is formed by recording the number of times each word appears in the text data. This can be achieved using using Scikit Learn’s CountVectorizer. The output dataframe shows the vectorized features of the input text data which can now be ingested into algorithms. While this technique achieves the vectorization purpose, it is suboptimal for machine learning algorithms as it only focuses on the frequency of words in the data. A better alternative approach is the Term Frequency–Inverse Document Frequency (TF–IDF) method that focuses on both the frequency of the words and their importance in the text data. In TF-IDF, the importance of each word in a text data is inferred by the inverse document frequency (IDF) of the word. The inverse document frequency is a statistical measure that evaluates how relevant a word is to a text in a collection of texts. The IDF for each word is calculated thus: idf = ln[1+N]/(1+df)]+1where: idf = Inverse document frequencyN = Number of texts in the data, N=4 for our example.df = the document frequencyThe df is the number of texts that a particular word appears in the data; for instance, the word "good" appears four (4) times in the data but has a df of (3) as it appears in 3 texts (once for two texts and twice for another text). An important aspect of the TF-IDF approach is that it assigns low scores to words that are either abundant or rare in the text data as it assumes that they are of less importance in finding patterns in the data . This is usually helpful in building efficient models as common words such as ‘the’, ‘is’, ‘are’, ‘of’ and rare words are mostly of little or no help in real time pattern recognition in text data. Sklearn’s TfidfVectorizer is useful to easily vectorize text data in this way. The output shows that the text data is vectorized according to the TF-IDF values of the words and can be then ingested into algorithms for learning. The disadvantage of the TD-IDF approach is that it doesn’t take account for words which share similar meanings as in word embeddings; nevertheless, it’s still a good fit for vectorizing text data. Another common technique of improving the performance of machine learning models through feature engineering is by deriving new features from existing features. This can be done by mathematically combining the input features in some way, thereby transforming the input features before training on it. In the Housing price dataset example for instance, features such as the Square feet per room or Total number of rooms in the house are often more reflective and indicative on the target price of the house than individual features such as the number of bedrooms, bathrooms etc. In cases where such useful features are not present in the data, they could be derived by mathematically combining the input features. Missing data are also another problem when working with raw data in machine learning. Dealing with missing data is an important aspect of feature engineering since raw data are often incomplete. Handling missing values in the data usually involves dropping the data points with missing values altogether, replacing missing values by utilizing any of the measures of central tendency(mean, median or mode) or by matrix completion. After carrying out most of the previously outlined steps according to the data type, your raw data are now transformed into feature vectors that can be passed into machine learning algorithms for the training phase. Summary: Feature engineering involves the processes of mapping raw data to machine learning features. The processes of feature engineering depends on the types of the data. common feature engineering processes includes scaling numerical data, label or one-hot encoding categorical data, vectorizing text data, deriving new features and handling missing data. Proper feature engineering helps to make raw data suitable for ingestion into machine learning models and improves the performance of machine learning models.
[ { "code": null, "e": 421, "s": 172, "text": "Feature engineering is one of the key steps in developing machine learning models. This involves any of the processes of selecting, aggregating, or extracting features from raw data with the aim of mapping the raw data to machine learning features." }, { "code": null, "e": 708, "s": 421, "text": "The type of feature engineering process that is applied to a data depends on its datatype. Numerical and non-numerical data are the two basic datatypes that can be present in a raw dat; These can be subdivided into discrete, continuous, categorical, text, image and temporal data types." }, { "code": null, "e": 891, "s": 708, "text": "This post focuses on feature engineering numerical, categorical and text data. It also considers ways of handling missing data and deriving new features to improve model performance." }, { "code": null, "e": 1054, "s": 891, "text": "The numerical and non-numerical columns of a data that has been read into a Pandas dataframe can be differentiated according to the datatypes of its columns thus:" }, { "code": null, "e": 1345, "s": 1054, "text": "Numerical data is a general term for the features data that hold numerical values that can be arranged in a logical order. It is often easier to work with numerical features in machine learning as numerical data formats (integer, floats, etc.) are ingestible by machine learning algorithms." }, { "code": null, "e": 1437, "s": 1345, "text": "For example, Let’s look at some of the numerical data of the popular Housing price dataset." }, { "code": null, "e": 1908, "s": 1437, "text": "The numerical data of a raw data are often expressed in different scales. Like in the example above, some columns such as the “FullBath” and “HalfBath” have lower scales (<10) while others such as “1stFlrSF” and “2ndFlrSF” have higher scales ( >1000). It is often a good practice to standardize the scales of the input numerical data to have a similar range in order to avoid the algorithms from assigning more weights to the features with larger scales during training." }, { "code": null, "e": 2193, "s": 1908, "text": "Numerical data can be scaled using Sklearn’s MinMaxScaler or StandardScaler. The MinMaxScaler scales all the numerical data to have a range of 0 to 1 while the StandardScaler scales the numerical data to a have a unit variance and mean of 0, thereby standardizing the numerical input." }, { "code": null, "e": 2335, "s": 2193, "text": "Non-numerical data include categorical and text data that are often encoded into numerals before being ingested into machine learning models." }, { "code": null, "e": 2583, "s": 2335, "text": "Categorical data could be sometimes expressed as numbers but are not to be confused as numerical data as they show the relationship between different classes of a data. Below is a dataframe of some categorical columns of the Housing price dataset." }, { "code": null, "e": 2901, "s": 2583, "text": "To avoid making assumptions that categorical data that are expressed as numerical values are numerical features during training, it’s often preferable to one-hot encode categorical features as against label encoding them, which may trick machine learning algorithms to assume algebraic relationships among categories." }, { "code": null, "e": 3463, "s": 2901, "text": "Unlike in label encoding where numerical values are simply assigned to represent respective categories, With one-hot encoding, each categorical value is converted into a new categorical column and assigned a binary value of 1 or 0, thereby representing each value as a binary vector. This prevents the algorithm from assuming numerical ordering or relationships among categories (like assuming that a boy > a girl, if they are label encoded with 1 and 0 respectively), thereby improving the performance of the model in learning the relationship within the data." }, { "code": null, "e": 3573, "s": 3463, "text": "Following the previous example, below is subpart of sample categorial columns from the Housing price dataset." }, { "code": null, "e": 3972, "s": 3573, "text": "Rather than represent each of the categories in these columns with a numerical value (0, 1, 2, 3,...) as in label encoding for model ingestion, it is rather optimal to one-hot encode the features in the dataframe, such that the presence of a category in a datapoint is denoted with one (1) while an absence is denoted with zero (0). This can be easily done using using Scikit Learn’s oneHotEncoder." }, { "code": null, "e": 4419, "s": 3972, "text": "The results show one-hot encoded features that could be ingested into models for efficient performance. Notice that the output dataframe now contains more dimensions (columns) which have numerical values (1.0, 0.0) that are representative of the presence or absence of that category in each datapoint. Thus, each column has been expanded into separate columns according to the number of categories in that column, for all the categorical columns." }, { "code": null, "e": 4712, "s": 4419, "text": "For text data, it is necessary to represent them as numerical values which are recognized by machine learning algorithms through a process known as vectorization. Some common text vectorization techniques are word count, term frequency–inverse document frequency (TF–IDF) and word embeddings." }, { "code": null, "e": 4909, "s": 4712, "text": "Word count is a simple vectorization technique of representing text data as numerical values according to the frequency of their occurrence in the data. Consider a list of texts below for example:" }, { "code": null, "e": 5091, "s": 4909, "text": "text_data = ['Today is a good day for battle', 'Battle of good against evil', 'For the day after today is Monday', 'Monday is a good day for good']" }, { "code": null, "e": 5316, "s": 5091, "text": "To vectorize the text data above using the word count technique, a sparse matrix is formed by recording the number of times each word appears in the text data. This can be achieved using using Scikit Learn’s CountVectorizer." }, { "code": null, "e": 5779, "s": 5316, "text": "The output dataframe shows the vectorized features of the input text data which can now be ingested into algorithms. While this technique achieves the vectorization purpose, it is suboptimal for machine learning algorithms as it only focuses on the frequency of words in the data. A better alternative approach is the Term Frequency–Inverse Document Frequency (TF–IDF) method that focuses on both the frequency of the words and their importance in the text data." }, { "code": null, "e": 6070, "s": 5779, "text": "In TF-IDF, the importance of each word in a text data is inferred by the inverse document frequency (IDF) of the word. The inverse document frequency is a statistical measure that evaluates how relevant a word is to a text in a collection of texts. The IDF for each word is calculated thus:" }, { "code": null, "e": 6445, "s": 6070, "text": "idf = ln[1+N]/(1+df)]+1where: idf = Inverse document frequencyN = Number of texts in the data, N=4 for our example.df = the document frequencyThe df is the number of texts that a particular word appears in the data; for instance, the word \"good\" appears four (4) times in the data but has a df of (3) as it appears in 3 texts (once for two texts and twice for another text)." }, { "code": null, "e": 6933, "s": 6445, "text": "An important aspect of the TF-IDF approach is that it assigns low scores to words that are either abundant or rare in the text data as it assumes that they are of less importance in finding patterns in the data . This is usually helpful in building efficient models as common words such as ‘the’, ‘is’, ‘are’, ‘of’ and rare words are mostly of little or no help in real time pattern recognition in text data. Sklearn’s TfidfVectorizer is useful to easily vectorize text data in this way." }, { "code": null, "e": 7279, "s": 6933, "text": "The output shows that the text data is vectorized according to the TF-IDF values of the words and can be then ingested into algorithms for learning. The disadvantage of the TD-IDF approach is that it doesn’t take account for words which share similar meanings as in word embeddings; nevertheless, it’s still a good fit for vectorizing text data." }, { "code": null, "e": 7580, "s": 7279, "text": "Another common technique of improving the performance of machine learning models through feature engineering is by deriving new features from existing features. This can be done by mathematically combining the input features in some way, thereby transforming the input features before training on it." }, { "code": null, "e": 7992, "s": 7580, "text": "In the Housing price dataset example for instance, features such as the Square feet per room or Total number of rooms in the house are often more reflective and indicative on the target price of the house than individual features such as the number of bedrooms, bathrooms etc. In cases where such useful features are not present in the data, they could be derived by mathematically combining the input features." }, { "code": null, "e": 8422, "s": 7992, "text": "Missing data are also another problem when working with raw data in machine learning. Dealing with missing data is an important aspect of feature engineering since raw data are often incomplete. Handling missing values in the data usually involves dropping the data points with missing values altogether, replacing missing values by utilizing any of the measures of central tendency(mean, median or mode) or by matrix completion." }, { "code": null, "e": 8638, "s": 8422, "text": "After carrying out most of the previously outlined steps according to the data type, your raw data are now transformed into feature vectors that can be passed into machine learning algorithms for the training phase." } ]
JavaMail API - Sending an HTML Email
Here is an example to send an HTML email from your machine. Here we have used JangoSMPT server via which emails are sent to our destination email address. The setup is explained in the Environment Setup chapter. This example is very similar to sending simple email, except that, here we are using setContent() method to set content whose second argument is "text/html" to specify that the HTML content is included in the message. Using this example, you can send as big as HTML content you like. To send a email with HTML content, the steps followed are: Get a Session Get a Session Create a default MimeMessage object and set From, To, Subject in the message. Create a default MimeMessage object and set From, To, Subject in the message. Set the actual message using setContent() method as below: message.setContent("<h1>This is actual message embedded in HTML tags</h1>", "text/html"); Set the actual message using setContent() method as below: message.setContent("<h1>This is actual message embedded in HTML tags</h1>", "text/html"); Send the message using the Transport object. Send the message using the Transport object. Create a java class file SendHTMLEmail, the contents of which are as follows: package com.tutorialspoint; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendHTMLEmail { public static void main(String[] args) { // Recipient's email ID needs to be mentioned. String to = "destinationemail@gmail.com"; // Sender's email ID needs to be mentioned String from = "fromemail@gmail.com"; final String username = "manishaspatil";//change accordingly final String password = "******";//change accordingly // Assuming you are sending email through relay.jangosmtp.net String host = "relay.jangosmtp.net"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "25"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("Testing Subject"); // Send the actual HTML message, as big as you like message.setContent( "<h1>This is actual message embedded in HTML tags</h1>", "text/html"); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { e.printStackTrace(); throw new RuntimeException(e); } } } As we are using the SMTP server provided by the host provider JangoSMTP, we need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password. Now that our class is ready, let us compile the above class. I've saved the class SendHTMLEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendHTMLEmail.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendHTMLEmail You should see the following message on the command console: Sent message successfully.... As I'm sending an email to my gmail address through JangoSMTP, the following mail would be received in my gmail account inbox: Print Add Notes Bookmark this page
[ { "code": null, "e": 2284, "s": 2071, "text": "Here is an example to send an HTML email from your machine. Here we have used JangoSMPT server via which emails are sent to our destination email address. The setup is explained in the Environment Setup chapter." }, { "code": null, "e": 2569, "s": 2284, "text": "This example is very similar to sending simple email, except that, here we are using setContent() method to set content whose second argument is \"text/html\" to specify that the HTML content is included in the message. Using this example, you can send as big as HTML content you like. " }, { "code": null, "e": 2628, "s": 2569, "text": "To send a email with HTML content, the steps followed are:" }, { "code": null, "e": 2642, "s": 2628, "text": "Get a Session" }, { "code": null, "e": 2656, "s": 2642, "text": "Get a Session" }, { "code": null, "e": 2734, "s": 2656, "text": "Create a default MimeMessage object and set From, To, Subject in the message." }, { "code": null, "e": 2812, "s": 2734, "text": "Create a default MimeMessage object and set From, To, Subject in the message." }, { "code": null, "e": 2966, "s": 2812, "text": "Set the actual message using setContent() method as below:\nmessage.setContent(\"<h1>This is actual message embedded in \n HTML tags</h1>\", \"text/html\");\n" }, { "code": null, "e": 3025, "s": 2966, "text": "Set the actual message using setContent() method as below:" }, { "code": null, "e": 3119, "s": 3025, "text": "message.setContent(\"<h1>This is actual message embedded in \n HTML tags</h1>\", \"text/html\");" }, { "code": null, "e": 3164, "s": 3119, "text": "Send the message using the Transport object." }, { "code": null, "e": 3209, "s": 3164, "text": "Send the message using the Transport object." }, { "code": null, "e": 3287, "s": 3209, "text": "Create a java class file SendHTMLEmail, the contents of which are as follows:" }, { "code": null, "e": 5449, "s": 3287, "text": "package com.tutorialspoint;\n\nimport java.util.Properties;\n\nimport javax.mail.Message;\nimport javax.mail.MessagingException;\nimport javax.mail.PasswordAuthentication;\nimport javax.mail.Session;\nimport javax.mail.Transport;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeMessage;\n\npublic class SendHTMLEmail {\n public static void main(String[] args) {\n // Recipient's email ID needs to be mentioned.\n String to = \"destinationemail@gmail.com\";\n\n // Sender's email ID needs to be mentioned\n String from = \"fromemail@gmail.com\";\n final String username = \"manishaspatil\";//change accordingly\n final String password = \"******\";//change accordingly\n\n // Assuming you are sending email through relay.jangosmtp.net\n String host = \"relay.jangosmtp.net\";\n\n Properties props = new Properties();\n props.put(\"mail.smtp.auth\", \"true\");\n props.put(\"mail.smtp.starttls.enable\", \"true\");\n props.put(\"mail.smtp.host\", host);\n props.put(\"mail.smtp.port\", \"25\");\n\n // Get the Session object.\n Session session = Session.getInstance(props,\n new javax.mail.Authenticator() {\n protected PasswordAuthentication getPasswordAuthentication() {\n return new PasswordAuthentication(username, password);\n }\n\t});\n\n try {\n // Create a default MimeMessage object.\n Message message = new MimeMessage(session);\n\n \t // Set From: header field of the header.\n\t message.setFrom(new InternetAddress(from));\n\n\t // Set To: header field of the header.\n\t message.setRecipients(Message.RecipientType.TO,\n InternetAddress.parse(to));\n\n\t // Set Subject: header field\n\t message.setSubject(\"Testing Subject\");\n\n\t // Send the actual HTML message, as big as you like\n\t message.setContent(\n \"<h1>This is actual message embedded in HTML tags</h1>\",\n \"text/html\");\n\n\t // Send message\n\t Transport.send(message);\n\n\t System.out.println(\"Sent message successfully....\");\n\n } catch (MessagingException e) {\n\t e.printStackTrace();\n\t throw new RuntimeException(e);\n }\n }\n}" }, { "code": null, "e": 5655, "s": 5449, "text": "As we are using the SMTP server provided by the host provider JangoSMTP, we need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password." }, { "code": null, "e": 6004, "s": 5655, "text": "Now that our class is ready, let us compile the above class. I've saved the class SendHTMLEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt:" }, { "code": null, "e": 6092, "s": 6004, "text": "javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendHTMLEmail.java" }, { "code": null, "e": 6158, "s": 6092, "text": "Now that the class is compiled, execute the below command to run:" }, { "code": null, "e": 6240, "s": 6158, "text": "java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendHTMLEmail" }, { "code": null, "e": 6301, "s": 6240, "text": "You should see the following message on the command console:" }, { "code": null, "e": 6331, "s": 6301, "text": "Sent message successfully...." }, { "code": null, "e": 6458, "s": 6331, "text": "As I'm sending an email to my gmail address through JangoSMTP, the following mail would be received in my gmail account inbox:" }, { "code": null, "e": 6465, "s": 6458, "text": " Print" }, { "code": null, "e": 6476, "s": 6465, "text": " Add Notes" } ]
0 - 1 Knapsack Problem | Practice | GeeksforGeeks
You are given weights and values of N items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that we have only one quantity of each item. In other words, given two integer arrays val[0..N-1] and wt[0..N-1] which represent values and weights associated with N items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item or dont pick it (0-1 property). Example 1: Input: N = 3 W = 4 values[] = {1,2,3} weight[] = {4,5,1} Output: 3 Example 2: Input: N = 3 W = 3 values[] = {1,2,3} weight[] = {4,5,6} Output: 0 Your Task: Complete the function knapSack() which takes maximum capacity W, weight array wt[], value array val[], and the number of items n as a parameter and returns the maximum possible value you can get. Expected Time Complexity: O(N*W). Expected Auxiliary Space: O(N*W) Constraints: 1 ≤ N ≤ 1000 1 ≤ W ≤ 1000 1 ≤ wt[i] ≤ 1000 1 ≤ v[i] ≤ 1000 0 itsmemritu14 hours ago int knapSack(int W, int wt[], int val[], int n) { // Your code here int dp[n+1][W+1]; for(int i=0 ;i<n+1 ;i++){ for(int j=0 ;j<W+1 ;j++){ if(i==0 or j==0){ dp[i][j]=0; continue; } if(wt[i-1]<=j){ dp[i][j]=max( (val[i-1]+ dp[i-1][j-wt[i-1]]) , (dp[i-1][j]) ); } else{ dp[i][j]=dp[i-1][j]; } } } return dp[n][W]; } +1 mr_coder99335 days ago C++/Simple Time Complexity:- O(n*W) Space Complexity:- O(W) Using Tabulation int knapSack(int W, int wt[], int val[], int n) { vector<int> dp(W+1,0),temp(W+1); for(int i=0;i<n;i++){ temp[0]=0; for(int j=1;j<=W;j++){ temp[j]=dp[j]; if(j>=wt[i]){ temp[j]=max(temp[j], val[i]+dp[j-wt[i]]); } } dp=temp; } return dp[W]; } 0 moaslam8261 week ago c++ soln int fun(int *value,int *weight,int n,int w,vector<vector<int>>&dp){ if(dp[n][w]!=-1) return dp[n][w]; if(w==0) return dp[n][w]=0; if(n==0){ if(w-weight[0]<0) return 0; else return dp[n][w]=value[0]; } if(w-weight[n]<0) return dp[n][w]=fun(value,weight,n-1,w,dp); else{ int a=INT_MIN,b=INT_MIN; a=fun(value,weight,n-1,w,dp); b=fun(value,weight,n-1,w-weight[n],dp)+value[n]; return dp[n][w]=max(a,b); } } int knapSack(int W, int wt[], int val[], int n) { // const int N=1e3+2; vector<vector<int>> dp(n+2,vector<int>(W+2,-1)); return fun(val,wt,n-1,W,dp); } 0 vinamrajha1 week ago int knapSack(int W, int wt[], int val[], int n) { // Your code here int dp[n+1][W+1]; for(int i =0; i<=n; ++i)dp[i][0] =0; for(int i =0; i<=W; ++i)dp[0][i] =0; for(int i =1; i<=n; ++i){ for(int j =1; j<=W; ++j){ if(wt[i-1]>j) dp[i][j] = dp[i-1][j]; else dp[i][j] = max(dp[i-1][j], val[i-1]+dp[i-1][j-wt[i-1]]); } } return dp[n][W]; } -2 2019011112 weeks ago int knapSack(int W, int wt[], int val[], int n) { int t[W+1]={0}; for(int i=0;i<n;i++) { for(int j=W;j>=wt[i];j--) { t[j]=max(t[j],t[j-wt[i]]+val[i]); } } return t[W]; } 0 devashishbakare2 weeks ago JAVA DP Tabulation static int knapSack(int cap, int wt[], int val[], int n) { if( n <= 0) return 0; //why we creating this space, what the reason of it? //creating this 2d array due to we have eigther pick or not pick conditon //if I pick this weight how much profit I will got after adding my profit //if not then no need,hence 2d Array //we have to store the maximum profit we can get from given capasity //each cell is representing a maximum profit we get int dp[][] = new int[n+1][cap+1]; //treavel through capcity we can store in knapsack for(int i = 1 ; i < dp.length ; i++) {//we are traversing form 1, coz zero index, means zero wt, we are not getting any value, so.. for(int j = 1 ; j < dp[0].length ; j++) { //check whether this cell has a capacity to add new weight //if yes then add it and check whether profit is maximum or not if( j >= wt[i-1]) { //current val + previous possible value; int temp = val[i-1] + dp[i-1][j - wt[i-1]]; //we have added selft weight then profit is maximum //chcek if I add my weight what the profit if(temp > dp[i-1][j]) //if profit maximize then add to this cell dp[i][j] = temp; else //we have not added self weight(val) and still profit is maximum. dp[i][j] = dp[i-1][j]; //if capcity of cell is not suffuciet to add this weight then carry the same pr }else { dp[i][j] = dp[i-1][j]; } } } return dp[n][cap]; } +1 sanketbhagat3 weeks ago SIMPEL JAVA SOLUTION class Solution { //Function to return max value that can be put in knapsack of capacity W. static int knapSack(int w, int wt[], int val[], int n) { // your code here int prev[] = new int[w+1]; for(int i=0;i<n;i++){ int curr[] = new int[w+1]; for(int j=1;j<=w;j++){ if(wt[i]<=j) curr[j] = Math.max(val[i]+prev[j-wt[i]],prev[j]); else curr[j] = prev[j]; } prev = curr; } return prev[w]; } } 0 kumarsuraj43 weeks ago Space Optimised : int knapSack(int W, int wt[], int val[], int n) { // Your code here vector<int> dp(W+1,0); for(int i=0;i<n;i++) { for(int w=W;w>=0;w--) { if(w-wt[i]>=0) dp[w] = max(dp[w],val[i] + dp[w-wt[i]]); else dp[w] = dp[w]; } } return dp[W]; } 0 09himanshusah1 month ago #JavaScript Solution class Solution { //Function to return max value that can be put in knapsack of capacity W. max(a,b){ if(a > b) return a; else return b; } knapSack(W, wt, val, n) { // code here let dp = []; for(let i = 0; i < n+1; i++) { dp[i] = []; for(let j = 0; j < W+1; j++) { if(i === 0 || j === 0) { dp[i][j] = 0; } } } for(let i = 1; i < n+1; i++) { for(let j = 1; j < W+1; j++) { if(wt[i-1] <= j) { dp[i][j] = this.max(val[i-1]+dp[i-1][j-wt[i-1]], dp[i-1][j]); } else { dp[i][j] = dp[i-1][j]; } } } return dp[n][W]; } } 0 adityagagtiwari1 month ago here is the code friends if need any help understanding anything or want to do pair-programming reply this thread. I am solving the dp section of GFG SDE Sheet. class Solution { //Function to return max value that can be put in knapsack of capacity W. static int knapSack(int W, int wt[], int val[], int n) { // your code here int[][] dp = new int[n+1][W+1]; int max = 0; for(int i=1;i<n+1;i++) { for(int j = 1 ; j<W+1;j++) { // is 0 case/we do not put it in the sack dp[i][j] = dp[i-1][j]; //if weight is lesser than current weight under consideration then there is a chance to put the ith //value in the sack. If adding this value i-1 is increasing the value then use it along with the j - wt[i]. if(j>=wt[i-1]) { int diff = j-wt[i-1]; dp[i][j] = Math.max(dp[i][j],(dp[i-1][j-wt[i-1]]+val[i-1])); } } } return dp[n][W]; } } 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": 832, "s": 238, "text": "You are given weights and values of N items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that we have only one quantity of each item.\nIn other words, given two integer arrays val[0..N-1] and wt[0..N-1] which represent values and weights associated with N items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the complete item or dont pick it (0-1 property)." }, { "code": null, "e": 843, "s": 832, "text": "Example 1:" }, { "code": null, "e": 911, "s": 843, "text": "Input:\nN = 3\nW = 4\nvalues[] = {1,2,3}\nweight[] = {4,5,1}\nOutput: 3\n" }, { "code": null, "e": 922, "s": 911, "text": "Example 2:" }, { "code": null, "e": 989, "s": 922, "text": "Input:\nN = 3\nW = 3\nvalues[] = {1,2,3}\nweight[] = {4,5,6}\nOutput: 0" }, { "code": null, "e": 1196, "s": 989, "text": "Your Task:\nComplete the function knapSack() which takes maximum capacity W, weight array wt[], value array val[], and the number of items n as a parameter and returns the maximum possible value you can get." }, { "code": null, "e": 1263, "s": 1196, "text": "Expected Time Complexity: O(N*W).\nExpected Auxiliary Space: O(N*W)" }, { "code": null, "e": 1335, "s": 1263, "text": "Constraints:\n1 ≤ N ≤ 1000\n1 ≤ W ≤ 1000\n1 ≤ wt[i] ≤ 1000\n1 ≤ v[i] ≤ 1000" }, { "code": null, "e": 1337, "s": 1335, "text": "0" }, { "code": null, "e": 1360, "s": 1337, "text": "itsmemritu14 hours ago" }, { "code": null, "e": 1864, "s": 1360, "text": "int knapSack(int W, int wt[], int val[], int n) { // Your code here int dp[n+1][W+1]; for(int i=0 ;i<n+1 ;i++){ for(int j=0 ;j<W+1 ;j++){ if(i==0 or j==0){ dp[i][j]=0; continue; } if(wt[i-1]<=j){ dp[i][j]=max( (val[i-1]+ dp[i-1][j-wt[i-1]]) , (dp[i-1][j]) ); } else{ dp[i][j]=dp[i-1][j]; } } } return dp[n][W]; }" }, { "code": null, "e": 1867, "s": 1864, "text": "+1" }, { "code": null, "e": 1890, "s": 1867, "text": "mr_coder99335 days ago" }, { "code": null, "e": 1901, "s": 1890, "text": "C++/Simple" }, { "code": null, "e": 1926, "s": 1901, "text": "Time Complexity:- O(n*W)" }, { "code": null, "e": 1950, "s": 1926, "text": "Space Complexity:- O(W)" }, { "code": null, "e": 1967, "s": 1950, "text": "Using Tabulation" }, { "code": null, "e": 2397, "s": 1967, "text": "int knapSack(int W, int wt[], int val[], int n) \n { \n vector<int> dp(W+1,0),temp(W+1);\n \n for(int i=0;i<n;i++){\n temp[0]=0;\n for(int j=1;j<=W;j++){\n temp[j]=dp[j];\n if(j>=wt[i]){\n \ttemp[j]=max(temp[j],\n val[i]+dp[j-wt[i]]);\n } \n }\n dp=temp;\n } \n return dp[W];\n }" }, { "code": null, "e": 2399, "s": 2397, "text": "0" }, { "code": null, "e": 2420, "s": 2399, "text": "moaslam8261 week ago" }, { "code": null, "e": 2429, "s": 2420, "text": "c++ soln" }, { "code": null, "e": 3061, "s": 2429, "text": "\nint fun(int *value,int *weight,int n,int w,vector<vector<int>>&dp){\nif(dp[n][w]!=-1) return dp[n][w];\n if(w==0) return dp[n][w]=0;\n if(n==0){\n \tif(w-weight[0]<0) return 0;\n \telse return dp[n][w]=value[0];\n }\n if(w-weight[n]<0)\n return dp[n][w]=fun(value,weight,n-1,w,dp);\n else{\n int a=INT_MIN,b=INT_MIN;\n a=fun(value,weight,n-1,w,dp);\n b=fun(value,weight,n-1,w-weight[n],dp)+value[n];\n return dp[n][w]=max(a,b);\n } \n}\n \n \n int knapSack(int W, int wt[], int val[], int n) \n { \n // const int N=1e3+2;\n vector<vector<int>> dp(n+2,vector<int>(W+2,-1));\n return fun(val,wt,n-1,W,dp);\n }" }, { "code": null, "e": 3063, "s": 3061, "text": "0" }, { "code": null, "e": 3084, "s": 3063, "text": "vinamrajha1 week ago" }, { "code": null, "e": 3516, "s": 3084, "text": "int knapSack(int W, int wt[], int val[], int n) \n { \n // Your code here\n int dp[n+1][W+1];\n for(int i =0; i<=n; ++i)dp[i][0] =0;\n for(int i =0; i<=W; ++i)dp[0][i] =0;\n for(int i =1; i<=n; ++i){\n for(int j =1; j<=W; ++j){\n if(wt[i-1]>j) dp[i][j] = dp[i-1][j];\n else dp[i][j] = max(dp[i-1][j], val[i-1]+dp[i-1][j-wt[i-1]]);\n }\n }\n return dp[n][W];\n }" }, { "code": null, "e": 3519, "s": 3516, "text": "-2" }, { "code": null, "e": 3540, "s": 3519, "text": "2019011112 weeks ago" }, { "code": null, "e": 3768, "s": 3540, "text": "int knapSack(int W, int wt[], int val[], int n) \n{ \n int t[W+1]={0};\n for(int i=0;i<n;i++)\n {\n for(int j=W;j>=wt[i];j--)\n {\n t[j]=max(t[j],t[j-wt[i]]+val[i]);\n }\n }\n return t[W];\n}" }, { "code": null, "e": 3770, "s": 3768, "text": "0" }, { "code": null, "e": 3797, "s": 3770, "text": "devashishbakare2 weeks ago" }, { "code": null, "e": 3816, "s": 3797, "text": "JAVA DP Tabulation" }, { "code": null, "e": 5782, "s": 3816, "text": " static int knapSack(int cap, int wt[], int val[], int n) \n { \n \n if( n <= 0)\n return 0;\n \n //why we creating this space, what the reason of it?\n //creating this 2d array due to we have eigther pick or not pick conditon \n //if I pick this weight how much profit I will got after adding my profit\n //if not then no need,hence 2d Array\n //we have to store the maximum profit we can get from given capasity\n //each cell is representing a maximum profit we get\n \n int dp[][] = new int[n+1][cap+1];\n \n //treavel through capcity we can store in knapsack\n for(int i = 1 ; i < dp.length ; i++)\n {//we are traversing form 1, coz zero index, means zero wt, we are not getting any value, so..\n for(int j = 1 ; j < dp[0].length ; j++)\n {\n \n //check whether this cell has a capacity to add new weight\n //if yes then add it and check whether profit is maximum or not\n if( j >= wt[i-1])\n {\n //current val + previous possible value;\n int temp = val[i-1] + dp[i-1][j - wt[i-1]];\n //we have added selft weight then profit is maximum\n //chcek if I add my weight what the profit \n if(temp > dp[i-1][j])\n //if profit maximize then add to this cell\n dp[i][j] = temp;\n else\n //we have not added self weight(val) and still profit is maximum.\n dp[i][j] = dp[i-1][j];\n //if capcity of cell is not suffuciet to add this weight then carry the same pr \n }else\n {\n dp[i][j] = dp[i-1][j];\n \n }\n \n }\n }\n \n return dp[n][cap];\n } " }, { "code": null, "e": 5787, "s": 5784, "text": "+1" }, { "code": null, "e": 5811, "s": 5787, "text": "sanketbhagat3 weeks ago" }, { "code": null, "e": 5832, "s": 5811, "text": "SIMPEL JAVA SOLUTION" }, { "code": null, "e": 6358, "s": 5832, "text": "class Solution { \n //Function to return max value that can be put in knapsack of capacity W.\n static int knapSack(int w, int wt[], int val[], int n) { \n // your code here \n int prev[] = new int[w+1];\n for(int i=0;i<n;i++){\n int curr[] = new int[w+1];\n for(int j=1;j<=w;j++){\n if(wt[i]<=j) curr[j] = Math.max(val[i]+prev[j-wt[i]],prev[j]);\n else curr[j] = prev[j];\n }\n prev = curr;\n }\n return prev[w];\n } \n}" }, { "code": null, "e": 6360, "s": 6358, "text": "0" }, { "code": null, "e": 6383, "s": 6360, "text": "kumarsuraj43 weeks ago" }, { "code": null, "e": 6402, "s": 6383, "text": "Space Optimised : " }, { "code": null, "e": 6792, "s": 6404, "text": "int knapSack(int W, int wt[], int val[], int n) \n { \n // Your code here\n vector<int> dp(W+1,0);\n \n for(int i=0;i<n;i++)\n {\n for(int w=W;w>=0;w--)\n {\n if(w-wt[i]>=0)\n dp[w] = max(dp[w],val[i] + dp[w-wt[i]]);\n else dp[w] = dp[w];\n }\n }\n return dp[W];\n }" }, { "code": null, "e": 6794, "s": 6792, "text": "0" }, { "code": null, "e": 6819, "s": 6794, "text": "09himanshusah1 month ago" }, { "code": null, "e": 6840, "s": 6819, "text": "#JavaScript Solution" }, { "code": null, "e": 7645, "s": 6840, "text": "class Solution \n{\n //Function to return max value that can be put in knapsack of capacity W.\n max(a,b){\n if(a > b) return a;\n else return b;\n }\n \n knapSack(W, wt, val, n)\n { \n // code here\n let dp = [];\n for(let i = 0; i < n+1; i++) {\n dp[i] = [];\n for(let j = 0; j < W+1; j++) {\n if(i === 0 || j === 0) {\n dp[i][j] = 0;\n }\n }\n }\n \n for(let i = 1; i < n+1; i++) {\n for(let j = 1; j < W+1; j++) {\n if(wt[i-1] <= j) {\n dp[i][j] = this.max(val[i-1]+dp[i-1][j-wt[i-1]], dp[i-1][j]);\n } else {\n dp[i][j] = dp[i-1][j];\n }\n }\n }\n return dp[n][W];\n }\n}" }, { "code": null, "e": 7647, "s": 7645, "text": "0" }, { "code": null, "e": 7674, "s": 7647, "text": "adityagagtiwari1 month ago" }, { "code": null, "e": 7790, "s": 7674, "text": "here is the code friends if need any help understanding anything or want to do pair-programming reply this thread. " }, { "code": null, "e": 7836, "s": 7790, "text": "I am solving the dp section of GFG SDE Sheet." }, { "code": null, "e": 8731, "s": 7836, "text": "class Solution { //Function to return max value that can be put in knapsack of capacity W. static int knapSack(int W, int wt[], int val[], int n) { // your code here int[][] dp = new int[n+1][W+1]; int max = 0; for(int i=1;i<n+1;i++) { for(int j = 1 ; j<W+1;j++) { // is 0 case/we do not put it in the sack dp[i][j] = dp[i-1][j]; //if weight is lesser than current weight under consideration then there is a chance to put the ith //value in the sack. If adding this value i-1 is increasing the value then use it along with the j - wt[i]. if(j>=wt[i-1]) { int diff = j-wt[i-1]; dp[i][j] = Math.max(dp[i][j],(dp[i-1][j-wt[i-1]]+val[i-1])); } } } return dp[n][W]; } }" }, { "code": null, "e": 8877, "s": 8731, "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": 8913, "s": 8877, "text": " Login to access your submissions. " }, { "code": null, "e": 8923, "s": 8913, "text": "\nProblem\n" }, { "code": null, "e": 8933, "s": 8923, "text": "\nContest\n" }, { "code": null, "e": 8996, "s": 8933, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9144, "s": 8996, "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": 9352, "s": 9144, "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": 9458, "s": 9352, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Count changes in Led Lights to display digits one by one - GeeksforGeeks
23 Mar, 2021 Given a number n. Count the number of changes in LED light when display one after another of a given number. (Initially all LED is off). Number is given input in the form of a string. See this image of seven segment display for better understanding.Examples: Input : n = "082" Output : 9 We need 6 LED lights to display 0 in seven segment display. We need 7 lights for 8 and 5 lights for 2. So total on/off is 6 + 1 + 2 = 9. Input : n = "12345" Output : 7 Source :Morgan Stanley Interview Set 20 The idea is to pre-compute the led lights required to display a given number. Now iterate the number and keep adding the changes. For the implementation, a basic concept of string hashing is used.Below is the implementation of above problem. C++ Java Python 3 C# PHP Javascript // CPP program to count number of on offs to// display digits of a number.#include<bits/stdc++.h>using namespace std; int countOnOff(string n){ // store the led lights required to display // a particular number. int Led[] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 5 }; int len = n.length(); // compute the change in led and keep // on adding the change int sum = Led[n[0] - '0']; for (int i = 1; i < len; i++) { sum = sum + abs(Led[n[i] - '0'] - Led[n[i - 1] - '0']); } return sum;} // Driver codeint main(){ string n = "082"; cout << countOnOff(n); return 0;} // Java program to count number of on offs to// display digits of a number.import java.io.*; class GFG{static int countOnOff(String n){ // store the led lights required to display // a particular number. int Led[] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 5 }; int len = n.length(); // compute the change in led and keep // on adding the change int sum = Led[n.charAt(0) - '0']; for (int i = 1; i < len; i++) { sum = sum + Math.abs(Led[n.charAt(i) - '0'] - Led[n.charAt(i - 1) - '0']); } return sum;} // Driver codepublic static void main(String args[]){ String n = "082"; System.out.println( countOnOff(n) );}} # Python3 program to count number of on offs to# display digits of a number. def countOnOff(n): # store the led lights required to display # a particular number. Led = [ 6, 2, 5, 5, 4, 5, 6, 3, 7, 5 ] leng = len(n) # compute the change in led and keep # on adding the change sum = Led[int(n[0]) - int('0')] for i in range(1,leng): sum = (sum + abs(Led[int(n[i]) - int('0')] - Led[int(n[i - 1]) - int('0')])) return sum #Driver codeif __name__=='__main__': n = "082" print(countOnOff(n)) # this code is contributed by# ash264 // C# program to count number of on// offs to display digits of a number.using System; class GFG{public static int countOnOff(string n){ // store the led lights required // to display a particular number. int[] Led = new int[] {6, 2, 5, 5, 4, 5, 6, 3, 7, 5}; int len = n.Length; // compute the change in led and // keep on adding the change int sum = Led[n[0] - '0']; for (int i = 1; i < len; i++) { sum = sum + Math.Abs(Led[n[i] - '0'] - Led[n[i - 1] - '0']); } return sum;} // Driver codepublic static void Main(string[] args){ string n = "082"; Console.WriteLine(countOnOff(n));}} // This code is contributed by Shrikant13 <?php// PHP program to count number// of on offs to display digits// of a number. function countOnOff($n){ // store the led lights required // to display a particular number. $Led = array(6, 2, 5, 5, 4, 5, 6, 3, 7, 5 ); $len = strlen($n); // compute the change in led // and keep on adding the change $sum = $Led[$n[0] - '0']; for ($i = 1; $i < $len; $i++) { $sum = $sum + abs($Led[$n[$i] - '0'] - $Led[$n[$i - 1] - '0']); } return $sum;} // Driver code$n = "082";echo countOnOff($n); // This code is contributed// by Akanksha Rai?> <script> // javascript program to count number of on offs to// display digits of a number.function countOnOff( n){ // store the led lights required to display // a particular number. var Led = [ 6, 2, 5, 5, 4, 5, 6, 3, 7, 5 ]; var len = n.length; // compute the change in led and keep // on adding the change var sum = Led[n.charAt(0) - '0']; for (i = 1; i < len; i++) { sum = sum + Math.abs(Led[n.charAt(i) - '0'] - Led[n.charAt(i - 1) - '0']); } return sum;} // Driver code n = "082";document.write( countOnOff(n) ); // This code is contributed by 29AjayKumar </script> 9 ash264 Krishna_Yadav shrikanth13 Akanksha_Rai 29AjayKumar Morgan Stanley programming-puzzle Technical Scripter 2018 Strings Morgan Stanley Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews Print all the duplicates in the input string Vigenère Cipher sprintf() in C Convert character array to string in C++ String class in Java | Set 1 How to Append a Character to a String in C Program to count occurrence of a given character in a string Naive algorithm for Pattern Searching Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 26097, "s": 26069, "text": "\n23 Mar, 2021" }, { "code": null, "e": 26358, "s": 26097, "text": "Given a number n. Count the number of changes in LED light when display one after another of a given number. (Initially all LED is off). Number is given input in the form of a string. See this image of seven segment display for better understanding.Examples: " }, { "code": null, "e": 26556, "s": 26358, "text": "Input : n = \"082\"\nOutput : 9\nWe need 6 LED lights to display 0 in seven segment display. We need 7 lights for 8 and 5 lights for 2. So total on/off is 6 + 1 + 2 = 9.\n\nInput : n = \"12345\"\nOutput : 7" }, { "code": null, "e": 26597, "s": 26556, "text": "Source :Morgan Stanley Interview Set 20 " }, { "code": null, "e": 26841, "s": 26597, "text": "The idea is to pre-compute the led lights required to display a given number. Now iterate the number and keep adding the changes. For the implementation, a basic concept of string hashing is used.Below is the implementation of above problem. " }, { "code": null, "e": 26845, "s": 26841, "text": "C++" }, { "code": null, "e": 26850, "s": 26845, "text": "Java" }, { "code": null, "e": 26859, "s": 26850, "text": "Python 3" }, { "code": null, "e": 26862, "s": 26859, "text": "C#" }, { "code": null, "e": 26866, "s": 26862, "text": "PHP" }, { "code": null, "e": 26877, "s": 26866, "text": "Javascript" }, { "code": "// CPP program to count number of on offs to// display digits of a number.#include<bits/stdc++.h>using namespace std; int countOnOff(string n){ // store the led lights required to display // a particular number. int Led[] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 5 }; int len = n.length(); // compute the change in led and keep // on adding the change int sum = Led[n[0] - '0']; for (int i = 1; i < len; i++) { sum = sum + abs(Led[n[i] - '0'] - Led[n[i - 1] - '0']); } return sum;} // Driver codeint main(){ string n = \"082\"; cout << countOnOff(n); return 0;}", "e": 27489, "s": 26877, "text": null }, { "code": "// Java program to count number of on offs to// display digits of a number.import java.io.*; class GFG{static int countOnOff(String n){ // store the led lights required to display // a particular number. int Led[] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 5 }; int len = n.length(); // compute the change in led and keep // on adding the change int sum = Led[n.charAt(0) - '0']; for (int i = 1; i < len; i++) { sum = sum + Math.abs(Led[n.charAt(i) - '0'] - Led[n.charAt(i - 1) - '0']); } return sum;} // Driver codepublic static void main(String args[]){ String n = \"082\"; System.out.println( countOnOff(n) );}}", "e": 28147, "s": 27489, "text": null }, { "code": "# Python3 program to count number of on offs to# display digits of a number. def countOnOff(n): # store the led lights required to display # a particular number. Led = [ 6, 2, 5, 5, 4, 5, 6, 3, 7, 5 ] leng = len(n) # compute the change in led and keep # on adding the change sum = Led[int(n[0]) - int('0')] for i in range(1,leng): sum = (sum + abs(Led[int(n[i]) - int('0')] - Led[int(n[i - 1]) - int('0')])) return sum #Driver codeif __name__=='__main__': n = \"082\" print(countOnOff(n)) # this code is contributed by# ash264", "e": 28731, "s": 28147, "text": null }, { "code": "// C# program to count number of on// offs to display digits of a number.using System; class GFG{public static int countOnOff(string n){ // store the led lights required // to display a particular number. int[] Led = new int[] {6, 2, 5, 5, 4, 5, 6, 3, 7, 5}; int len = n.Length; // compute the change in led and // keep on adding the change int sum = Led[n[0] - '0']; for (int i = 1; i < len; i++) { sum = sum + Math.Abs(Led[n[i] - '0'] - Led[n[i - 1] - '0']); } return sum;} // Driver codepublic static void Main(string[] args){ string n = \"082\"; Console.WriteLine(countOnOff(n));}} // This code is contributed by Shrikant13", "e": 29460, "s": 28731, "text": null }, { "code": "<?php// PHP program to count number// of on offs to display digits// of a number. function countOnOff($n){ // store the led lights required // to display a particular number. $Led = array(6, 2, 5, 5, 4, 5, 6, 3, 7, 5 ); $len = strlen($n); // compute the change in led // and keep on adding the change $sum = $Led[$n[0] - '0']; for ($i = 1; $i < $len; $i++) { $sum = $sum + abs($Led[$n[$i] - '0'] - $Led[$n[$i - 1] - '0']); } return $sum;} // Driver code$n = \"082\";echo countOnOff($n); // This code is contributed// by Akanksha Rai?>", "e": 30077, "s": 29460, "text": null }, { "code": "<script> // javascript program to count number of on offs to// display digits of a number.function countOnOff( n){ // store the led lights required to display // a particular number. var Led = [ 6, 2, 5, 5, 4, 5, 6, 3, 7, 5 ]; var len = n.length; // compute the change in led and keep // on adding the change var sum = Led[n.charAt(0) - '0']; for (i = 1; i < len; i++) { sum = sum + Math.abs(Led[n.charAt(i) - '0'] - Led[n.charAt(i - 1) - '0']); } return sum;} // Driver code n = \"082\";document.write( countOnOff(n) ); // This code is contributed by 29AjayKumar </script>", "e": 30701, "s": 30077, "text": null }, { "code": null, "e": 30703, "s": 30701, "text": "9" }, { "code": null, "e": 30712, "s": 30705, "text": "ash264" }, { "code": null, "e": 30726, "s": 30712, "text": "Krishna_Yadav" }, { "code": null, "e": 30738, "s": 30726, "text": "shrikanth13" }, { "code": null, "e": 30751, "s": 30738, "text": "Akanksha_Rai" }, { "code": null, "e": 30763, "s": 30751, "text": "29AjayKumar" }, { "code": null, "e": 30778, "s": 30763, "text": "Morgan Stanley" }, { "code": null, "e": 30797, "s": 30778, "text": "programming-puzzle" }, { "code": null, "e": 30821, "s": 30797, "text": "Technical Scripter 2018" }, { "code": null, "e": 30829, "s": 30821, "text": "Strings" }, { "code": null, "e": 30844, "s": 30829, "text": "Morgan Stanley" }, { "code": null, "e": 30852, "s": 30844, "text": "Strings" }, { "code": null, "e": 30950, "s": 30852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30995, "s": 30950, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 31040, "s": 30995, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 31057, "s": 31040, "text": "Vigenère Cipher" }, { "code": null, "e": 31072, "s": 31057, "text": "sprintf() in C" }, { "code": null, "e": 31113, "s": 31072, "text": "Convert character array to string in C++" }, { "code": null, "e": 31142, "s": 31113, "text": "String class in Java | Set 1" }, { "code": null, "e": 31185, "s": 31142, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 31246, "s": 31185, "text": "Program to count occurrence of a given character in a string" }, { "code": null, "e": 31284, "s": 31246, "text": "Naive algorithm for Pattern Searching" } ]
Plot Live Graphs using Python Dash and Plotly - GeeksforGeeks
16 Jul, 2020 Dash is a Python framework built on top of ReactJS, Plotly and Flask. It is used to create interactive web dashboards using just python. Live graphs are particularly necessary for certain applications such as medical tests, stock data, or basically for any kind of data that changes in a very short amount of time where it is not viable to reload each time the data is updated. This can be done using a feature called “hot reloading”, not to be confused with “live reloading”. Live reloading reloads or refreshes the entire app when the data is updated, while hot reloading only refreshes the data that was updated without changing the state of the app. Dash automatically includes hot-reloading making it the best choice for this kind of visualization. Now, let’s build a dashboard that generates random data, appends it onto a buffer at regular intervals and visualizes the same. Install Dash module and Plotly modules. pip install dash pip install plotly First, let’s import all the required modules and dependencies. Import Output and Input for callbacks, dash_core_components for graphs and other basic components offered by Dash. Import dash_html_components offers basic HTML components. Also, import dash and plotly. Import the graph_objs from plotly for graph features. Import deque(Doubly Ended Queue) from collections. import dash from dash.dependencies import Output, Input import dash_core_components as dcc import dash_html_components as html import plotly import random import plotly.graph_objs as go from collections import deque Let’s initialize two deques for X and Y components of the graph. Append single data to it, this will be our first points on the graph. X = deque(maxlen = 20) X.append(1) Y = deque(maxlen = 20) Y.append(1) Initialize the dash app. app = dash.Dash(__name__) Now let’s specify the layout of the dashboard that we want to build. It is important to note that there is no need to write HTML pages for the layout and we can use dash’s HTML components to make simple layouts. Let’s build a simple layout with just a graph component. In the code below, let’s set animate to True, this will easily handle scroll animations for the graph which would look better than an abrupt change in the values after updating. Let’s assign an id to the graph component. We have another component named Interval, which has properties like id which specifies a unique ID for this component. The property interval specifies the time elapsed between two updations of data. n_interval refers to the number of intervals completed from the start of the server. app.layout = html.Div( [ dcc.Graph(id = 'live-graph', animate = True), dcc.Interval( id = 'graph-update', interval = 1000, n_intervals = 0 ), ] ) Now let’s call the callback decorators @app.callback( Output('live-graph', 'figure'), [ Input('graph-update', 'n_intervals') ] ) Now let’s make the update_graph method which takes in n_intervals as parameter. Let’s update X values sequentially, i.e., from 1 to 2 to 3 and so on. Let’s update Y values to random values. Now let’s make a new data variable and assign it to a plotly graph. Plotly graphs, by default, requires you to set X and Y values with a list. Let’s specify the mode to “lines+markers” which essentially means that Plotly is going to plot markers first and then draw lines to it. def update_graph_scatter(n): X.append(X[-1]+1) Y.append(Y[-1]+Y[-1] * random.uniform(-0.1,0.1)) data = plotly.graph_objs.Scatter( x=list(X), y=list(Y), name='Scatter', mode= 'lines+markers' ) return {'data': [data], 'layout' : go.Layout(xaxis=dict( range=[min(X),max(X)]),yaxis = dict(range = [min(Y),max(Y)]), )} Finally, run the server. if __name__ == '__main__': app.run_server() Complete Code: Python3 import dashfrom dash.dependencies import Output, Inputimport dash_core_components as dccimport dash_html_components as htmlimport plotlyimport randomimport plotly.graph_objs as gofrom collections import deque X = deque(maxlen = 20)X.append(1) Y = deque(maxlen = 20)Y.append(1) app = dash.Dash(__name__) app.layout = html.Div( [ dcc.Graph(id = 'live-graph', animate = True), dcc.Interval( id = 'graph-update', interval = 1000, n_intervals = 0 ), ]) @app.callback( Output('live-graph', 'figure'), [ Input('graph-update', 'n_intervals') ]) def update_graph_scatter(n): X.append(X[-1]+1) Y.append(Y[-1]+Y[-1] * random.uniform(-0.1,0.1)) data = plotly.graph_objs.Scatter( x=list(X), y=list(Y), name='Scatter', mode= 'lines+markers' ) return {'data': [data], 'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]),yaxis = dict(range = [min(Y),max(Y)]),)} if __name__ == '__main__': app.run_server() Open the browser and run the app on the local host and port 8050 http://localhost:8050/ Output: This is how dash can be used for live graph visualizations. In this article, we have used it with random values generated by the computer. However, the same can be done with data pulled from APIs or a database. Python-Plotly Python-projects python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 24727, "s": 24699, "text": "\n16 Jul, 2020" }, { "code": null, "e": 25482, "s": 24727, "text": "Dash is a Python framework built on top of ReactJS, Plotly and Flask. It is used to create interactive web dashboards using just python. Live graphs are particularly necessary for certain applications such as medical tests, stock data, or basically for any kind of data that changes in a very short amount of time where it is not viable to reload each time the data is updated. This can be done using a feature called “hot reloading”, not to be confused with “live reloading”. Live reloading reloads or refreshes the entire app when the data is updated, while hot reloading only refreshes the data that was updated without changing the state of the app. Dash automatically includes hot-reloading making it the best choice for this kind of visualization. " }, { "code": null, "e": 25611, "s": 25482, "text": "Now, let’s build a dashboard that generates random data, appends it onto a buffer at regular intervals and visualizes the same. " }, { "code": null, "e": 25652, "s": 25611, "text": "Install Dash module and Plotly modules. " }, { "code": null, "e": 25689, "s": 25652, "text": "pip install dash\npip install plotly\n" }, { "code": null, "e": 26060, "s": 25689, "text": "First, let’s import all the required modules and dependencies. Import Output and Input for callbacks, dash_core_components for graphs and other basic components offered by Dash. Import dash_html_components offers basic HTML components. Also, import dash and plotly. Import the graph_objs from plotly for graph features. Import deque(Doubly Ended Queue) from collections." }, { "code": null, "e": 26276, "s": 26060, "text": "import dash\nfrom dash.dependencies import Output, Input\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly\nimport random\nimport plotly.graph_objs as go\nfrom collections import deque" }, { "code": null, "e": 26412, "s": 26276, "text": "Let’s initialize two deques for X and Y components of the graph. Append single data to it, this will be our first points on the graph. " }, { "code": null, "e": 26483, "s": 26412, "text": "X = deque(maxlen = 20)\nX.append(1)\n\nY = deque(maxlen = 20)\nY.append(1)" }, { "code": null, "e": 26508, "s": 26483, "text": "Initialize the dash app." }, { "code": null, "e": 26534, "s": 26508, "text": "app = dash.Dash(__name__)" }, { "code": null, "e": 27308, "s": 26534, "text": "Now let’s specify the layout of the dashboard that we want to build. It is important to note that there is no need to write HTML pages for the layout and we can use dash’s HTML components to make simple layouts. Let’s build a simple layout with just a graph component. In the code below, let’s set animate to True, this will easily handle scroll animations for the graph which would look better than an abrupt change in the values after updating. Let’s assign an id to the graph component. We have another component named Interval, which has properties like id which specifies a unique ID for this component. The property interval specifies the time elapsed between two updations of data. n_interval refers to the number of intervals completed from the start of the server." }, { "code": null, "e": 27544, "s": 27308, "text": "app.layout = html.Div(\n [ \n dcc.Graph(id = 'live-graph',\n animate = True),\n dcc.Interval(\n id = 'graph-update',\n interval = 1000,\n n_intervals = 0\n ),\n ]\n)" }, { "code": null, "e": 27583, "s": 27544, "text": "Now let’s call the callback decorators" }, { "code": null, "e": 27681, "s": 27583, "text": "@app.callback(\n Output('live-graph', 'figure'),\n [ Input('graph-update', 'n_intervals') ]\n)" }, { "code": null, "e": 28150, "s": 27681, "text": "Now let’s make the update_graph method which takes in n_intervals as parameter. Let’s update X values sequentially, i.e., from 1 to 2 to 3 and so on. Let’s update Y values to random values. Now let’s make a new data variable and assign it to a plotly graph. Plotly graphs, by default, requires you to set X and Y values with a list. Let’s specify the mode to “lines+markers” which essentially means that Plotly is going to plot markers first and then draw lines to it." }, { "code": null, "e": 28607, "s": 28150, "text": "def update_graph_scatter(n):\n X.append(X[-1]+1)\n Y.append(Y[-1]+Y[-1] * random.uniform(-0.1,0.1))\n\n data = plotly.graph_objs.Scatter(\n x=list(X),\n y=list(Y),\n name='Scatter',\n mode= 'lines+markers'\n )\n\n return {'data': [data],\n 'layout' : go.Layout(xaxis=dict(\n range=[min(X),max(X)]),yaxis = \n dict(range = [min(Y),max(Y)]),\n )}" }, { "code": null, "e": 28632, "s": 28607, "text": "Finally, run the server." }, { "code": null, "e": 28680, "s": 28632, "text": "if __name__ == '__main__':\n app.run_server()" }, { "code": null, "e": 28695, "s": 28680, "text": "Complete Code:" }, { "code": null, "e": 28703, "s": 28695, "text": "Python3" }, { "code": "import dashfrom dash.dependencies import Output, Inputimport dash_core_components as dccimport dash_html_components as htmlimport plotlyimport randomimport plotly.graph_objs as gofrom collections import deque X = deque(maxlen = 20)X.append(1) Y = deque(maxlen = 20)Y.append(1) app = dash.Dash(__name__) app.layout = html.Div( [ dcc.Graph(id = 'live-graph', animate = True), dcc.Interval( id = 'graph-update', interval = 1000, n_intervals = 0 ), ]) @app.callback( Output('live-graph', 'figure'), [ Input('graph-update', 'n_intervals') ]) def update_graph_scatter(n): X.append(X[-1]+1) Y.append(Y[-1]+Y[-1] * random.uniform(-0.1,0.1)) data = plotly.graph_objs.Scatter( x=list(X), y=list(Y), name='Scatter', mode= 'lines+markers' ) return {'data': [data], 'layout' : go.Layout(xaxis=dict(range=[min(X),max(X)]),yaxis = dict(range = [min(Y),max(Y)]),)} if __name__ == '__main__': app.run_server()", "e": 29746, "s": 28703, "text": null }, { "code": null, "e": 29811, "s": 29746, "text": "Open the browser and run the app on the local host and port 8050" }, { "code": null, "e": 29834, "s": 29811, "text": "http://localhost:8050/" }, { "code": null, "e": 29842, "s": 29834, "text": "Output:" }, { "code": null, "e": 30054, "s": 29842, "text": "This is how dash can be used for live graph visualizations. In this article, we have used it with random values generated by the computer. However, the same can be done with data pulled from APIs or a database. " }, { "code": null, "e": 30068, "s": 30054, "text": "Python-Plotly" }, { "code": null, "e": 30084, "s": 30068, "text": "Python-projects" }, { "code": null, "e": 30099, "s": 30084, "text": "python-utility" }, { "code": null, "e": 30106, "s": 30099, "text": "Python" }, { "code": null, "e": 30204, "s": 30106, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30232, "s": 30204, "text": "Read JSON file using Python" }, { "code": null, "e": 30282, "s": 30232, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 30304, "s": 30282, "text": "Python map() function" }, { "code": null, "e": 30348, "s": 30304, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 30366, "s": 30348, "text": "Python Dictionary" }, { "code": null, "e": 30389, "s": 30366, "text": "Taking input in Python" }, { "code": null, "e": 30424, "s": 30389, "text": "Read a file line by line in Python" }, { "code": null, "e": 30456, "s": 30424, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30478, "s": 30456, "text": "Enumerate() in Python" } ]
How to change password of superuser in Django? - GeeksforGeeks
04 Jan, 2021 Django provides us Admin Panel for it’s users to look over the database and other activities. If you dont know how to create superuser then you can refer to How to create superuser in Django? How to change password of superuser in Django? For changing password of superuser, first reach the same directory as that of manage.py and run the following command: python manage.py changepassword user_name Changing password for user ‘user_name’ Enter the Password in-front of the Password field and press enter. Enter a strong password so as to keep it secure. Password: ****** Then again enter the same Password for confirmation. Password (again): ****** This password is too short. It must contain at least 8 characters. Enter the Password again in-front of the Password field and press enter. Enter a strong password and at least of 8 characters so as to keep it secure. Password: ******** Password (again): ******** Password changed successfully for user ‘user_name’. Python Django Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Pandas dataframe.groupby() Create a directory in Python Defaultdict in Python Python | Get unique values from a list
[ { "code": null, "e": 25673, "s": 25645, "text": "\n04 Jan, 2021" }, { "code": null, "e": 25865, "s": 25673, "text": "Django provides us Admin Panel for it’s users to look over the database and other activities. If you dont know how to create superuser then you can refer to How to create superuser in Django?" }, { "code": null, "e": 25912, "s": 25865, "text": "How to change password of superuser in Django?" }, { "code": null, "e": 26031, "s": 25912, "text": "For changing password of superuser, first reach the same directory as that of manage.py and run the following command:" }, { "code": null, "e": 26073, "s": 26031, "text": "python manage.py changepassword user_name" }, { "code": null, "e": 26112, "s": 26073, "text": "Changing password for user ‘user_name’" }, { "code": null, "e": 26228, "s": 26112, "text": "Enter the Password in-front of the Password field and press enter. Enter a strong password so as to keep it secure." }, { "code": null, "e": 26245, "s": 26228, "text": "Password: ******" }, { "code": null, "e": 26298, "s": 26245, "text": "Then again enter the same Password for confirmation." }, { "code": null, "e": 26323, "s": 26298, "text": "Password (again): ******" }, { "code": null, "e": 26390, "s": 26323, "text": "This password is too short. It must contain at least 8 characters." }, { "code": null, "e": 26541, "s": 26390, "text": "Enter the Password again in-front of the Password field and press enter. Enter a strong password and at least of 8 characters so as to keep it secure." }, { "code": null, "e": 26560, "s": 26541, "text": "Password: ********" }, { "code": null, "e": 26587, "s": 26560, "text": "Password (again): ********" }, { "code": null, "e": 26639, "s": 26587, "text": "Password changed successfully for user ‘user_name’." }, { "code": null, "e": 26653, "s": 26639, "text": "Python Django" }, { "code": null, "e": 26677, "s": 26653, "text": "Technical Scripter 2020" }, { "code": null, "e": 26684, "s": 26677, "text": "Python" }, { "code": null, "e": 26703, "s": 26684, "text": "Technical Scripter" }, { "code": null, "e": 26801, "s": 26703, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26833, "s": 26801, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26875, "s": 26833, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26917, "s": 26875, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26973, "s": 26917, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27000, "s": 26973, "text": "Python Classes and Objects" }, { "code": null, "e": 27031, "s": 27000, "text": "Python | os.path.join() method" }, { "code": null, "e": 27067, "s": 27031, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27096, "s": 27067, "text": "Create a directory in Python" }, { "code": null, "e": 27118, "s": 27096, "text": "Defaultdict in Python" } ]
jQuery UI Buttonset enable() Method - GeeksforGeeks
07 Jan, 2022 jQuery UI consists of GUI widgets, visual effects, and themes implemented using HTML, CSS, and jQuery. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI buttonset widget is used to give a visual grouping for a group of related buttons. The jQuery UI buttonset enable() method is used for enabling the buttonset widget. Syntax: $( ".selector" ).buttonset( "enable" ); Parameters: This method does not accept any parameter. Return values: This method does not return any values. CDN Link: First, add jQuery UI scripts needed for your project. <link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script> Example: This example demonstrates the jQuery UI buttonset enable() Method. HTML <!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.12.4.js"> </script> <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"> </script></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h3>jQuery UI Buttonset enable() method</h3> <form> <fieldset> <legend>Button_Set</legend> <div id="ButtonSet_Radio"> <input id="Company" type="radio" checked="checked"> <label for="Company">GeeksforGeeks</label> <input id="Department" type="radio"> <label for="Department">Computer Science</label> </div> </fieldset> </form> <input type="button" id="Button_for_enable" style="padding:5px 15px; margin-top:40px;" value="Enable the Widget"> </center> <script> $(document).ready(function () { $("#ButtonSet_Radio").buttonset({ disabled: true }); $("#ButtonSet_Radio").buttonset("option", "disabled", true); $("#Button_for_enable").on('click', function () { $("#ButtonSet_Radio").buttonset("enable"); }); }); </script></body></html> Output: Reference: https://api.jqueryui.com/buttonset/#method-enable jQuery-UI jQuery-UI-Buttonset JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? 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": 27144, "s": 27116, "text": "\n07 Jan, 2022" }, { "code": null, "e": 27408, "s": 27144, "text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using HTML, CSS, and jQuery. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI buttonset widget is used to give a visual grouping for a group of related buttons." }, { "code": null, "e": 27491, "s": 27408, "text": "The jQuery UI buttonset enable() method is used for enabling the buttonset widget." }, { "code": null, "e": 27499, "s": 27491, "text": "Syntax:" }, { "code": null, "e": 27539, "s": 27499, "text": "$( \".selector\" ).buttonset( \"enable\" );" }, { "code": null, "e": 27594, "s": 27539, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 27649, "s": 27594, "text": "Return values: This method does not return any values." }, { "code": null, "e": 27713, "s": 27649, "text": "CDN Link: First, add jQuery UI scripts needed for your project." }, { "code": null, "e": 27926, "s": 27713, "text": "<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>" }, { "code": null, "e": 28002, "s": 27926, "text": "Example: This example demonstrates the jQuery UI buttonset enable() Method." }, { "code": null, "e": 28007, "s": 28002, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css\"> <script src=\"//code.jquery.com/jquery-1.12.4.js\"> </script> <script src=\"//code.jquery.com/ui/1.12.1/jquery-ui.js\"> </script></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3>jQuery UI Buttonset enable() method</h3> <form> <fieldset> <legend>Button_Set</legend> <div id=\"ButtonSet_Radio\"> <input id=\"Company\" type=\"radio\" checked=\"checked\"> <label for=\"Company\">GeeksforGeeks</label> <input id=\"Department\" type=\"radio\"> <label for=\"Department\">Computer Science</label> </div> </fieldset> </form> <input type=\"button\" id=\"Button_for_enable\" style=\"padding:5px 15px; margin-top:40px;\" value=\"Enable the Widget\"> </center> <script> $(document).ready(function () { $(\"#ButtonSet_Radio\").buttonset({ disabled: true }); $(\"#ButtonSet_Radio\").buttonset(\"option\", \"disabled\", true); $(\"#Button_for_enable\").on('click', function () { $(\"#ButtonSet_Radio\").buttonset(\"enable\"); }); }); </script></body></html>", "e": 29468, "s": 28007, "text": null }, { "code": null, "e": 29476, "s": 29468, "text": "Output:" }, { "code": null, "e": 29537, "s": 29476, "text": "Reference: https://api.jqueryui.com/buttonset/#method-enable" }, { "code": null, "e": 29547, "s": 29537, "text": "jQuery-UI" }, { "code": null, "e": 29567, "s": 29547, "text": "jQuery-UI-Buttonset" }, { "code": null, "e": 29574, "s": 29567, "text": "JQuery" }, { "code": null, "e": 29591, "s": 29574, "text": "Web Technologies" }, { "code": null, "e": 29689, "s": 29591, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29744, "s": 29689, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 29817, "s": 29744, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 29840, "s": 29817, "text": "jQuery | ajax() Method" }, { "code": null, "e": 29876, "s": 29840, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 29933, "s": 29876, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 29973, "s": 29933, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30006, "s": 29973, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30051, "s": 30006, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30094, "s": 30051, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Convert Hexadecimal to Decimal?
Whereas Hexadecimal number is one of the number systems which has value is 16 and it has only 16 symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and A, B, C, D, E, F. Where A, B, C, D, E and F are single bit representations of decimal value 10, 11, 12, 13, 14 and 15 respectively. Whereas Decimal system is most familiar number system to the general public. It is base 10 which has only 10 symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. There are various indirect or direct methods to convert a hexadecimal number into decimal number. In an indirect method, you need to convert a hexadecimal number into binary or octal number, then you can convert it into decimal number. Example − Convert hexadecimal number F1 into decimal number. First convert it into binary or octal number, = (F1)16 = (1111 0001)2 or (011 110 001)2 Because in binary, value of F and 1 are 1111 and 0001 respectively. Then convert it into decimal number multiplying power of its position of base. = (1x27+1x26+1x25+1x24+0x23+0x22+0x21+1x20)10 or (3 6 1)8 = (1x27+1x26+1x25+1x24+0x23+0x22+0x21+1x20)10 or (3x82+6x81+1x80)10 = (241)10 However, there is a simple direct method to convert a hexadecimal number to decimal number. Since, there are only 16 digits (from 0 to 7 and A to F) in hexadecimal number system, so we can represent any digit of hexadecimal number system using only 4 bit as following below. Hexadecimal number system provides convenient way of converting large binary numbers into more compact and smaller groups. These are weights of hexadecimal of respective position of hexadecimal (value of base is 16). Since number numbers are type of positional number system. That means weight of the positions from right to left are as 160, 161, 162, 163and so on. for the integer part and weight of the positions from left to right are as 16-1, 16-2, 16-3and so on. for the fractional part. You can directly convert a hexadecimal number into decimal number using reverse method of decimal to hexadecimal number. Assume any unsigned hexadecimal number is hnh(n-1) ... h1h0.h-1h-2 ... h(m-1)hm. Then the decimal number is equal to the sum of hexadecimal digits (hn) times their power of 16 (16n), i.e., = hnh(n-1) ... h1h0.h-1h-2 ... h(m-1)hm = hnx16n+h(n-1)x16(n-1)+ ... +h1x161+h0x160+h-1x16-1+h-2x16-2+ ... +h(m-1)x16-(m-1)+h-mx16-m This is simple algorithm where you have to multiply positional value of binary with their digit and get the sum of these steps. Example-1 − Convert hexadecimal number ABCDEF into decimal number. Since value of Symbols − A, B, C, D, E, F are 10, 11, 12, 13, 14, 15 respectively. Therefore equivalent decimal number is, = (ABCDEF)16 = (10x165+11x164+12x163+13x162+14x161+15x160)10 = (10485760+720896+49152+3328+224+15)10 = (11259375)10 which is answer. Example-2 − Convert hexadecimal number 1F.01B into decimal number. Since value of Symbols: B and F are 11 and 15 respectively. Therefore equivalent decimal number is, = (1F.01B)16 = (1x161+15x160 +0x16-1+1x16-2+11x16-3)10 = (31.0065918)10 which is answer.
[ { "code": null, "e": 1484, "s": 1062, "text": "Whereas Hexadecimal number is one of the number systems which has value is 16 and it has only 16 symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and A, B, C, D, E, F. Where A, B, C, D, E and F are single bit representations of decimal value 10, 11, 12, 13, 14 and 15 respectively. Whereas Decimal system is most familiar number system to the general public. It is base 10 which has only 10 symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9." }, { "code": null, "e": 1720, "s": 1484, "text": "There are various indirect or direct methods to convert a hexadecimal number into decimal number. In an indirect method, you need to convert a hexadecimal number into binary or octal number, then you can convert it into decimal number." }, { "code": null, "e": 1781, "s": 1720, "text": "Example − Convert hexadecimal number F1 into decimal number." }, { "code": null, "e": 2153, "s": 1781, "text": "First convert it into binary or octal number,\n= (F1)16\n= (1111 0001)2 or (011 110 001)2\nBecause in binary, value of F and 1 are 1111 and 0001 respectively. Then convert it into decimal number multiplying power of its position of base.\n= (1x27+1x26+1x25+1x24+0x23+0x22+0x21+1x20)10\nor (3 6 1)8\n\n= (1x27+1x26+1x25+1x24+0x23+0x22+0x21+1x20)10 or (3x82+6x81+1x80)10\n= (241)10" }, { "code": null, "e": 2430, "s": 2155, "text": "However, there is a simple direct method to convert a hexadecimal number to decimal number. Since, there are only 16 digits (from 0 to 7 and A to F) in hexadecimal number system, so we can represent any digit of hexadecimal number system using only 4 bit as following below." }, { "code": null, "e": 2647, "s": 2430, "text": "Hexadecimal number system provides convenient way of converting large binary numbers into more compact and smaller groups. These are weights of hexadecimal of respective position of hexadecimal (value of base is 16)." }, { "code": null, "e": 2923, "s": 2647, "text": "Since number numbers are type of positional number system. That means weight of the positions from right to left are as 160, 161, 162, 163and so on. for the integer part and weight of the positions from left to right are as 16-1, 16-2, 16-3and so on. for the fractional part." }, { "code": null, "e": 3044, "s": 2923, "text": "You can directly convert a hexadecimal number into decimal number using reverse method of decimal to hexadecimal number." }, { "code": null, "e": 3233, "s": 3044, "text": "Assume any unsigned hexadecimal number is hnh(n-1) ... h1h0.h-1h-2 ... h(m-1)hm. Then the decimal number is equal to the sum of hexadecimal digits (hn) times their power of 16 (16n), i.e.," }, { "code": null, "e": 3273, "s": 3233, "text": "= hnh(n-1) ... h1h0.h-1h-2 ... h(m-1)hm" }, { "code": null, "e": 3366, "s": 3273, "text": "= hnx16n+h(n-1)x16(n-1)+ ... +h1x161+h0x160+h-1x16-1+h-2x16-2+ ... +h(m-1)x16-(m-1)+h-mx16-m" }, { "code": null, "e": 3494, "s": 3366, "text": "This is simple algorithm where you have to multiply positional value of binary with their digit and get the sum of these steps." }, { "code": null, "e": 3561, "s": 3494, "text": "Example-1 − Convert hexadecimal number ABCDEF into decimal number." }, { "code": null, "e": 3684, "s": 3561, "text": "Since value of Symbols − A, B, C, D, E, F are 10, 11, 12, 13, 14, 15 respectively. Therefore equivalent decimal number is," }, { "code": null, "e": 3818, "s": 3684, "text": "= (ABCDEF)16\n= (10x165+11x164+12x163+13x162+14x161+15x160)10\n\n= (10485760+720896+49152+3328+224+15)10\n= (11259375)10 which is answer." }, { "code": null, "e": 3887, "s": 3820, "text": "Example-2 − Convert hexadecimal number 1F.01B into decimal number." }, { "code": null, "e": 3987, "s": 3887, "text": "Since value of Symbols: B and F are 11 and 15 respectively. Therefore equivalent decimal number is," }, { "code": null, "e": 4076, "s": 3987, "text": "= (1F.01B)16\n= (1x161+15x160 +0x16-1+1x16-2+11x16-3)10\n= (31.0065918)10 which is answer." } ]
Lambda expression in C++
C++ STL includes useful generic functions like std::for_each. Unfortunately they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function. So this function that you'll create will be in that namespace just being used at that one place. The solution to this is using anonymous functions. C++ has introduced lambda expressions in C++11 to allow creating anonymous function. For example, Live Demo #include<iostream> #include<vector> #include <algorithm> // for_each using namespace std; int main() { vector<int> myvector; myvector.push_back(1); myvector.push_back(2); myvector.push_back(3); for_each(myvector.begin(), myvector.end(), [](int x) { cout << x*x << endl; }); } 1 4 9 The (int x) is used to define the arguments that the lambda expression would be called with. The [] are used to pass variables from the local scope to the inner scope of the lambda, this is called capturing variables. These expressions if simple, can auto deduce their types. You can also explicitly provide type information using the following syntax [](int x) -> double { return x/2.0; }
[ { "code": null, "e": 1418, "s": 1062, "text": "C++ STL includes useful generic functions like std::for_each. Unfortunately they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function. So this function that you'll create will be in that namespace just being used at that one place. The solution to this is using anonymous functions." }, { "code": null, "e": 1516, "s": 1418, "text": "C++ has introduced lambda expressions in C++11 to allow creating anonymous function. For example," }, { "code": null, "e": 1527, "s": 1516, "text": " Live Demo" }, { "code": null, "e": 1827, "s": 1527, "text": "#include<iostream>\n#include<vector>\n#include <algorithm> // for_each\nusing namespace std;\nint main() {\n vector<int> myvector;\n myvector.push_back(1);\n myvector.push_back(2);\n myvector.push_back(3);\n for_each(myvector.begin(), myvector.end(), [](int x) {\n cout << x*x << endl;\n });\n}" }, { "code": null, "e": 1833, "s": 1827, "text": "1\n4\n9" }, { "code": null, "e": 2185, "s": 1833, "text": "The (int x) is used to define the arguments that the lambda expression would be called with. The [] are used to pass variables from the local scope to the inner scope of the lambda, this is called capturing variables. These expressions if simple, can auto deduce their types. You can also explicitly provide type information using the following syntax" }, { "code": null, "e": 2226, "s": 2185, "text": "[](int x) -> double {\n return x/2.0;\n}" } ]
COVID-19 Data Collection: A Python & API Story. | by Somesh Routray | Towards Data Science
This context will be a brief discussion on the collection of data from an API using python. The agenda for this will be as below. Connect to API using pythonParse the data collected into a CSV formatA little touch of Python Pandas Connect to API using python Parse the data collected into a CSV format A little touch of Python Pandas API- Application Programming Interface: Pretend you want to use other website data for your program. You have different options to do that. You can scrape the website using BeautifulSoup and Scrapy or you can use an interface that will help you to talk with your program. That interface is API. More elaborately if I say if the website has API, you can connect your connect application to the internet and it will send data to the server. Then the server retrieves the data and performs certain actions according to your application. This happens primarily through the API The modern APIs have layers of security features. When your application sends a request to the server and when the target website sends a response, they never fully exposed to the internet. Either of the communication happens with small packets of data and the information shared just as per the requirement. This is so trusted that many big companies get revenues through APIs. Below are a few points about why APIs are helpful. The modern APIs follow the standards of HTTP and REST, developer-friendly kinds of stuff.These are more than a piece of code and built for consumption by a specific audience.The building of an API follows proper security, governance. It is developed in an SDLC and monitored thoroughly. The modern APIs follow the standards of HTTP and REST, developer-friendly kinds of stuff. These are more than a piece of code and built for consumption by a specific audience. The building of an API follows proper security, governance. It is developed in an SDLC and monitored thoroughly. This blog is dedicated to connecting one API using python and along with I will let you know some of the techniques of Pandas library as well. Here I will be using COVID-19 API. You can get that API from the rapid-api website. These guys are doing a great job in making different API. I will recommend visiting the website or you can make an API for your own use. The good thing about this website is, you can get a sample code in different programming languages. Prerequisites: local development environment for python 3API URL and key local development environment for python 3 API URL and key here Key is used as first security to identify that the requested data is genuine. It is used to prevent unethical use of APIs. Let’s get started with the coding. Step1 -Import these necessary libraries import json import pandas as pdimport requests Step2- Get API URL and Key and send a request url = “your url"headers = { ‘x-rapidapi-host’: “api host”, ‘x-rapidapi-key’: “api token” }response = requests.request("GET", url, headers=headers)print(response) if the response is 200 means request success. Generally, API has documentation regarding API details and its purpose. Some API services have API wrappers that need to be installed in your PC to access API. The APIs may have the data in JSON, XML or any custom format. To parse data you can use different libraries in python. The request and response headers often include request headers and a key. This is the current information about your use of the API service. Voila !!! you got the results. But the data I got is like a nested JSON structure of data. Let’s process it further. Step3- Parse the JSON data parsed_data = json.loads(response.text)print(parsed_data) JSON data seems more organized. But these are still in nested form. Let’s flatten this JSON def flatten_json(json): dict1 = {} def flatten(i, name=’’): if type(i) is dict: for a in i: flatten(i[a], name + a + ‘_’) else: dict1[name[:-1]] = i flatten(json) return dict1df = pd.DataFrame.from_dict(flatten_json(parsed_data), orient=’index’) flatten_json() will help you to make the nested json in a single json structure. This JSON is easy to convert to a DataFrame. The csv format data you get there is one column with numerical values. The alphabetical data you are seeing there is actually the index. Let's apply some Pandas techniques in the dataset State-wise confirmed cases State-wise confirmed cases states = [‘Andhra Pradesh’,’Arunachal Pradesh’, ‘Assam’, ‘Bihar’, ‘Chhattisgarh’, ‘Goa’, ‘Gujarat’, ‘Haryana’, ‘Himachal Pradesh’, ‘Jharkhand’, ‘Karnataka’, ‘Kerala’, ‘Madhya Pradesh’, ‘Maharashtra’, ‘Manipur’, ‘Meghalaya’, ‘Mizoram’, ‘Nagaland’, ‘Odisha’, ‘Punjab’, ‘Rajasthan’, ‘Sikkim’, ‘Tamil Nadu’, ‘Telangana’, ‘Tripura’, ‘Uttar Pradesh’, ‘Uttarakhand’, ‘West Bengal’, ‘Andaman and Nicobar Islands’, ‘Chandigarh’, ‘Dadra and Nagar Haveli’, ‘Daman and Diu’, ‘Delhi’, ‘Lakshadweep’, ‘Puducherry’, ‘Jammu and Kashmir’, ‘Ladakh’]list1 = []list2 = []for i in states: list1.append(df.at[‘state_wise_{}_confirmed’.format(i), 0]) list2.append(i)df1 = pd.DataFrame(list(zip(list2,list1)), columns=[‘state’,’state_value’]) This will help you to get confirmed case details according to states 2.reset_index() df.reset_index() Here index is changed. The previous index in the DataFrame has been converted to a column. 3. df.rename()- rename the column names df = df.rename(columns={“index”: “Statewise_details”, 0 : “Values”}) 4. at[] print(df.at[4,’Statewise_details’],”:”,df.at[4,’Values’]) at[] helps you to access the cell values whenever you require. The output is as below total_values_deltaconfirmed : 1370 5. Create separate data frames for cured, recovered, deaths and confirmed case according to states and merge it If you extend the logic of case-1(State-wise confirmed cases), you will end up with the below results You can perform different operations using pandas. Later you can visualize the data using matplotlib, seaborn and many other libraries and tools. This blog is a way of collecting data that has been continuously generating in a server. Soon I will be back with another story of web scraping. I hope you have enjoyed the Natural Language Processing Part-I & Part-2. Follow me up at Medium or Subscribe to my blogs to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @RoutraySomesh.
[ { "code": null, "e": 302, "s": 172, "text": "This context will be a brief discussion on the collection of data from an API using python. The agenda for this will be as below." }, { "code": null, "e": 403, "s": 302, "text": "Connect to API using pythonParse the data collected into a CSV formatA little touch of Python Pandas" }, { "code": null, "e": 431, "s": 403, "text": "Connect to API using python" }, { "code": null, "e": 474, "s": 431, "text": "Parse the data collected into a CSV format" }, { "code": null, "e": 506, "s": 474, "text": "A little touch of Python Pandas" }, { "code": null, "e": 546, "s": 506, "text": "API- Application Programming Interface:" }, { "code": null, "e": 801, "s": 546, "text": "Pretend you want to use other website data for your program. You have different options to do that. You can scrape the website using BeautifulSoup and Scrapy or you can use an interface that will help you to talk with your program. That interface is API." }, { "code": null, "e": 1079, "s": 801, "text": "More elaborately if I say if the website has API, you can connect your connect application to the internet and it will send data to the server. Then the server retrieves the data and performs certain actions according to your application. This happens primarily through the API" }, { "code": null, "e": 1509, "s": 1079, "text": "The modern APIs have layers of security features. When your application sends a request to the server and when the target website sends a response, they never fully exposed to the internet. Either of the communication happens with small packets of data and the information shared just as per the requirement. This is so trusted that many big companies get revenues through APIs. Below are a few points about why APIs are helpful." }, { "code": null, "e": 1796, "s": 1509, "text": "The modern APIs follow the standards of HTTP and REST, developer-friendly kinds of stuff.These are more than a piece of code and built for consumption by a specific audience.The building of an API follows proper security, governance. It is developed in an SDLC and monitored thoroughly." }, { "code": null, "e": 1886, "s": 1796, "text": "The modern APIs follow the standards of HTTP and REST, developer-friendly kinds of stuff." }, { "code": null, "e": 1972, "s": 1886, "text": "These are more than a piece of code and built for consumption by a specific audience." }, { "code": null, "e": 2085, "s": 1972, "text": "The building of an API follows proper security, governance. It is developed in an SDLC and monitored thoroughly." }, { "code": null, "e": 2549, "s": 2085, "text": "This blog is dedicated to connecting one API using python and along with I will let you know some of the techniques of Pandas library as well. Here I will be using COVID-19 API. You can get that API from the rapid-api website. These guys are doing a great job in making different API. I will recommend visiting the website or you can make an API for your own use. The good thing about this website is, you can get a sample code in different programming languages." }, { "code": null, "e": 2564, "s": 2549, "text": "Prerequisites:" }, { "code": null, "e": 2622, "s": 2564, "text": "local development environment for python 3API URL and key" }, { "code": null, "e": 2665, "s": 2622, "text": "local development environment for python 3" }, { "code": null, "e": 2681, "s": 2665, "text": "API URL and key" }, { "code": null, "e": 2809, "s": 2681, "text": "here Key is used as first security to identify that the requested data is genuine. It is used to prevent unethical use of APIs." }, { "code": null, "e": 2844, "s": 2809, "text": "Let’s get started with the coding." }, { "code": null, "e": 2884, "s": 2844, "text": "Step1 -Import these necessary libraries" }, { "code": null, "e": 2931, "s": 2884, "text": "import json import pandas as pdimport requests" }, { "code": null, "e": 2977, "s": 2931, "text": "Step2- Get API URL and Key and send a request" }, { "code": null, "e": 3139, "s": 2977, "text": "url = “your url\"headers = { ‘x-rapidapi-host’: “api host”, ‘x-rapidapi-key’: “api token” }response = requests.request(\"GET\", url, headers=headers)print(response)" }, { "code": null, "e": 3185, "s": 3139, "text": "if the response is 200 means request success." }, { "code": null, "e": 3345, "s": 3185, "text": "Generally, API has documentation regarding API details and its purpose. Some API services have API wrappers that need to be installed in your PC to access API." }, { "code": null, "e": 3605, "s": 3345, "text": "The APIs may have the data in JSON, XML or any custom format. To parse data you can use different libraries in python. The request and response headers often include request headers and a key. This is the current information about your use of the API service." }, { "code": null, "e": 3636, "s": 3605, "text": "Voila !!! you got the results." }, { "code": null, "e": 3722, "s": 3636, "text": "But the data I got is like a nested JSON structure of data. Let’s process it further." }, { "code": null, "e": 3749, "s": 3722, "text": "Step3- Parse the JSON data" }, { "code": null, "e": 3807, "s": 3749, "text": "parsed_data = json.loads(response.text)print(parsed_data)" }, { "code": null, "e": 3899, "s": 3807, "text": "JSON data seems more organized. But these are still in nested form. Let’s flatten this JSON" }, { "code": null, "e": 4191, "s": 3899, "text": "def flatten_json(json): dict1 = {} def flatten(i, name=’’): if type(i) is dict: for a in i: flatten(i[a], name + a + ‘_’) else: dict1[name[:-1]] = i flatten(json) return dict1df = pd.DataFrame.from_dict(flatten_json(parsed_data), orient=’index’)" }, { "code": null, "e": 4272, "s": 4191, "text": "flatten_json() will help you to make the nested json in a single json structure." }, { "code": null, "e": 4454, "s": 4272, "text": "This JSON is easy to convert to a DataFrame. The csv format data you get there is one column with numerical values. The alphabetical data you are seeing there is actually the index." }, { "code": null, "e": 4504, "s": 4454, "text": "Let's apply some Pandas techniques in the dataset" }, { "code": null, "e": 4531, "s": 4504, "text": "State-wise confirmed cases" }, { "code": null, "e": 4558, "s": 4531, "text": "State-wise confirmed cases" }, { "code": null, "e": 5277, "s": 4558, "text": "states = [‘Andhra Pradesh’,’Arunachal Pradesh’, ‘Assam’, ‘Bihar’, ‘Chhattisgarh’, ‘Goa’, ‘Gujarat’, ‘Haryana’, ‘Himachal Pradesh’, ‘Jharkhand’, ‘Karnataka’, ‘Kerala’, ‘Madhya Pradesh’, ‘Maharashtra’, ‘Manipur’, ‘Meghalaya’, ‘Mizoram’, ‘Nagaland’, ‘Odisha’, ‘Punjab’, ‘Rajasthan’, ‘Sikkim’, ‘Tamil Nadu’, ‘Telangana’, ‘Tripura’, ‘Uttar Pradesh’, ‘Uttarakhand’, ‘West Bengal’, ‘Andaman and Nicobar Islands’, ‘Chandigarh’, ‘Dadra and Nagar Haveli’, ‘Daman and Diu’, ‘Delhi’, ‘Lakshadweep’, ‘Puducherry’, ‘Jammu and Kashmir’, ‘Ladakh’]list1 = []list2 = []for i in states: list1.append(df.at[‘state_wise_{}_confirmed’.format(i), 0]) list2.append(i)df1 = pd.DataFrame(list(zip(list2,list1)), columns=[‘state’,’state_value’])" }, { "code": null, "e": 5346, "s": 5277, "text": "This will help you to get confirmed case details according to states" }, { "code": null, "e": 5362, "s": 5346, "text": "2.reset_index()" }, { "code": null, "e": 5379, "s": 5362, "text": "df.reset_index()" }, { "code": null, "e": 5470, "s": 5379, "text": "Here index is changed. The previous index in the DataFrame has been converted to a column." }, { "code": null, "e": 5510, "s": 5470, "text": "3. df.rename()- rename the column names" }, { "code": null, "e": 5579, "s": 5510, "text": "df = df.rename(columns={“index”: “Statewise_details”, 0 : “Values”})" }, { "code": null, "e": 5587, "s": 5579, "text": "4. at[]" }, { "code": null, "e": 5645, "s": 5587, "text": "print(df.at[4,’Statewise_details’],”:”,df.at[4,’Values’])" }, { "code": null, "e": 5731, "s": 5645, "text": "at[] helps you to access the cell values whenever you require. The output is as below" }, { "code": null, "e": 5766, "s": 5731, "text": "total_values_deltaconfirmed : 1370" }, { "code": null, "e": 5878, "s": 5766, "text": "5. Create separate data frames for cured, recovered, deaths and confirmed case according to states and merge it" }, { "code": null, "e": 5980, "s": 5878, "text": "If you extend the logic of case-1(State-wise confirmed cases), you will end up with the below results" }, { "code": null, "e": 6126, "s": 5980, "text": "You can perform different operations using pandas. Later you can visualize the data using matplotlib, seaborn and many other libraries and tools." }, { "code": null, "e": 6271, "s": 6126, "text": "This blog is a way of collecting data that has been continuously generating in a server. Soon I will be back with another story of web scraping." } ]
Impala - Truncate a Table
The Truncate Table Statement of Impala is used to remove all the records from an existing table. You can also use DROP TABLE command to delete a complete table, but it would remove the complete table structure from the database and you would need to re-create this table once again if you wish you store some data. Following is the syntax of the truncate table statement. truncate table_name; Suppose, we have a table named customers in Impala, and if you verify its contents, you are getting the following result. This means that the customers table contains 6 records. [quickstart.cloudera:21000] > select * from customers; Query: select * from customers +----+----------+-----+-----------+--------+--------+ | id | name | age | address | salary | e_mail | +----+----------+-----+-----------+--------+--------+ | 1 | Ramesh | 32 | Ahmedabad | 20000 | NULL | | 2 | Khilan | 25 | Delhi | 15000 | NULL | | 3 | kaushik | 23 | Kota | 30000 | NULL | | 4 | Chaitali | 25 | Mumbai | 35000 | NULL | | 5 | Hardik | 27 | Bhopal | 40000 | NULL | | 6 | Komal | 22 | MP | 32000 | NULL | +----+----------+-----+-----------+--------+--------+ Following is an example of truncating a table in Impala using truncate statement. Here we are removing all the records of the table named customers. [quickstart.cloudera:21000] > truncate customers; On executing the above statement, Impala deletes all the records of the specified table, displaying the following message. Query: truncate customers Fetched 0 row(s) in 0.37s If you verify the contents of the customers table, after the delete operation, using select statement, you will get an empty row as shown below. [quickstart.cloudera:21000] > select * from customers; Query: select * from customers Fetched 0 row(s) in 0.12s Open Impala Query editor and type the truncate Statement in it. And click on the execute button as shown in the following screenshot. After executing the query/statement, all the records from the table are deleted. Print Add Notes Bookmark this page
[ { "code": null, "e": 2382, "s": 2285, "text": "The Truncate Table Statement of Impala is used to remove all the records from an existing table." }, { "code": null, "e": 2600, "s": 2382, "text": "You can also use DROP TABLE command to delete a complete table, but it would remove the complete table structure from the database and you would need to re-create this table once again if you wish you store some data." }, { "code": null, "e": 2657, "s": 2600, "text": "Following is the syntax of the truncate table statement." }, { "code": null, "e": 2679, "s": 2657, "text": "truncate table_name;\n" }, { "code": null, "e": 2857, "s": 2679, "text": "Suppose, we have a table named customers in Impala, and if you verify its contents, you are getting the following result. This means that the customers table contains 6 records." }, { "code": null, "e": 3494, "s": 2857, "text": "[quickstart.cloudera:21000] > select * from customers; \n\nQuery: select * from customers \n+----+----------+-----+-----------+--------+--------+ \n| id | name | age | address | salary | e_mail | \n+----+----------+-----+-----------+--------+--------+\n| 1 | Ramesh | 32 | Ahmedabad | 20000 | NULL | \n| 2 | Khilan | 25 | Delhi | 15000 | NULL | \n| 3 | kaushik | 23 | Kota | 30000 | NULL |\n| 4 | Chaitali | 25 | Mumbai | 35000 | NULL | \n| 5 | Hardik | 27 | Bhopal | 40000 | NULL | \n| 6 | Komal | 22 | MP | 32000 | NULL | \n+----+----------+-----+-----------+--------+--------+\n" }, { "code": null, "e": 3643, "s": 3494, "text": "Following is an example of truncating a table in Impala using truncate statement. Here we are removing all the records of the table named customers." }, { "code": null, "e": 3694, "s": 3643, "text": "[quickstart.cloudera:21000] > truncate customers;\n" }, { "code": null, "e": 3817, "s": 3694, "text": "On executing the above statement, Impala deletes all the records of the specified table, displaying the following message." }, { "code": null, "e": 3872, "s": 3817, "text": "Query: truncate customers \n\nFetched 0 row(s) in 0.37s\n" }, { "code": null, "e": 4017, "s": 3872, "text": "If you verify the contents of the customers table, after the delete operation, using select statement, you will get an empty row as shown below." }, { "code": null, "e": 4132, "s": 4017, "text": "[quickstart.cloudera:21000] > select * from customers;\nQuery: select * from customers \n\nFetched 0 row(s) in 0.12s\n" }, { "code": null, "e": 4266, "s": 4132, "text": "Open Impala Query editor and type the truncate Statement in it. And click on the execute button as shown in the following screenshot." }, { "code": null, "e": 4347, "s": 4266, "text": "After executing the query/statement, all the records from the table are deleted." }, { "code": null, "e": 4354, "s": 4347, "text": " Print" }, { "code": null, "e": 4365, "s": 4354, "text": " Add Notes" } ]
Fraud detection with cost-sensitive machine learning | by Roman Moser | Towards Data Science
In traditional two-class classification problems we aim to minimize misclassifications and measure the model performance with metrics like Accuracy, F-score or the AUC-ROC Curve. In certain problems, however, it is for the best to allow more misclassifications at the benefit of lower total costs. If costs associated with misclassifications vary among samples, we should apply an example-dependent cost-sensitive learning approach. But let’s start from the beginning... In this article, I will be explaining the concept of example dependent cost-sensitive machine learning by training and testing a variety of models on a credit card fraud data set. Please note that I chose the models for this task for the purpose of illustrating the concept rather than achieving optimal prediction results. Snippets of the code are presented in this article and the full code is available on my GitHub. Whereas traditional classification models assume that all misclassification errors carry the same cost, cost-sensitive models consider costs that vary by type of classification and across samples. Let’s take a look at the case of credit card transactions. Transactions that are not authorized by the true holder are considered fraudulent (usually a very small portion of all transactions). A credit card fraud detection system should automatically identify and block such fraudulent transactions and at the same time avoid blocking legitimate transactions. What are the costs associated with each type of classification? Let’s assume the following scenario. If a fraudulent transaction is not recognized by the system, the money is lost and the card holder needs to be reimbursed for the whole transaction amount. If the system labels a transaction as fraudulent, the transaction is blocked. In that case administrative costs occur because the card holder needs to be contacted and the card needs to be replaced (if the transaction was correctly labeled fraudulent) or reactivated (if the transaction was actually legitimate). Let’s also make the simplified assumption that the administrative cost are always identical. If the system correctly labels a transaction as legitimate, the transaction is automatically approved and no costs occur. This results in the following costs associated with each prediction scenario: Note that “Positives” are transactions predicted as fraudulent and “Negatives” are transactions predicted as legitimate. “True” and “False” refer to correct and incorrect predictions, respectively. Because the transaction cost depends on the sample, the cost of a False Negative can be negligibly low (e.g. for a transaction of $0.10), in which case the administrative costs of a positive prediction would outweigh the reimbursement costs, or very high (e.g. for a transaction of $10,000). The idea behind cost-sensitive learning is to take these example dependent costs into account and make predictions that aim to minimize the overall costs instead of minimizing misclassifications. Let’s consider two different approaches. The first one is to train a model with a loss function that minimizes the actual costs ($) instead of misclassification errors. In this case we need to provide the loss function with the costs associated with each of the four cases (False Positives, False Negatives, True Positives and True Negatives) so that the model can learn to make optimal predictions accordingly. The second approach is to train a regular model, but classify each sample when making predictions according to the lowest expected costs. In this case the costs on the training set are not needed. However, this approach only works for models that predict a probability which can then be used to calculate the expected costs. In the following, I will refer to models that use a cost-sensitive loss function as “Cost-sensitive models” and to models that minimize the expected costs when making predictions as “Cost classification models” For this case study, I used a credit card fraud data set (available on Kaggle) with 284,000 samples and 30 features. The target variable indicates whether a transaction is legitimate (0) or fraudulent (1). The data is highly imbalanced with only 0.17% fraudulent transactions. I trained and evaluated the following five models. Regular Logistic Regression (from scikit-learn)Regular Artificial Neural Network (built in Keras)Cost-sensitive Artificial Neural Network (Keras)Cost classification Logistic RegressionCost classification Artificial Neural Network Regular Logistic Regression (from scikit-learn) Regular Artificial Neural Network (built in Keras) Cost-sensitive Artificial Neural Network (Keras) Cost classification Logistic Regression Cost classification Artificial Neural Network In practice, artificial neural networks (“ANNs”) might not be the first choice for fraud detection. Tree based models such as Random Forests and Gradient Boosting Machines have the advantage of interpretability and often perform better. For the purpose of this illustration I used ANNs because of the relatively straightforward implementation of a cost-sensitive loss function. Also, as I will be showing, a simple ANN delivers quite strong results. To evaluate the results, I used two different metrics. The first one is the traditional F1-score which weighs precision and recall but does not consider the example dependent cost of misclassifications. To evaluate a model’s performance in terms of costs, I first calculated the sum of all costs resulting from the predictions based on whether the model predicted a False Positive, False Negative, True Positive or True Negative and the costs associated with each case. I then calculated the sum of the costs that would occur if all cases were predicted negative (“cost_max”), and define the cost savings as the fraction by which the actual predictions reduce the costs. To evaluate the models I used 5-fold cross-validation and split the data into five different training (80%) and test sets (20%). The results presented in the subsequent section refer to the average result on the five test sets. As base model serves a regular Logistic Regression model from the scikit-learn library. The plot below visualizes the distribution between predicted probabilities and transaction amounts. Without cost-sensitive classification there is no visible association between fraud probability and transaction amount. The logistic regression performs reasonably well with an average test set F1-score of 0.73 and cost savings of 0.48. Next, I built an ANN in Keras with three fully connected layers (50, 25 and 15 neurons) and two dropout layers. I ran the model for two epochs and used a batch size of 50. Using the Sequential model API from Keras, the implementation in Python looks like this: from keras.models import Sequentialfrom keras.layers import Dense, Dropoutdef ann(indput_dim, dropout=0.2): model = Sequential([ Dense(units=50, input_dim=indput_dim, activation='relu'), Dropout(dropout), Dense(units=25, activation='relu'), Dropout(dropout), Dense(15, activation='relu'), Dense(1, activation='sigmoid')]) return modelclf = ann(indput_dim=X_train.shape[1], dropout=0.2)clf.compile(optimizer='adam', loss='binary_crossentropy')clf.fit(X_train, y_train, batch_size=50, epochs=2, verbose=1)clf.predict(X_test, verbose=1) Below is the distribution of predicted fraud probabilities with the ANN. Similar to the logistic regression model there is no visible relationship between fraud probabilities and transaction amount. The ANN outperformed the logistic regression model in terms of both, F1-score and cost savings. Now it gets a bit more interesting. The cost-sensitive ANN is identical to the regular ANN with the difference of a cost-sensitive loss function. Both of the previous models used the logarithmic loss (“binary cross entropy”) as loss function: This loss function punishes false negatives and false positives equally. Let’s now take a look at a cost-sensitive loss function. Here, all four possible outcomes (False Positives, False Negatives, True Positives and True Negatives) are being considered and each of the outcomes carries a specified cost. The cost-sensitive loss function looks like this: Remember from the first section that True Positives and False Positives are being considered as equally expensive (fixed administrative cost for blocking a transaction). The cost for True negatives is $0 (no action) and the cost for False Negatives is the transaction amount (assume we have to reimburse the whole transaction). Note that of these four costs, only the cost for false negatives is example-dependent. This has the effect that with a higher transaction amount, the punishment for a not identified fraudulent transaction increases relative to the administrative cost of a positive prediction. The loss function should therefore train a model that is likelier to reject suspicious transaction when the transaction amount is higher. The transaction amounts range anywhere from $0 to $25,691 with a mean of $88 and I assumed a fixed administrative cost of $3. In Python we define the costs for False Positives, False Negatives, True Positives and True Negatives accordingly. Since the costs for False Negatives are example-dependent they are represented in a vector of length equal to number of samples. cost_FP = 3cost_FN = data['Amount']cost_TP = 3cost_TN = 0 Implementing an example dependent loss function in Keras is tricky because Keras does not allow arguments other than y_true and y_pred to be passed to the loss function. Constant variables can be passed to the loss function by wrapping the loss function into another function. However, the costs for False Negatives are example-dependent. I therefore used the trick of adding the costs of False Negatives as digits after the comma to y_true and extracting them inside the custom loss function while rounding y_true to the original integer value. The implementation of the functions to transform y_true and the custom loss function in Keras look like this: import keras.backend as Kdef create_y_input(y_train, c_FN): y_str = pd.Series(y_train).reset_index(drop=True).\ apply(lambda x: str(int(x))) c_FN_str = pd.Series(c_FN).reset_index(drop=True).\ apply(lambda x: '0'*(5-len(str(int(x)))) + str(int(x)) return y_str + '.' + c_FN_strdef custom_loss(c_FP, c_TP, c_TN): def loss_function(y_input, y_pred): y_true = K.round(y_input) c_FN = (y_input - y_true) * 1e5 cost = y_true * K.log(y_pred) * c_FN + y_true * K.log(1 - y_pred) * c_TP) + (1 - y_true) * K.log(1 - y_pred) * c_FP + (1 - y_true) * K.log(y_pred) * c_TN) return - K.mean(cost, axis=-1) return loss_function I then called the defined functions to create the y_input vector, train the cost-sensitive ANN and make predictions: y_input = create_y_input(y_train, cost_FN_train).apply(float)clf = ann(indput_dim=X_train.shape[1], dropout=0.2)clf.compile(optimizer='adam', loss=custom_loss(cost_FP, cost_TP, cost_TN))clf.fit(X_train, y_input, batch_size=50, epochs=2, verbose=1)clf.predict(X_test, verbose=1) In the distribution plot below we can see the effect of cost-sensitive learning. With an increasing transaction amount, the general distribution of predictions expands to the right (higher fraud probabilities). Note that in this case, due to the nature of the problem and definition of the loss function, “predicted fraud probability” means “should we identify the transaction as fraudulent?” rather than “is the transaction fraudulent”. The evaluation shows the expected effect of cost-sensitive learning. The cost savings increased by 5% and the F1-score decreased by a similar margin. The consequence of cost-sensitive classification is a higher number of misclassifications at the benefit of lower total misclassification costs. As opposed to a cost-sensitive model that trains with a customized loss function, cost classification models calculate the expected costs based on predicted probabilities. The expected costs for a predicting a legitimate and a fraudulent transaction are calculated as follows: The classifier then chooses whichever prediction is expected to result in lower costs. I therefore used the probability prediction results from the regular logistic regression and ANN and reclassified the predictions based on the expected costs. The plot below visualizes the effect of the cost-dependent classification for the example of the logistic regression model. Note that the distribution of predicted probabilities did not change from the one produced by the regular logistic regression model. However, with cost dependent classification, the model tends to identify transactions with a small fraud probability as fraudulent as the transaction amount increases. On the right side of the plot we see that transactions with a very small amount are predicted as legitimate even as the fraud probabilities approach 1. This is due to the assumption that True Positives carry administrative costs of $3. Classifying the predictions based on expected costs leads to even better results in terms of cost savings (and significantly worse results in terms of F1-score). While implementing a cost-sensitive loss function for the ANN reduced the costs by 5%, the cost classification ANN was able to reduce costs by 10%. This article illustrates two fundamentally different approaches for example based cost-sensitive classification on credit card fraud prediction. While cost-sensitive training models require a custom loss function, cost classification models only require the probabilities for each class and the costs associated with each outcome to classify a transaction. In my sample case cost classification models achieved slightly better cost savings at the expense of a high number of misclassifications. Additionally, a cost-classification model is easier to implement as it does not require a custom loss function for training. However, the cost classification method is only applicable for models that predict probabilities, which a logistic regression and ANN conveniently do. Tree based models, adopted more widely for fraud detection, however, generally separate predictions directly into classes, making the cost classification approach infeasible. A cost-sensitive approach for tree based models is, while conceptually similar to the one presented in this article, more complicated in implementation. If you are interested in this topic I would suggest to take a look at the paper referenced below. Thanks for reading this article. Please feel free to comment or ask questions via the comment section below or to connect with me on LinkedIn. The code created for this illustration can be accessed on my GitHub The credit card fraud data set is available on Kaggle If you are interested in learning more about cost-sensitive learning with tree based models I suggest this paper from A. C. Bahnsen, D. Aouada and B. Ottersten along with the costcla GitHub repository
[ { "code": null, "e": 643, "s": 172, "text": "In traditional two-class classification problems we aim to minimize misclassifications and measure the model performance with metrics like Accuracy, F-score or the AUC-ROC Curve. In certain problems, however, it is for the best to allow more misclassifications at the benefit of lower total costs. If costs associated with misclassifications vary among samples, we should apply an example-dependent cost-sensitive learning approach. But let’s start from the beginning..." }, { "code": null, "e": 1063, "s": 643, "text": "In this article, I will be explaining the concept of example dependent cost-sensitive machine learning by training and testing a variety of models on a credit card fraud data set. Please note that I chose the models for this task for the purpose of illustrating the concept rather than achieving optimal prediction results. Snippets of the code are presented in this article and the full code is available on my GitHub." }, { "code": null, "e": 1260, "s": 1063, "text": "Whereas traditional classification models assume that all misclassification errors carry the same cost, cost-sensitive models consider costs that vary by type of classification and across samples." }, { "code": null, "e": 1620, "s": 1260, "text": "Let’s take a look at the case of credit card transactions. Transactions that are not authorized by the true holder are considered fraudulent (usually a very small portion of all transactions). A credit card fraud detection system should automatically identify and block such fraudulent transactions and at the same time avoid blocking legitimate transactions." }, { "code": null, "e": 2483, "s": 1620, "text": "What are the costs associated with each type of classification? Let’s assume the following scenario. If a fraudulent transaction is not recognized by the system, the money is lost and the card holder needs to be reimbursed for the whole transaction amount. If the system labels a transaction as fraudulent, the transaction is blocked. In that case administrative costs occur because the card holder needs to be contacted and the card needs to be replaced (if the transaction was correctly labeled fraudulent) or reactivated (if the transaction was actually legitimate). Let’s also make the simplified assumption that the administrative cost are always identical. If the system correctly labels a transaction as legitimate, the transaction is automatically approved and no costs occur. This results in the following costs associated with each prediction scenario:" }, { "code": null, "e": 2681, "s": 2483, "text": "Note that “Positives” are transactions predicted as fraudulent and “Negatives” are transactions predicted as legitimate. “True” and “False” refer to correct and incorrect predictions, respectively." }, { "code": null, "e": 2973, "s": 2681, "text": "Because the transaction cost depends on the sample, the cost of a False Negative can be negligibly low (e.g. for a transaction of $0.10), in which case the administrative costs of a positive prediction would outweigh the reimbursement costs, or very high (e.g. for a transaction of $10,000)." }, { "code": null, "e": 3169, "s": 2973, "text": "The idea behind cost-sensitive learning is to take these example dependent costs into account and make predictions that aim to minimize the overall costs instead of minimizing misclassifications." }, { "code": null, "e": 3581, "s": 3169, "text": "Let’s consider two different approaches. The first one is to train a model with a loss function that minimizes the actual costs ($) instead of misclassification errors. In this case we need to provide the loss function with the costs associated with each of the four cases (False Positives, False Negatives, True Positives and True Negatives) so that the model can learn to make optimal predictions accordingly." }, { "code": null, "e": 3906, "s": 3581, "text": "The second approach is to train a regular model, but classify each sample when making predictions according to the lowest expected costs. In this case the costs on the training set are not needed. However, this approach only works for models that predict a probability which can then be used to calculate the expected costs." }, { "code": null, "e": 4117, "s": 3906, "text": "In the following, I will refer to models that use a cost-sensitive loss function as “Cost-sensitive models” and to models that minimize the expected costs when making predictions as “Cost classification models”" }, { "code": null, "e": 4445, "s": 4117, "text": "For this case study, I used a credit card fraud data set (available on Kaggle) with 284,000 samples and 30 features. The target variable indicates whether a transaction is legitimate (0) or fraudulent (1). The data is highly imbalanced with only 0.17% fraudulent transactions. I trained and evaluated the following five models." }, { "code": null, "e": 4675, "s": 4445, "text": "Regular Logistic Regression (from scikit-learn)Regular Artificial Neural Network (built in Keras)Cost-sensitive Artificial Neural Network (Keras)Cost classification Logistic RegressionCost classification Artificial Neural Network" }, { "code": null, "e": 4723, "s": 4675, "text": "Regular Logistic Regression (from scikit-learn)" }, { "code": null, "e": 4774, "s": 4723, "text": "Regular Artificial Neural Network (built in Keras)" }, { "code": null, "e": 4823, "s": 4774, "text": "Cost-sensitive Artificial Neural Network (Keras)" }, { "code": null, "e": 4863, "s": 4823, "text": "Cost classification Logistic Regression" }, { "code": null, "e": 4909, "s": 4863, "text": "Cost classification Artificial Neural Network" }, { "code": null, "e": 5359, "s": 4909, "text": "In practice, artificial neural networks (“ANNs”) might not be the first choice for fraud detection. Tree based models such as Random Forests and Gradient Boosting Machines have the advantage of interpretability and often perform better. For the purpose of this illustration I used ANNs because of the relatively straightforward implementation of a cost-sensitive loss function. Also, as I will be showing, a simple ANN delivers quite strong results." }, { "code": null, "e": 5562, "s": 5359, "text": "To evaluate the results, I used two different metrics. The first one is the traditional F1-score which weighs precision and recall but does not consider the example dependent cost of misclassifications." }, { "code": null, "e": 5829, "s": 5562, "text": "To evaluate a model’s performance in terms of costs, I first calculated the sum of all costs resulting from the predictions based on whether the model predicted a False Positive, False Negative, True Positive or True Negative and the costs associated with each case." }, { "code": null, "e": 6030, "s": 5829, "text": "I then calculated the sum of the costs that would occur if all cases were predicted negative (“cost_max”), and define the cost savings as the fraction by which the actual predictions reduce the costs." }, { "code": null, "e": 6258, "s": 6030, "text": "To evaluate the models I used 5-fold cross-validation and split the data into five different training (80%) and test sets (20%). The results presented in the subsequent section refer to the average result on the five test sets." }, { "code": null, "e": 6566, "s": 6258, "text": "As base model serves a regular Logistic Regression model from the scikit-learn library. The plot below visualizes the distribution between predicted probabilities and transaction amounts. Without cost-sensitive classification there is no visible association between fraud probability and transaction amount." }, { "code": null, "e": 6683, "s": 6566, "text": "The logistic regression performs reasonably well with an average test set F1-score of 0.73 and cost savings of 0.48." }, { "code": null, "e": 6944, "s": 6683, "text": "Next, I built an ANN in Keras with three fully connected layers (50, 25 and 15 neurons) and two dropout layers. I ran the model for two epochs and used a batch size of 50. Using the Sequential model API from Keras, the implementation in Python looks like this:" }, { "code": null, "e": 7502, "s": 6944, "text": "from keras.models import Sequentialfrom keras.layers import Dense, Dropoutdef ann(indput_dim, dropout=0.2): model = Sequential([ Dense(units=50, input_dim=indput_dim, activation='relu'), Dropout(dropout), Dense(units=25, activation='relu'), Dropout(dropout), Dense(15, activation='relu'), Dense(1, activation='sigmoid')]) return modelclf = ann(indput_dim=X_train.shape[1], dropout=0.2)clf.compile(optimizer='adam', loss='binary_crossentropy')clf.fit(X_train, y_train, batch_size=50, epochs=2, verbose=1)clf.predict(X_test, verbose=1)" }, { "code": null, "e": 7701, "s": 7502, "text": "Below is the distribution of predicted fraud probabilities with the ANN. Similar to the logistic regression model there is no visible relationship between fraud probabilities and transaction amount." }, { "code": null, "e": 7797, "s": 7701, "text": "The ANN outperformed the logistic regression model in terms of both, F1-score and cost savings." }, { "code": null, "e": 8040, "s": 7797, "text": "Now it gets a bit more interesting. The cost-sensitive ANN is identical to the regular ANN with the difference of a cost-sensitive loss function. Both of the previous models used the logarithmic loss (“binary cross entropy”) as loss function:" }, { "code": null, "e": 8395, "s": 8040, "text": "This loss function punishes false negatives and false positives equally. Let’s now take a look at a cost-sensitive loss function. Here, all four possible outcomes (False Positives, False Negatives, True Positives and True Negatives) are being considered and each of the outcomes carries a specified cost. The cost-sensitive loss function looks like this:" }, { "code": null, "e": 9264, "s": 8395, "text": "Remember from the first section that True Positives and False Positives are being considered as equally expensive (fixed administrative cost for blocking a transaction). The cost for True negatives is $0 (no action) and the cost for False Negatives is the transaction amount (assume we have to reimburse the whole transaction). Note that of these four costs, only the cost for false negatives is example-dependent. This has the effect that with a higher transaction amount, the punishment for a not identified fraudulent transaction increases relative to the administrative cost of a positive prediction. The loss function should therefore train a model that is likelier to reject suspicious transaction when the transaction amount is higher. The transaction amounts range anywhere from $0 to $25,691 with a mean of $88 and I assumed a fixed administrative cost of $3." }, { "code": null, "e": 9508, "s": 9264, "text": "In Python we define the costs for False Positives, False Negatives, True Positives and True Negatives accordingly. Since the costs for False Negatives are example-dependent they are represented in a vector of length equal to number of samples." }, { "code": null, "e": 9566, "s": 9508, "text": "cost_FP = 3cost_FN = data['Amount']cost_TP = 3cost_TN = 0" }, { "code": null, "e": 10222, "s": 9566, "text": "Implementing an example dependent loss function in Keras is tricky because Keras does not allow arguments other than y_true and y_pred to be passed to the loss function. Constant variables can be passed to the loss function by wrapping the loss function into another function. However, the costs for False Negatives are example-dependent. I therefore used the trick of adding the costs of False Negatives as digits after the comma to y_true and extracting them inside the custom loss function while rounding y_true to the original integer value. The implementation of the functions to transform y_true and the custom loss function in Keras look like this:" }, { "code": null, "e": 10943, "s": 10222, "text": "import keras.backend as Kdef create_y_input(y_train, c_FN): y_str = pd.Series(y_train).reset_index(drop=True).\\ apply(lambda x: str(int(x))) c_FN_str = pd.Series(c_FN).reset_index(drop=True).\\ apply(lambda x: '0'*(5-len(str(int(x)))) + str(int(x)) return y_str + '.' + c_FN_strdef custom_loss(c_FP, c_TP, c_TN): def loss_function(y_input, y_pred): y_true = K.round(y_input) c_FN = (y_input - y_true) * 1e5 cost = y_true * K.log(y_pred) * c_FN + y_true * K.log(1 - y_pred) * c_TP) + (1 - y_true) * K.log(1 - y_pred) * c_FP + (1 - y_true) * K.log(y_pred) * c_TN) return - K.mean(cost, axis=-1) return loss_function" }, { "code": null, "e": 11060, "s": 10943, "text": "I then called the defined functions to create the y_input vector, train the cost-sensitive ANN and make predictions:" }, { "code": null, "e": 11349, "s": 11060, "text": "y_input = create_y_input(y_train, cost_FN_train).apply(float)clf = ann(indput_dim=X_train.shape[1], dropout=0.2)clf.compile(optimizer='adam', loss=custom_loss(cost_FP, cost_TP, cost_TN))clf.fit(X_train, y_input, batch_size=50, epochs=2, verbose=1)clf.predict(X_test, verbose=1)" }, { "code": null, "e": 11787, "s": 11349, "text": "In the distribution plot below we can see the effect of cost-sensitive learning. With an increasing transaction amount, the general distribution of predictions expands to the right (higher fraud probabilities). Note that in this case, due to the nature of the problem and definition of the loss function, “predicted fraud probability” means “should we identify the transaction as fraudulent?” rather than “is the transaction fraudulent”." }, { "code": null, "e": 12082, "s": 11787, "text": "The evaluation shows the expected effect of cost-sensitive learning. The cost savings increased by 5% and the F1-score decreased by a similar margin. The consequence of cost-sensitive classification is a higher number of misclassifications at the benefit of lower total misclassification costs." }, { "code": null, "e": 12359, "s": 12082, "text": "As opposed to a cost-sensitive model that trains with a customized loss function, cost classification models calculate the expected costs based on predicted probabilities. The expected costs for a predicting a legitimate and a fraudulent transaction are calculated as follows:" }, { "code": null, "e": 12446, "s": 12359, "text": "The classifier then chooses whichever prediction is expected to result in lower costs." }, { "code": null, "e": 13266, "s": 12446, "text": "I therefore used the probability prediction results from the regular logistic regression and ANN and reclassified the predictions based on the expected costs. The plot below visualizes the effect of the cost-dependent classification for the example of the logistic regression model. Note that the distribution of predicted probabilities did not change from the one produced by the regular logistic regression model. However, with cost dependent classification, the model tends to identify transactions with a small fraud probability as fraudulent as the transaction amount increases. On the right side of the plot we see that transactions with a very small amount are predicted as legitimate even as the fraud probabilities approach 1. This is due to the assumption that True Positives carry administrative costs of $3." }, { "code": null, "e": 13576, "s": 13266, "text": "Classifying the predictions based on expected costs leads to even better results in terms of cost savings (and significantly worse results in terms of F1-score). While implementing a cost-sensitive loss function for the ANN reduced the costs by 5%, the cost classification ANN was able to reduce costs by 10%." }, { "code": null, "e": 14773, "s": 13576, "text": "This article illustrates two fundamentally different approaches for example based cost-sensitive classification on credit card fraud prediction. While cost-sensitive training models require a custom loss function, cost classification models only require the probabilities for each class and the costs associated with each outcome to classify a transaction. In my sample case cost classification models achieved slightly better cost savings at the expense of a high number of misclassifications. Additionally, a cost-classification model is easier to implement as it does not require a custom loss function for training. However, the cost classification method is only applicable for models that predict probabilities, which a logistic regression and ANN conveniently do. Tree based models, adopted more widely for fraud detection, however, generally separate predictions directly into classes, making the cost classification approach infeasible. A cost-sensitive approach for tree based models is, while conceptually similar to the one presented in this article, more complicated in implementation. If you are interested in this topic I would suggest to take a look at the paper referenced below." }, { "code": null, "e": 14916, "s": 14773, "text": "Thanks for reading this article. Please feel free to comment or ask questions via the comment section below or to connect with me on LinkedIn." }, { "code": null, "e": 14984, "s": 14916, "text": "The code created for this illustration can be accessed on my GitHub" }, { "code": null, "e": 15038, "s": 14984, "text": "The credit card fraud data set is available on Kaggle" } ]
Model Evaluation and Parameter Tuning | Towards Data Science
In the previous article, we built an ANN to solve a binary classification problem. If you remember, one question left for homework is why we used [[]] for new customer data. The answer is we need to put a customer data in a horizontal vector, not a vertical vector because all observations in the input data are in lines not in columns. Hope you got it right😎. This article focuses on cross-validation and grid search for model optimization, split into 2 parts: Model evaluationParameter tuningSummary Model evaluation Parameter tuning Summary Now let’s begin the journey 🏃‍♀️🏃‍♂️. Model evaluation Model evaluation You may wonder why we have to spend efforts on model evaluation 🤔? The problem is if we re-run the ANN, every time the model produces different accuracy not only on the train set and the test set. So evaluating the model performance on one single test is not the most relevant way. A typical method is to use K-fold cross-validation. Figure 1 shows how it works. We split the training set into K folds (e.g. K=10). Then train the model on 9 folds and test it on the last remaining fold. With 10 folds, we make 10 different combinations with 9 training sets and 1 test set, and train/test the model 10 times. After that, we take an average of 10 evaluations and compute the standard deviation. With that, we can determine which category of the model belongs to as in Figure 2. To implement K-fold cross-validation, we use a scikit_learn wrapper in Keras: KerasClassifier. Specifically, we use Keras to build the model and use scikit_learn for cross-validation. First thing is to build a function for the model architecture as the function is a required argument for the Keras wrapper. As you notice below, this is the same ANN architecture as we built before. from keras.wrappers.scikit_learn import KerasClassifierfrom sklearn.model_selection import cross_val_scorefrom keras.models import Sequentialfrom keras.layers import Densedef build_classifier(): classifier = Sequential() classifier.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’, input_dim = 11)) classifier.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’)) classifier.add(Dense(units = 1, kernel_initializer = ‘uniform’, activation = ‘sigmoid’)) classifier.compile(optimizer = ‘adam’, loss = ‘binary_crossentropy’, metrics = [‘accuracy’]) return classifier With the classifier built using the above function, we create a KerasClassifier object. Below we specify the batch size of 10 and the number of epochs of 100 which model needs to be trained on. classifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs = 100) Now, let’s apply K-fold cross-validation on the classifier by using cross_val_score() method. This function returns a list of training accuracy. Parameter cv is the fold number we use for cross-validation. Here the classifier will be trained on 10 different training sets, split from the initial training set. accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)mean = accuracies.mean()std = accuracies.std() Here, cross-validation may take a while. In the end, we get an accuracy of 10 evaluation as shown in Figure 2. The average accuracy is 0.843 and the standard deviation is 1.60% 🤪. 2. Parameter tuning With reliable model accuracy, let’s try to improve it using two techniques. 2.1 Dropout regularization One technique we have not mentioned is dropout regularization. This is the solution for over-fitting which is related to high variance. How does dropout work? At each training iteration, some neurons are randomly disabled to prevent them from depending on each other. By overwriting these neurons, neural networks retain a different configuration of neurons each time, helping the neural networks learn independent correlations of the data. This prevents the neurons from over-learn. Let’s implement it using Keras. Basically, we add a drop out layer after each hidden layer. Note p=0.1 means 10% of neurons will be disabled each iteration. from keras.layers import Dropoutclassifier.add(Dense(output_dim = 6, init = ‘uniform’, activation = ‘relu’, input_dim = 11))#add dropout layerclassifier.add(Dropout(p =0.1))classifier.add(Dense(output_dim = 6, init = ‘uniform’, activation = ‘relu’))#add dropout layerclassifier.add(Dropout(p =0.1))#add output layerclassifier.add(Dense(output_dim = 1, init = ‘uniform’, activation = ‘sigmoid’)) 2.2 Parameter tuning Neural networks have a few hyper-parameters, such as the number of epochs, batch size, and learning rate. Parameter tuning is about finding the best parameter for the model. Here we use grid search to test different combinations of the parameters. To implement it, we use a scikit_learn wrapper in Keras: KerasClassifier to wrap the neural network. Then create a grid search object and apply parameter tuning on the wrapped classifier. First, build the classifier function as below. def build_classifier(optimizer): classifier = Sequential() classifier.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’, input_dim = 11)) classifier.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’)) classifier.add(Dense(units = 1, kernel_initializer = ‘uniform’, activation = ‘sigmoid’)) classifier.compile(optimizer = optimizer, loss = ‘binary_crossentropy’, metrics = [‘accuracy’]) return classifierclassifier = KerasClassifier(build_fn = build_classifier) Note above, the number of epoch and batch size is not specified, because they are the parameters we plan to tune, which will be specified in the grid search object below. Let’s create a dictionary for parameters that contain values we want the model to try on. parameters = {‘batch_size’: [25, 32], ‘nb_epoch’: [100, 500], ‘optimizer’: [‘adam’, ‘rmsprop’]} If you notice above, we have an argument optimizer for build_classifier() function. This argument gives a way to tune the optimizer. To implement grid search, we first create an object of GridSearchCV class with the classifier and parameters. grid_search = GridSearchCV(estimator=classifier, param_grid =parameters, scoring = ‘accuracy, cv = 10’) Finally, let’s fit ANN on the training set while running grid search to find optimal parameters. grid_search = grid_search.fit(X_train, y_train) What we are most interested in is the best parameter which produces the highest accuracy. So with below: best_parameters = grid_search.best_params_best_accuracy = grid_search.best_score_ Finally, after a few hours, we got an improved accuracy of 0.849 ✨✨. The optimal parameter is batch size 25, epoch number 500, and optimizer Adam as shown in Figure 3. 3. Summary In a summary, through cross-validation, we found the model accuracy is about 0.843. By using random dropout regularization and grid search, we improved the model accuracy to 0.849. Generally, Grid Search can be performed in 2 steps with a step first to find the rough range and another small step to refine the best range. Great! That’s all! ✨✨If you need some extra, visit my Github page. (FYI, the repos is actively maintained 💕💕)
[ { "code": null, "e": 532, "s": 171, "text": "In the previous article, we built an ANN to solve a binary classification problem. If you remember, one question left for homework is why we used [[]] for new customer data. The answer is we need to put a customer data in a horizontal vector, not a vertical vector because all observations in the input data are in lines not in columns. Hope you got it right😎." }, { "code": null, "e": 633, "s": 532, "text": "This article focuses on cross-validation and grid search for model optimization, split into 2 parts:" }, { "code": null, "e": 673, "s": 633, "text": "Model evaluationParameter tuningSummary" }, { "code": null, "e": 690, "s": 673, "text": "Model evaluation" }, { "code": null, "e": 707, "s": 690, "text": "Parameter tuning" }, { "code": null, "e": 715, "s": 707, "text": "Summary" }, { "code": null, "e": 753, "s": 715, "text": "Now let’s begin the journey 🏃‍♀️🏃‍♂️." }, { "code": null, "e": 770, "s": 753, "text": "Model evaluation" }, { "code": null, "e": 787, "s": 770, "text": "Model evaluation" }, { "code": null, "e": 1069, "s": 787, "text": "You may wonder why we have to spend efforts on model evaluation 🤔? The problem is if we re-run the ANN, every time the model produces different accuracy not only on the train set and the test set. So evaluating the model performance on one single test is not the most relevant way." }, { "code": null, "e": 1150, "s": 1069, "text": "A typical method is to use K-fold cross-validation. Figure 1 shows how it works." }, { "code": null, "e": 1563, "s": 1150, "text": "We split the training set into K folds (e.g. K=10). Then train the model on 9 folds and test it on the last remaining fold. With 10 folds, we make 10 different combinations with 9 training sets and 1 test set, and train/test the model 10 times. After that, we take an average of 10 evaluations and compute the standard deviation. With that, we can determine which category of the model belongs to as in Figure 2." }, { "code": null, "e": 1946, "s": 1563, "text": "To implement K-fold cross-validation, we use a scikit_learn wrapper in Keras: KerasClassifier. Specifically, we use Keras to build the model and use scikit_learn for cross-validation. First thing is to build a function for the model architecture as the function is a required argument for the Keras wrapper. As you notice below, this is the same ANN architecture as we built before." }, { "code": null, "e": 2555, "s": 1946, "text": "from keras.wrappers.scikit_learn import KerasClassifierfrom sklearn.model_selection import cross_val_scorefrom keras.models import Sequentialfrom keras.layers import Densedef build_classifier(): classifier = Sequential() classifier.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’, input_dim = 11)) classifier.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’)) classifier.add(Dense(units = 1, kernel_initializer = ‘uniform’, activation = ‘sigmoid’)) classifier.compile(optimizer = ‘adam’, loss = ‘binary_crossentropy’, metrics = [‘accuracy’]) return classifier" }, { "code": null, "e": 2749, "s": 2555, "text": "With the classifier built using the above function, we create a KerasClassifier object. Below we specify the batch size of 10 and the number of epochs of 100 which model needs to be trained on." }, { "code": null, "e": 2838, "s": 2749, "text": "classifier = KerasClassifier(build_fn = build_classifier, batch_size = 10, epochs = 100)" }, { "code": null, "e": 3148, "s": 2838, "text": "Now, let’s apply K-fold cross-validation on the classifier by using cross_val_score() method. This function returns a list of training accuracy. Parameter cv is the fold number we use for cross-validation. Here the classifier will be trained on 10 different training sets, split from the initial training set." }, { "code": null, "e": 3282, "s": 3148, "text": "accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10)mean = accuracies.mean()std = accuracies.std()" }, { "code": null, "e": 3462, "s": 3282, "text": "Here, cross-validation may take a while. In the end, we get an accuracy of 10 evaluation as shown in Figure 2. The average accuracy is 0.843 and the standard deviation is 1.60% 🤪." }, { "code": null, "e": 3482, "s": 3462, "text": "2. Parameter tuning" }, { "code": null, "e": 3558, "s": 3482, "text": "With reliable model accuracy, let’s try to improve it using two techniques." }, { "code": null, "e": 3585, "s": 3558, "text": "2.1 Dropout regularization" }, { "code": null, "e": 4069, "s": 3585, "text": "One technique we have not mentioned is dropout regularization. This is the solution for over-fitting which is related to high variance. How does dropout work? At each training iteration, some neurons are randomly disabled to prevent them from depending on each other. By overwriting these neurons, neural networks retain a different configuration of neurons each time, helping the neural networks learn independent correlations of the data. This prevents the neurons from over-learn." }, { "code": null, "e": 4226, "s": 4069, "text": "Let’s implement it using Keras. Basically, we add a drop out layer after each hidden layer. Note p=0.1 means 10% of neurons will be disabled each iteration." }, { "code": null, "e": 4621, "s": 4226, "text": "from keras.layers import Dropoutclassifier.add(Dense(output_dim = 6, init = ‘uniform’, activation = ‘relu’, input_dim = 11))#add dropout layerclassifier.add(Dropout(p =0.1))classifier.add(Dense(output_dim = 6, init = ‘uniform’, activation = ‘relu’))#add dropout layerclassifier.add(Dropout(p =0.1))#add output layerclassifier.add(Dense(output_dim = 1, init = ‘uniform’, activation = ‘sigmoid’))" }, { "code": null, "e": 4642, "s": 4621, "text": "2.2 Parameter tuning" }, { "code": null, "e": 4890, "s": 4642, "text": "Neural networks have a few hyper-parameters, such as the number of epochs, batch size, and learning rate. Parameter tuning is about finding the best parameter for the model. Here we use grid search to test different combinations of the parameters." }, { "code": null, "e": 5125, "s": 4890, "text": "To implement it, we use a scikit_learn wrapper in Keras: KerasClassifier to wrap the neural network. Then create a grid search object and apply parameter tuning on the wrapped classifier. First, build the classifier function as below." }, { "code": null, "e": 5632, "s": 5125, "text": "def build_classifier(optimizer): classifier = Sequential() classifier.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’, input_dim = 11)) classifier.add(Dense(units = 6, kernel_initializer = ‘uniform’, activation = ‘relu’)) classifier.add(Dense(units = 1, kernel_initializer = ‘uniform’, activation = ‘sigmoid’)) classifier.compile(optimizer = optimizer, loss = ‘binary_crossentropy’, metrics = [‘accuracy’]) return classifierclassifier = KerasClassifier(build_fn = build_classifier)" }, { "code": null, "e": 5803, "s": 5632, "text": "Note above, the number of epoch and batch size is not specified, because they are the parameters we plan to tune, which will be specified in the grid search object below." }, { "code": null, "e": 5893, "s": 5803, "text": "Let’s create a dictionary for parameters that contain values we want the model to try on." }, { "code": null, "e": 5989, "s": 5893, "text": "parameters = {‘batch_size’: [25, 32], ‘nb_epoch’: [100, 500], ‘optimizer’: [‘adam’, ‘rmsprop’]}" }, { "code": null, "e": 6232, "s": 5989, "text": "If you notice above, we have an argument optimizer for build_classifier() function. This argument gives a way to tune the optimizer. To implement grid search, we first create an object of GridSearchCV class with the classifier and parameters." }, { "code": null, "e": 6336, "s": 6232, "text": "grid_search = GridSearchCV(estimator=classifier, param_grid =parameters, scoring = ‘accuracy, cv = 10’)" }, { "code": null, "e": 6433, "s": 6336, "text": "Finally, let’s fit ANN on the training set while running grid search to find optimal parameters." }, { "code": null, "e": 6481, "s": 6433, "text": "grid_search = grid_search.fit(X_train, y_train)" }, { "code": null, "e": 6586, "s": 6481, "text": "What we are most interested in is the best parameter which produces the highest accuracy. So with below:" }, { "code": null, "e": 6668, "s": 6586, "text": "best_parameters = grid_search.best_params_best_accuracy = grid_search.best_score_" }, { "code": null, "e": 6836, "s": 6668, "text": "Finally, after a few hours, we got an improved accuracy of 0.849 ✨✨. The optimal parameter is batch size 25, epoch number 500, and optimizer Adam as shown in Figure 3." }, { "code": null, "e": 6847, "s": 6836, "text": "3. Summary" }, { "code": null, "e": 7170, "s": 6847, "text": "In a summary, through cross-validation, we found the model accuracy is about 0.843. By using random dropout regularization and grid search, we improved the model accuracy to 0.849. Generally, Grid Search can be performed in 2 steps with a step first to find the rough range and another small step to refine the best range." } ]
MATLAB - Bitwise Operations
MATLAB provides various functions for bit-wise operations like 'bitwise and', 'bitwise or' and 'bitwise not' operations, shift operation, etc. The following table shows the commonly used bitwise operations − Create a script file and type the following code − a = 60; % 60 = 0011 1100 b = 13; % 13 = 0000 1101 c = bitand(a, b) % 12 = 0000 1100 c = bitor(a, b) % 61 = 0011 1101 c = bitxor(a, b) % 49 = 0011 0001 c = bitshift(a, 2) % 240 = 1111 0000 */ c = bitshift(a,-2) % 15 = 0000 1111 */ When you run the file, it displays the following result − c = 12 c = 61 c = 49 c = 240 c = 15 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": 2284, "s": 2141, "text": "MATLAB provides various functions for bit-wise operations like 'bitwise and', 'bitwise or' and 'bitwise not' operations, shift operation, etc." }, { "code": null, "e": 2349, "s": 2284, "text": "The following table shows the commonly used bitwise operations −" }, { "code": null, "e": 2400, "s": 2349, "text": "Create a script file and type the following code −" }, { "code": null, "e": 2688, "s": 2400, "text": "a = 60; % 60 = 0011 1100 \nb = 13; % 13 = 0000 1101 \nc = bitand(a, b) % 12 = 0000 1100 \nc = bitor(a, b) % 61 = 0011 1101 \nc = bitxor(a, b) % 49 = 0011 0001 \nc = bitshift(a, 2) % 240 = 1111 0000 */\nc = bitshift(a,-2) % 15 = 0000 1111 */" }, { "code": null, "e": 2746, "s": 2688, "text": "When you run the file, it displays the following result −" }, { "code": null, "e": 2788, "s": 2746, "text": "c = 12\nc = 61\nc = 49\nc = 240\nc = 15\n" }, { "code": null, "e": 2821, "s": 2788, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 2834, "s": 2821, "text": " Nouman Azam" }, { "code": null, "e": 2869, "s": 2834, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 2882, "s": 2869, "text": " Nouman Azam" }, { "code": null, "e": 2915, "s": 2882, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 2924, "s": 2915, "text": " Sanjeev" }, { "code": null, "e": 2957, "s": 2924, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 2973, "s": 2957, "text": " TELCOMA Global" }, { "code": null, "e": 3006, "s": 2973, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 3022, "s": 3006, "text": " TELCOMA Global" }, { "code": null, "e": 3055, "s": 3022, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 3072, "s": 3055, "text": " Phinite Academy" }, { "code": null, "e": 3079, "s": 3072, "text": " Print" }, { "code": null, "e": 3090, "s": 3079, "text": " Add Notes" } ]
java.net.BindException in Java with Examples - GeeksforGeeks
03 Mar, 2021 The java.net.BindException is an exception that is thrown when there is an error caused in binding when an application tries to bind a socket to a local address and port. Mostly, this may occur due to 2 reasons, either the port is already in use(due to another application) or the address requested just cannot be assigned to this application. The BindException inherits from the SocketException class, thus showing there is an error related to the socket creation or access. Constructors The following constructors are available for BindException: BindException(): Creates a simple instance of the BindException class with no detailed message BindException(String msg): Creates an instance of the BindException class with the specified message as the reason why the bind error occurred. Method Summary Methods inherited from class java.lang.Throwable: addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, setStackTrace, toString. Methods inherited from class java.lang.Object: clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait. Methods inherited from class java.lang.Throwable: addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, setStackTrace, toString. Methods inherited from class java.lang.Object: clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait. HIERARCHY OF java.net.BindException Example: In the example below, we have created a class Ex_BindException to demonstrate the BindException : Java // java.net.BindException in Java with Examples import java.io.*;import java.net.*;public class Ex_BindException { // Creating a variable PORT1 with arbitrary port value private final static int PORT1 = 8000; public static void main(String[] args) throws IOException { // Creating instance of the ServerSocket class // and binding it to the arbitrary port ServerSocket socket1 = new ServerSocket(PORT1); // Creating another instance of the ServerSocket // class and binding it to the same arbitrary // port,thus it gives a BindException. ServerSocket socket2 = new ServerSocket(PORT1); socket1.close(); socket2.close(); }} Output: In the above code, we first created an instance of the ServerSocket class using the specified port. That instance is successfully bound. However, when on the creation of another instance using the same port, a BindException occurs as the port is already bound to the other Socket. Here, we can simply use another arbitrary port (which is not in use) for the second socket to get rid of this exception. Java-Exceptions Picked Technical Scripter 2020 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23948, "s": 23920, "text": "\n03 Mar, 2021" }, { "code": null, "e": 24426, "s": 23948, "text": "The java.net.BindException is an exception that is thrown when there is an error caused in binding when an application tries to bind a socket to a local address and port. Mostly, this may occur due to 2 reasons, either the port is already in use(due to another application) or the address requested just cannot be assigned to this application. The BindException inherits from the SocketException class, thus showing there is an error related to the socket creation or access. " }, { "code": null, "e": 24439, "s": 24426, "text": "Constructors" }, { "code": null, "e": 24499, "s": 24439, "text": "The following constructors are available for BindException:" }, { "code": null, "e": 24594, "s": 24499, "text": "BindException(): Creates a simple instance of the BindException class with no detailed message" }, { "code": null, "e": 24738, "s": 24594, "text": "BindException(String msg): Creates an instance of the BindException class with the specified message as the reason why the bind error occurred." }, { "code": null, "e": 24754, "s": 24738, "text": "Method Summary " }, { "code": null, "e": 25080, "s": 24754, "text": "Methods inherited from class java.lang.Throwable: addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, setStackTrace, toString. Methods inherited from class java.lang.Object: clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait." }, { "code": null, "e": 25290, "s": 25080, "text": "Methods inherited from class java.lang.Throwable: addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, setStackTrace, toString. " }, { "code": null, "e": 25407, "s": 25290, "text": "Methods inherited from class java.lang.Object: clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait." }, { "code": null, "e": 25443, "s": 25407, "text": "HIERARCHY OF java.net.BindException" }, { "code": null, "e": 25452, "s": 25443, "text": "Example:" }, { "code": null, "e": 25550, "s": 25452, "text": "In the example below, we have created a class Ex_BindException to demonstrate the BindException :" }, { "code": null, "e": 25555, "s": 25550, "text": "Java" }, { "code": "// java.net.BindException in Java with Examples import java.io.*;import java.net.*;public class Ex_BindException { // Creating a variable PORT1 with arbitrary port value private final static int PORT1 = 8000; public static void main(String[] args) throws IOException { // Creating instance of the ServerSocket class // and binding it to the arbitrary port ServerSocket socket1 = new ServerSocket(PORT1); // Creating another instance of the ServerSocket // class and binding it to the same arbitrary // port,thus it gives a BindException. ServerSocket socket2 = new ServerSocket(PORT1); socket1.close(); socket2.close(); }}", "e": 26272, "s": 25555, "text": null }, { "code": null, "e": 26280, "s": 26272, "text": "Output:" }, { "code": null, "e": 26682, "s": 26280, "text": "In the above code, we first created an instance of the ServerSocket class using the specified port. That instance is successfully bound. However, when on the creation of another instance using the same port, a BindException occurs as the port is already bound to the other Socket. Here, we can simply use another arbitrary port (which is not in use) for the second socket to get rid of this exception." }, { "code": null, "e": 26698, "s": 26682, "text": "Java-Exceptions" }, { "code": null, "e": 26705, "s": 26698, "text": "Picked" }, { "code": null, "e": 26729, "s": 26705, "text": "Technical Scripter 2020" }, { "code": null, "e": 26734, "s": 26729, "text": "Java" }, { "code": null, "e": 26753, "s": 26734, "text": "Technical Scripter" }, { "code": null, "e": 26758, "s": 26753, "text": "Java" }, { "code": null, "e": 26856, "s": 26758, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26871, "s": 26856, "text": "Stream In Java" }, { "code": null, "e": 26917, "s": 26871, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26938, "s": 26917, "text": "Constructors in Java" }, { "code": null, "e": 26957, "s": 26938, "text": "Exceptions in Java" }, { "code": null, "e": 26987, "s": 26957, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27004, "s": 26987, "text": "Generics in Java" }, { "code": null, "e": 27047, "s": 27004, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27076, "s": 27047, "text": "HashMap get() Method in Java" }, { "code": null, "e": 27097, "s": 27076, "text": "Introduction to Java" } ]
Data to Text generation with T5; Building a simple yet advanced NLG model | by Mathew Alexander | Towards Data Science
The Data to text generation capability of NLG models is something that I have been exploring since the inception of sequence to sequence models in the field of NLP. The earlier attempts to tackle this problem were not showing any promising results. The non- ML Rule-based approaches like simple NLG did not seem to scale well as they require a well-formatted input and can only perform tasks such as changing the tense of the sentence. But in the age of language models, where new variants of transformers are getting released every two weeks, a task like this is not a far-fetched dream anymore. In this blog, I will discuss how I approached the Data-to-text generation problem with advanced deep learning models. The openAI GPT-2 seemed like a good option as it had compelling text generation capabilities. But training it on the web NLG 2017 data didn’t get me anywhere. The model didn’t converge at all. The conditional, as well as the unconditional text generation capabilities of GPT-2, are reasonably good, but you would hardly find a business use case that can be addressed with these tasks. Furthermore, finetuning them on the domain-specific data at times resulted in the generation of the sentences which were out of context With openAI(Not so open) not releasing the code of GPT-3, I was left with second best in the series, which is T5. Google’s T5 is a Text-To-Text Transfer Transformer which is a shared NLP framework where all NLP tasks are reframed into a unified text-to-text-format where the input and output are always text strings. It is quite different from the BERT-style models that can only output either a class label or a span of the input. The T5 allows us to use the same model along with the loss function and hyperparameters on any NLP task. I used the data of the RDF-to-text generation task from WebNLG Challenge 2020 to train the T5. Given the four RDF triples shown in (a), the aim is to generate a text such as (b) (a) Set of RDF triples (b) English text Trane, which was founded on January 1st, 1913 in La Crosse, Wisconsin, is based in Ireland. It has 29,000 employees. To preprocess the data, one can make use of The XML WebNLG data reader in Python here, or use the xml.etree.ElementTree module as given in the code below. (I ended up using the latter as I was too ignorant to read the entire challenge documentation 😐) In the code, you can see that we keep the normal triplets as it is and join multiple triplets with “&&”.It can be thought of as a separator when multiple rows of a table are fed into the model at once. As always, google’s TensorFlow implementation being really tough to interpret, I went ahead with the hugging face’s PyTorch implementation and chose the T5 base model. The entire model training was performed in google colab. Installing the transformer library !pip install transformers Importing the required modules import pandas as pdimport torchfrom transformers import T5Tokenizer, T5ForConditionalGeneration,Adafactor Load the preprocessed data and randomly shuffle the rows to have triplets with different lengths (1 triplet to 7triplets) distributed across the data frame and hence to generalize the loss quickly.Trimming off a few data points and so that a batch would not leave any remainder, hence some lines of codes can be avoided (Okay, this might be a hackish way of doing it ). train_df=pd.read_csv(‘webNLG2020_train.csv’, index_col=[0])train_df=train_df.iloc[ :35000,:]train_df=train_df.sample(frac = 1)batch_size=8num_of_batches=len(train_df)/batch_size Detecting the GPU. if torch.cuda.is_available(): dev = torch.device("cuda:0") print("Running on the GPU")else: dev = torch.device("cpu") print("Running on the CPU") Loading the pre-trained models, tokenizers, and moving the model into GPU. tokenizer = T5Tokenizer.from_pretrained(‘t5-base’)model = T5ForConditionalGeneration.from_pretrained(‘t5-base’, return_dict=True)#moving the model to GPUmodel.to(dev) Initiating the Adafactor optimizer with recommended T5 settings. optimizer = Adafactor(model.parameters(),lr=1e-3, eps=(1e-30, 1e-3), clip_threshold=1.0, decay_rate=-0.8, beta1=None, weight_decay=0.0, relative_step=False, scale_parameter=False, warmup_init=False) Html based progress bar. from IPython.display import HTML, displaydef progress(loss,value, max=100): return HTML(""" Batch loss :{loss} <progress value='{value}'max='{max}',style='width: 100%'>{value} </progress> """.format(loss=loss,value=value, max=max)) Now, training the model. It took me about 3–4 hours in Colab GPU to run four epochs. Serializing the model torch.save(model.state_dict(),'pytoch_model.bin') The configuration file for the t5 base model can be downloaded and placed on the same directory as the saved model. Make sure to rename it to config.json !wget https://s3.amazonaws.com/models.huggingface.co/bert/t5-base-config.json Make sure that the given path has both saved model and the configuration file. Also, remember to move the model and input tensors to GPU if you have one for performing the inference. Now let’s take a look at the generated text outputs for different inputs. We discussed how we can build an advanced NLG model that generates text from structured data. The text-to-text architecture of the T5 made it easy to feed structured data(which can be a combination of text and numerical data) into the model. I used the native PyTorch code on top of the huggingface’s transformer to fine-tune it on the WebNLG 2020 dataset. Unlike GPT-2 based text generation, here we don’t just trigger the language generation, We control it !! However, this is a basic implementation of the approach and a relatively less complex dataset is used to test the model. When the model was tested with data points with more than two triplets, it seems to be ignoring some of the information present in the data input. Further research and a lot of experimentation need to be done in order to fix this. You can find the code in this repo Feel free to ask any questions! Thank you!
[ { "code": null, "e": 769, "s": 172, "text": "The Data to text generation capability of NLG models is something that I have been exploring since the inception of sequence to sequence models in the field of NLP. The earlier attempts to tackle this problem were not showing any promising results. The non- ML Rule-based approaches like simple NLG did not seem to scale well as they require a well-formatted input and can only perform tasks such as changing the tense of the sentence. But in the age of language models, where new variants of transformers are getting released every two weeks, a task like this is not a far-fetched dream anymore." }, { "code": null, "e": 887, "s": 769, "text": "In this blog, I will discuss how I approached the Data-to-text generation problem with advanced deep learning models." }, { "code": null, "e": 1272, "s": 887, "text": "The openAI GPT-2 seemed like a good option as it had compelling text generation capabilities. But training it on the web NLG 2017 data didn’t get me anywhere. The model didn’t converge at all. The conditional, as well as the unconditional text generation capabilities of GPT-2, are reasonably good, but you would hardly find a business use case that can be addressed with these tasks." }, { "code": null, "e": 1408, "s": 1272, "text": "Furthermore, finetuning them on the domain-specific data at times resulted in the generation of the sentences which were out of context" }, { "code": null, "e": 1522, "s": 1408, "text": "With openAI(Not so open) not releasing the code of GPT-3, I was left with second best in the series, which is T5." }, { "code": null, "e": 1725, "s": 1522, "text": "Google’s T5 is a Text-To-Text Transfer Transformer which is a shared NLP framework where all NLP tasks are reframed into a unified text-to-text-format where the input and output are always text strings." }, { "code": null, "e": 1945, "s": 1725, "text": "It is quite different from the BERT-style models that can only output either a class label or a span of the input. The T5 allows us to use the same model along with the loss function and hyperparameters on any NLP task." }, { "code": null, "e": 2040, "s": 1945, "text": "I used the data of the RDF-to-text generation task from WebNLG Challenge 2020 to train the T5." }, { "code": null, "e": 2123, "s": 2040, "text": "Given the four RDF triples shown in (a), the aim is to generate a text such as (b)" }, { "code": null, "e": 2146, "s": 2123, "text": "(a) Set of RDF triples" }, { "code": null, "e": 2163, "s": 2146, "text": "(b) English text" }, { "code": null, "e": 2280, "s": 2163, "text": "Trane, which was founded on January 1st, 1913 in La Crosse, Wisconsin, is based in Ireland. It has 29,000 employees." }, { "code": null, "e": 2532, "s": 2280, "text": "To preprocess the data, one can make use of The XML WebNLG data reader in Python here, or use the xml.etree.ElementTree module as given in the code below. (I ended up using the latter as I was too ignorant to read the entire challenge documentation 😐)" }, { "code": null, "e": 2734, "s": 2532, "text": "In the code, you can see that we keep the normal triplets as it is and join multiple triplets with “&&”.It can be thought of as a separator when multiple rows of a table are fed into the model at once." }, { "code": null, "e": 2959, "s": 2734, "text": "As always, google’s TensorFlow implementation being really tough to interpret, I went ahead with the hugging face’s PyTorch implementation and chose the T5 base model. The entire model training was performed in google colab." }, { "code": null, "e": 2994, "s": 2959, "text": "Installing the transformer library" }, { "code": null, "e": 3020, "s": 2994, "text": "!pip install transformers" }, { "code": null, "e": 3051, "s": 3020, "text": "Importing the required modules" }, { "code": null, "e": 3157, "s": 3051, "text": "import pandas as pdimport torchfrom transformers import T5Tokenizer, T5ForConditionalGeneration,Adafactor" }, { "code": null, "e": 3527, "s": 3157, "text": "Load the preprocessed data and randomly shuffle the rows to have triplets with different lengths (1 triplet to 7triplets) distributed across the data frame and hence to generalize the loss quickly.Trimming off a few data points and so that a batch would not leave any remainder, hence some lines of codes can be avoided (Okay, this might be a hackish way of doing it )." }, { "code": null, "e": 3706, "s": 3527, "text": "train_df=pd.read_csv(‘webNLG2020_train.csv’, index_col=[0])train_df=train_df.iloc[ :35000,:]train_df=train_df.sample(frac = 1)batch_size=8num_of_batches=len(train_df)/batch_size" }, { "code": null, "e": 3725, "s": 3706, "text": "Detecting the GPU." }, { "code": null, "e": 3879, "s": 3725, "text": "if torch.cuda.is_available(): dev = torch.device(\"cuda:0\") print(\"Running on the GPU\")else: dev = torch.device(\"cpu\") print(\"Running on the CPU\")" }, { "code": null, "e": 3954, "s": 3879, "text": "Loading the pre-trained models, tokenizers, and moving the model into GPU." }, { "code": null, "e": 4165, "s": 3954, "text": "tokenizer = T5Tokenizer.from_pretrained(‘t5-base’)model = T5ForConditionalGeneration.from_pretrained(‘t5-base’, return_dict=True)#moving the model to GPUmodel.to(dev)" }, { "code": null, "e": 4230, "s": 4165, "text": "Initiating the Adafactor optimizer with recommended T5 settings." }, { "code": null, "e": 4597, "s": 4230, "text": "optimizer = Adafactor(model.parameters(),lr=1e-3, eps=(1e-30, 1e-3), clip_threshold=1.0, decay_rate=-0.8, beta1=None, weight_decay=0.0, relative_step=False, scale_parameter=False, warmup_init=False)" }, { "code": null, "e": 4622, "s": 4597, "text": "Html based progress bar." }, { "code": null, "e": 4879, "s": 4622, "text": "from IPython.display import HTML, displaydef progress(loss,value, max=100): return HTML(\"\"\" Batch loss :{loss} <progress value='{value}'max='{max}',style='width: 100%'>{value} </progress> \"\"\".format(loss=loss,value=value, max=max))" }, { "code": null, "e": 4904, "s": 4879, "text": "Now, training the model." }, { "code": null, "e": 4964, "s": 4904, "text": "It took me about 3–4 hours in Colab GPU to run four epochs." }, { "code": null, "e": 4986, "s": 4964, "text": "Serializing the model" }, { "code": null, "e": 5036, "s": 4986, "text": "torch.save(model.state_dict(),'pytoch_model.bin')" }, { "code": null, "e": 5190, "s": 5036, "text": "The configuration file for the t5 base model can be downloaded and placed on the same directory as the saved model. Make sure to rename it to config.json" }, { "code": null, "e": 5268, "s": 5190, "text": "!wget https://s3.amazonaws.com/models.huggingface.co/bert/t5-base-config.json" }, { "code": null, "e": 5451, "s": 5268, "text": "Make sure that the given path has both saved model and the configuration file. Also, remember to move the model and input tensors to GPU if you have one for performing the inference." }, { "code": null, "e": 5525, "s": 5451, "text": "Now let’s take a look at the generated text outputs for different inputs." }, { "code": null, "e": 5882, "s": 5525, "text": "We discussed how we can build an advanced NLG model that generates text from structured data. The text-to-text architecture of the T5 made it easy to feed structured data(which can be a combination of text and numerical data) into the model. I used the native PyTorch code on top of the huggingface’s transformer to fine-tune it on the WebNLG 2020 dataset." }, { "code": null, "e": 5987, "s": 5882, "text": "Unlike GPT-2 based text generation, here we don’t just trigger the language generation, We control it !!" }, { "code": null, "e": 6339, "s": 5987, "text": "However, this is a basic implementation of the approach and a relatively less complex dataset is used to test the model. When the model was tested with data points with more than two triplets, it seems to be ignoring some of the information present in the data input. Further research and a lot of experimentation need to be done in order to fix this." }, { "code": null, "e": 6374, "s": 6339, "text": "You can find the code in this repo" } ]
How to Manipulate a Pandas Dataframe in SQL | by Angelica Lo Duca | Towards Data Science
In this tutorial, I illustrate some tricks to manipulate a Python Pandas Dataframe, using SQL queries. In details, I cover the following topic: Missing Values (removal and replacement) Dataframe Ordering Dropping Duplicates Merge two Dataframe (Union and Intersection) In order to query a Pandas Dataframe through SQL queries, I exploit the sqldf Python library, which can be installed through the following command: pip install sqldf. I import the pandas library and I read a simple dataset, which contains for each country, its capital and a generic field, called Value. import pandas as pddf = pd.read_csv('../../Datasets/capitals1.csv')df.head() Now I import the sqldf library. import sqldf Missing values are values not availabale in the dataset. For example, a missing value could be indicated as NULL, None or NaN. Different strategies could be adopted to deal with missing values. In this tutorial, I illustrate two techniques: drop missing values replace missing values. Dropping missing values involves removing all the rows with a missing value for a certain column. In our sample dataset, row with index 3 has a missing value. I define a query which selects only the rows where the Value column is not null: query = """SELECT *FROM dfWHERE Value IS NOT NULL;""" Now I can run the query through the run() function. The run() function returns a new dataframe if the query contains a SELECT statement. Instead, if the query contains an UPDATE statement, the original dataframe is updated. sqldf.run(query) Another strategy to deal with missing values involves replacing them with a fixed value. For example, the fixed value could be the average value. To the best of my knowledge, the sqldf library does not support nested queries, thus I must run two separate queries, one to retrieve the average value and the other to replace missing values. Firstly, I calculate the average value of the column Value: query = """SELECT AVG(Value) as AVGFROM df"""avg = sqldf.run(query)['AVG'][0] And then I update the dataset: query = """UPDATE dfSET Value = {}WHERE Value IS NULL;"""sqldf.run(query.format(avg))df.head() It may happen that to build a final visualisation, a dataframe must be ordered. Thus, I can exploit the ORDER BY statement, provided by SQL: query = """SELECT *FROM dfORDER BY Value DESC;"""sqldf.run(query) The power of SQL could be also used to drop duplicates. This can be achieved by building a query, which selects distinct columns: query = """SELECT DISTINCT Country, Capital, ValueFROM df;"""sqldf.run(query) Dataset Merging involves combining two dataframes. SQL is a very powerful method to merge datasets without difficulties. The result of a union operation between two dataframes contains all the rows of both datasets. In order to perform union, I load an additional dataframe, df2, called capitals2., which is similar to the previous one. The additional dataframe df2 contains only one overlapping row with df. df2 = pd.read_csv('../../Datasets/capitals2.csv')df2.head(len(df2)) The union of the two dataframes can be achieved through the following query: query = """SELECT Country, Capital, Value FROM dfUNIONSELECT Country, Capital, Value FROM df2ORDER BY Value DESC"""sqldf.run(query) Note that duplicates have been removed by the union operation. Intersection of two dataframes takes only rows contained in both dataframes. In SQL, intersection can be performed through the INNER JOIN operation: query = """SELECT *FROM dfINNER JOIN df2 ON df.Country = df2.Country AND df.Capital = df2.Capital;"""sqldf.run(query) In this tutorial, I have illustrated some tricks to run SQL queries on a Pandas Dataframe. I have described only some examples of queries, but your fantasy will be truly much more creative than mine! The full code of this tutorial can be downloaded from my Github repository. If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and Github.
[ { "code": null, "e": 315, "s": 171, "text": "In this tutorial, I illustrate some tricks to manipulate a Python Pandas Dataframe, using SQL queries. In details, I cover the following topic:" }, { "code": null, "e": 356, "s": 315, "text": "Missing Values (removal and replacement)" }, { "code": null, "e": 375, "s": 356, "text": "Dataframe Ordering" }, { "code": null, "e": 395, "s": 375, "text": "Dropping Duplicates" }, { "code": null, "e": 440, "s": 395, "text": "Merge two Dataframe (Union and Intersection)" }, { "code": null, "e": 607, "s": 440, "text": "In order to query a Pandas Dataframe through SQL queries, I exploit the sqldf Python library, which can be installed through the following command: pip install sqldf." }, { "code": null, "e": 744, "s": 607, "text": "I import the pandas library and I read a simple dataset, which contains for each country, its capital and a generic field, called Value." }, { "code": null, "e": 821, "s": 744, "text": "import pandas as pddf = pd.read_csv('../../Datasets/capitals1.csv')df.head()" }, { "code": null, "e": 853, "s": 821, "text": "Now I import the sqldf library." }, { "code": null, "e": 866, "s": 853, "text": "import sqldf" }, { "code": null, "e": 1107, "s": 866, "text": "Missing values are values not availabale in the dataset. For example, a missing value could be indicated as NULL, None or NaN. Different strategies could be adopted to deal with missing values. In this tutorial, I illustrate two techniques:" }, { "code": null, "e": 1127, "s": 1107, "text": "drop missing values" }, { "code": null, "e": 1151, "s": 1127, "text": "replace missing values." }, { "code": null, "e": 1310, "s": 1151, "text": "Dropping missing values involves removing all the rows with a missing value for a certain column. In our sample dataset, row with index 3 has a missing value." }, { "code": null, "e": 1391, "s": 1310, "text": "I define a query which selects only the rows where the Value column is not null:" }, { "code": null, "e": 1445, "s": 1391, "text": "query = \"\"\"SELECT *FROM dfWHERE Value IS NOT NULL;\"\"\"" }, { "code": null, "e": 1497, "s": 1445, "text": "Now I can run the query through the run() function." }, { "code": null, "e": 1669, "s": 1497, "text": "The run() function returns a new dataframe if the query contains a SELECT statement. Instead, if the query contains an UPDATE statement, the original dataframe is updated." }, { "code": null, "e": 1686, "s": 1669, "text": "sqldf.run(query)" }, { "code": null, "e": 2025, "s": 1686, "text": "Another strategy to deal with missing values involves replacing them with a fixed value. For example, the fixed value could be the average value. To the best of my knowledge, the sqldf library does not support nested queries, thus I must run two separate queries, one to retrieve the average value and the other to replace missing values." }, { "code": null, "e": 2085, "s": 2025, "text": "Firstly, I calculate the average value of the column Value:" }, { "code": null, "e": 2163, "s": 2085, "text": "query = \"\"\"SELECT AVG(Value) as AVGFROM df\"\"\"avg = sqldf.run(query)['AVG'][0]" }, { "code": null, "e": 2194, "s": 2163, "text": "And then I update the dataset:" }, { "code": null, "e": 2289, "s": 2194, "text": "query = \"\"\"UPDATE dfSET Value = {}WHERE Value IS NULL;\"\"\"sqldf.run(query.format(avg))df.head()" }, { "code": null, "e": 2430, "s": 2289, "text": "It may happen that to build a final visualisation, a dataframe must be ordered. Thus, I can exploit the ORDER BY statement, provided by SQL:" }, { "code": null, "e": 2496, "s": 2430, "text": "query = \"\"\"SELECT *FROM dfORDER BY Value DESC;\"\"\"sqldf.run(query)" }, { "code": null, "e": 2626, "s": 2496, "text": "The power of SQL could be also used to drop duplicates. This can be achieved by building a query, which selects distinct columns:" }, { "code": null, "e": 2704, "s": 2626, "text": "query = \"\"\"SELECT DISTINCT Country, Capital, ValueFROM df;\"\"\"sqldf.run(query)" }, { "code": null, "e": 2825, "s": 2704, "text": "Dataset Merging involves combining two dataframes. SQL is a very powerful method to merge datasets without difficulties." }, { "code": null, "e": 3113, "s": 2825, "text": "The result of a union operation between two dataframes contains all the rows of both datasets. In order to perform union, I load an additional dataframe, df2, called capitals2., which is similar to the previous one. The additional dataframe df2 contains only one overlapping row with df." }, { "code": null, "e": 3181, "s": 3113, "text": "df2 = pd.read_csv('../../Datasets/capitals2.csv')df2.head(len(df2))" }, { "code": null, "e": 3258, "s": 3181, "text": "The union of the two dataframes can be achieved through the following query:" }, { "code": null, "e": 3390, "s": 3258, "text": "query = \"\"\"SELECT Country, Capital, Value FROM dfUNIONSELECT Country, Capital, Value FROM df2ORDER BY Value DESC\"\"\"sqldf.run(query)" }, { "code": null, "e": 3453, "s": 3390, "text": "Note that duplicates have been removed by the union operation." }, { "code": null, "e": 3602, "s": 3453, "text": "Intersection of two dataframes takes only rows contained in both dataframes. In SQL, intersection can be performed through the INNER JOIN operation:" }, { "code": null, "e": 3721, "s": 3602, "text": "query = \"\"\"SELECT *FROM dfINNER JOIN df2 ON df.Country = df2.Country AND df.Capital = df2.Capital;\"\"\"sqldf.run(query)" }, { "code": null, "e": 3921, "s": 3721, "text": "In this tutorial, I have illustrated some tricks to run SQL queries on a Pandas Dataframe. I have described only some examples of queries, but your fantasy will be truly much more creative than mine!" }, { "code": null, "e": 3997, "s": 3921, "text": "The full code of this tutorial can be downloaded from my Github repository." } ]
Python time sleep() Method
Python time method sleep() suspends execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal's catching routine. Following is the syntax for sleep() method − time.sleep(t) t − This is the number of seconds execution to be suspended. t − This is the number of seconds execution to be suspended. This method does not return any value. The following example shows the usage of sleep() method. #!/usr/bin/python import time print "Start : %s" % time.ctime() time.sleep( 5 ) print "End : %s" % time.ctime() When we run above program, it produces following result − Start : Tue Feb 17 10:19:18 2009 End : Tue Feb 17 10:19:23 2009 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": 2406, "s": 2244, "text": "Python time method sleep() suspends execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time." }, { "code": null, "e": 2573, "s": 2406, "text": "The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal's catching routine." }, { "code": null, "e": 2618, "s": 2573, "text": "Following is the syntax for sleep() method −" }, { "code": null, "e": 2633, "s": 2618, "text": "time.sleep(t)\n" }, { "code": null, "e": 2694, "s": 2633, "text": "t − This is the number of seconds execution to be suspended." }, { "code": null, "e": 2755, "s": 2694, "text": "t − This is the number of seconds execution to be suspended." }, { "code": null, "e": 2794, "s": 2755, "text": "This method does not return any value." }, { "code": null, "e": 2851, "s": 2794, "text": "The following example shows the usage of sleep() method." }, { "code": null, "e": 2964, "s": 2851, "text": "#!/usr/bin/python\nimport time\n\nprint \"Start : %s\" % time.ctime()\ntime.sleep( 5 )\nprint \"End : %s\" % time.ctime()" }, { "code": null, "e": 3022, "s": 2964, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 3087, "s": 3022, "text": "Start : Tue Feb 17 10:19:18 2009\nEnd : Tue Feb 17 10:19:23 2009\n" }, { "code": null, "e": 3124, "s": 3087, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3140, "s": 3124, "text": " Malhar Lathkar" }, { "code": null, "e": 3173, "s": 3140, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3192, "s": 3173, "text": " Arnab Chakraborty" }, { "code": null, "e": 3227, "s": 3192, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3249, "s": 3227, "text": " In28Minutes Official" }, { "code": null, "e": 3283, "s": 3249, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3311, "s": 3283, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3346, "s": 3311, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3360, "s": 3346, "text": " Lets Kode It" }, { "code": null, "e": 3393, "s": 3360, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3410, "s": 3393, "text": " Abhilash Nelson" }, { "code": null, "e": 3417, "s": 3410, "text": " Print" }, { "code": null, "e": 3428, "s": 3417, "text": " Add Notes" } ]
SQL Tryit Editor v1.6
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country ORDER BY COUNT(CustomerID) DESC; ​ 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": 34, "s": 0, "text": "SELECT COUNT(CustomerID), Country" }, { "code": null, "e": 49, "s": 34, "text": "FROM Customers" }, { "code": null, "e": 66, "s": 49, "text": "GROUP BY Country" }, { "code": null, "e": 99, "s": 66, "text": "ORDER BY COUNT(CustomerID) DESC;" }, { "code": null, "e": 101, "s": 99, "text": "​" }, { "code": null, "e": 164, "s": 101, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 224, "s": 164, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 292, "s": 224, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 330, "s": 292, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 415, "s": 330, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 589, "s": 415, "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": 640, "s": 589, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 708, "s": 640, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 879, "s": 708, "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": 979, "s": 879, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 1039, "s": 979, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
Kotlin list : listOf()
02 Jul, 2021 A list is a generic ordered collection of elements. Kotlin has two types of lists, immutable lists (cannot be modified) and mutable lists (can be modified). Read-only lists are created with listOf() whose elements can not be modified and mutable lists created with mutableListOf() method where we alter or modify the elements of the list.Kotlin program of list contains Integers – Java fun main(args: Array<String>) { val a = listOf('1', '2', '3') println(a.size) println(a.indexOf('2')) println(a[2])} Output: 3 1 3 Kotlin program of list contains Strings – Java fun main(args: Array<String>) { //creating list of strings val a = listOf("Ram", "Shyam", "Raja", "Rani") println("The size of the list is: "+a.size) println("The index of the element Raja is: "+a.indexOf("Raja")) println("The element at index "+a[2]) for(i in a.indices){ println(a[i]) }} Output: The size of the list is: 4 The index of the element Raja is: 2 The element at index Raja Ram Shyam Raja Rani Each element of a list has an index. The first element has an index of zero (0) and the last Element has index len – 1, where ‘len’ is the length of the list. Java fun main(args: Array<String>){ val numbers = listOf(1, 5, 7, 32, 0, 21, 1, 6, 10) val num1 = numbers.get(0) println(num1) val num2 = numbers[7] println(num2) val index1 = numbers.indexOf(1) println("The first index of number is $index1") val index2 = numbers.lastIndexOf(1) println("The last index of number is $index2") val index3 = numbers.lastIndex println("The last index of the list is $index3")} Output: 1 6 The first index of number is 0 The last index of number is 6 The last index of the list is 8 We can retrieve the first and the last elements of the list without using the get() method. Considering the previous example, if we include the following code after line no. 17 Java fun main(args: Array<String>){ val numbers = listOf(1, 5, 7, 32, 0, 21, 1, 6, 10) println(numbers.first()) println(numbers.last())} Output: 1 10 It is process of accessing the elements of list one by one. There are several ways of doing this in Kotlin. Java fun main(args: Array<String>){ val names = listOf("Gopal", "Asad", "Shubham", "Aditya", "Devarsh", "Nikhil", "Gagan") // method 1 for (name in names) { print("$name, ") } println() // method 2 for (i in 0 until names.size) { print("${names[i]} ") } println() // method 3 names.forEachIndexed({i, j -> println("names[$i] = $j")}) // method 4 val it: ListIterator<String> = names.listIterator() while (it.hasNext()) { val i = it.next() print("$i ") } println()} Output: Gopal, Asad, Shubham, Aditya, Devarsh, Nikhil, Gagan, Gopal Asad Shubham Aditya Devarsh Nikhil Gagan names[0] = Gopal names[1] = Asad names[2] = Shubham names[3] = Aditya names[4] = Devarsh names[5] = Nikhil names[6] = Gagan Gopal Asad Shubham Aditya Devarsh Nikhil Gagan Explanation: for (name in names) { print("$name, ") } The for loop traverses the list. In each cycle, the variable ‘name’ points to the next element in the list. for (i in 0 until names.size) { print("${names[i]} ") } This method uses the size of the list. The until keyword creates a range of the list indexes. names.forEachIndexed({i, j -> println("namess[$i] = $j")}) With the forEachIndexed() method, we loop over the list having index and value available in each iteration. val it: ListIterator = names.listIterator() while (it.hasNext()) { val i = it.next() print("$i ") } Here we use a ListIterator to iterate through the list. The following example show how to sort a list in ascending or descending order. Java fun main(args: Array<String>){ val list = listOf(8, 4, 7, 1, 2, 3, 0, 5, 6 ) val asc = list.sorted() println(asc) val desc = list.sortedDescending() println(desc)} Output: [0, 1, 2, 3, 4, 5, 6, 7, 8] [8, 7, 6, 5, 4, 3, 2, 1, 0] Explanation: val asc = list.sorted() The sorted() method sorts the list in ascending order. val desc = list.sortedDescending() The sortedDescending() method sorts the list in descending order. This method checks whether an element exists in the list or not. Java fun main(args: Array<String>){ val list = listOf(8, 4, 7, 1, 2, 3, 0, 5, 6 ) val res = list.contains(0) if (res) println("The list contains 0") else println("The list does not contain 0") val result = list.containsAll(listOf(3, -1)) if (result) println("The list contains 3 and -1") else println("The list does not contain 3 and -1")} Output: The list contains 0 The list does not contain 3 and -1 Explanation: val res = list.contains(0) Checks whether the list contains 0 or not and returns true or false (her true) that is stored in res. val result = list.containsAll(listOf(3, -1)) Checks whether the list contains 3 and -1 or not. simranarora5sos Kotlin Collections Picked Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Jul, 2021" }, { "code": null, "e": 435, "s": 52, "text": "A list is a generic ordered collection of elements. Kotlin has two types of lists, immutable lists (cannot be modified) and mutable lists (can be modified). Read-only lists are created with listOf() whose elements can not be modified and mutable lists created with mutableListOf() method where we alter or modify the elements of the list.Kotlin program of list contains Integers – " }, { "code": null, "e": 440, "s": 435, "text": "Java" }, { "code": "fun main(args: Array<String>) { val a = listOf('1', '2', '3') println(a.size) println(a.indexOf('2')) println(a[2])}", "e": 569, "s": 440, "text": null }, { "code": null, "e": 579, "s": 569, "text": "Output: " }, { "code": null, "e": 585, "s": 579, "text": "3\n1\n3" }, { "code": null, "e": 629, "s": 585, "text": "Kotlin program of list contains Strings – " }, { "code": null, "e": 634, "s": 629, "text": "Java" }, { "code": "fun main(args: Array<String>) { //creating list of strings val a = listOf(\"Ram\", \"Shyam\", \"Raja\", \"Rani\") println(\"The size of the list is: \"+a.size) println(\"The index of the element Raja is: \"+a.indexOf(\"Raja\")) println(\"The element at index \"+a[2]) for(i in a.indices){ println(a[i]) }}", "e": 952, "s": 634, "text": null }, { "code": null, "e": 962, "s": 952, "text": "Output: " }, { "code": null, "e": 1071, "s": 962, "text": "The size of the list is: 4\nThe index of the element Raja is: 2\nThe element at index Raja\nRam\nShyam\nRaja\nRani" }, { "code": null, "e": 1234, "s": 1073, "text": "Each element of a list has an index. The first element has an index of zero (0) and the last Element has index len – 1, where ‘len’ is the length of the list. " }, { "code": null, "e": 1239, "s": 1234, "text": "Java" }, { "code": "fun main(args: Array<String>){ val numbers = listOf(1, 5, 7, 32, 0, 21, 1, 6, 10) val num1 = numbers.get(0) println(num1) val num2 = numbers[7] println(num2) val index1 = numbers.indexOf(1) println(\"The first index of number is $index1\") val index2 = numbers.lastIndexOf(1) println(\"The last index of number is $index2\") val index3 = numbers.lastIndex println(\"The last index of the list is $index3\")}", "e": 1679, "s": 1239, "text": null }, { "code": null, "e": 1689, "s": 1679, "text": "Output: " }, { "code": null, "e": 1786, "s": 1689, "text": "1\n6\nThe first index of number is 0\nThe last index of number is 6\nThe last index of the list is 8" }, { "code": null, "e": 1967, "s": 1788, "text": "We can retrieve the first and the last elements of the list without using the get() method. Considering the previous example, if we include the following code after line no. 17 " }, { "code": null, "e": 1972, "s": 1967, "text": "Java" }, { "code": "fun main(args: Array<String>){ val numbers = listOf(1, 5, 7, 32, 0, 21, 1, 6, 10) println(numbers.first()) println(numbers.last())}", "e": 2113, "s": 1972, "text": null }, { "code": null, "e": 2123, "s": 2113, "text": "Output: " }, { "code": null, "e": 2128, "s": 2123, "text": "1\n10" }, { "code": null, "e": 2239, "s": 2130, "text": "It is process of accessing the elements of list one by one. There are several ways of doing this in Kotlin. " }, { "code": null, "e": 2244, "s": 2239, "text": "Java" }, { "code": "fun main(args: Array<String>){ val names = listOf(\"Gopal\", \"Asad\", \"Shubham\", \"Aditya\", \"Devarsh\", \"Nikhil\", \"Gagan\") // method 1 for (name in names) { print(\"$name, \") } println() // method 2 for (i in 0 until names.size) { print(\"${names[i]} \") } println() // method 3 names.forEachIndexed({i, j -> println(\"names[$i] = $j\")}) // method 4 val it: ListIterator<String> = names.listIterator() while (it.hasNext()) { val i = it.next() print(\"$i \") } println()}", "e": 2798, "s": 2244, "text": null }, { "code": null, "e": 2808, "s": 2798, "text": "Output: " }, { "code": null, "e": 3083, "s": 2808, "text": "Gopal, Asad, Shubham, Aditya, Devarsh, Nikhil, Gagan, \nGopal Asad Shubham Aditya Devarsh Nikhil Gagan \nnames[0] = Gopal\nnames[1] = Asad\nnames[2] = Shubham\nnames[3] = Aditya\nnames[4] = Devarsh\nnames[5] = Nikhil\nnames[6] = Gagan\nGopal Asad Shubham Aditya Devarsh Nikhil Gagan " }, { "code": null, "e": 3098, "s": 3083, "text": "Explanation: " }, { "code": null, "e": 3152, "s": 3098, "text": "for (name in names) {\n\n print(\"$name, \")\n }" }, { "code": null, "e": 3262, "s": 3152, "text": "The for loop traverses the list. In each cycle, the variable ‘name’ points to the next element in the list. " }, { "code": null, "e": 3331, "s": 3262, "text": "for (i in 0 until names.size) {\n\n print(\"${names[i]} \")\n }" }, { "code": null, "e": 3426, "s": 3331, "text": "This method uses the size of the list. The until keyword creates a range of the list indexes. " }, { "code": null, "e": 3485, "s": 3426, "text": "names.forEachIndexed({i, j -> println(\"namess[$i] = $j\")})" }, { "code": null, "e": 3595, "s": 3485, "text": "With the forEachIndexed() method, we loop over the list having index and value available in each iteration. " }, { "code": null, "e": 3721, "s": 3595, "text": "val it: ListIterator = names.listIterator()\n\n while (it.hasNext()) {\n\n val i = it.next()\n print(\"$i \")\n }" }, { "code": null, "e": 3778, "s": 3721, "text": "Here we use a ListIterator to iterate through the list. " }, { "code": null, "e": 3860, "s": 3778, "text": "The following example show how to sort a list in ascending or descending order. " }, { "code": null, "e": 3865, "s": 3860, "text": "Java" }, { "code": "fun main(args: Array<String>){ val list = listOf(8, 4, 7, 1, 2, 3, 0, 5, 6 ) val asc = list.sorted() println(asc) val desc = list.sortedDescending() println(desc)}", "e": 4046, "s": 3865, "text": null }, { "code": null, "e": 4056, "s": 4046, "text": "Output: " }, { "code": null, "e": 4112, "s": 4056, "text": "[0, 1, 2, 3, 4, 5, 6, 7, 8]\n[8, 7, 6, 5, 4, 3, 2, 1, 0]" }, { "code": null, "e": 4127, "s": 4112, "text": "Explanation: " }, { "code": null, "e": 4151, "s": 4127, "text": "val asc = list.sorted()" }, { "code": null, "e": 4208, "s": 4151, "text": "The sorted() method sorts the list in ascending order. " }, { "code": null, "e": 4243, "s": 4208, "text": "val desc = list.sortedDescending()" }, { "code": null, "e": 4310, "s": 4243, "text": "The sortedDescending() method sorts the list in descending order. " }, { "code": null, "e": 4377, "s": 4310, "text": "This method checks whether an element exists in the list or not. " }, { "code": null, "e": 4382, "s": 4377, "text": "Java" }, { "code": "fun main(args: Array<String>){ val list = listOf(8, 4, 7, 1, 2, 3, 0, 5, 6 ) val res = list.contains(0) if (res) println(\"The list contains 0\") else println(\"The list does not contain 0\") val result = list.containsAll(listOf(3, -1)) if (result) println(\"The list contains 3 and -1\") else println(\"The list does not contain 3 and -1\")}", "e": 4770, "s": 4382, "text": null }, { "code": null, "e": 4780, "s": 4770, "text": "Output: " }, { "code": null, "e": 4835, "s": 4780, "text": "The list contains 0\nThe list does not contain 3 and -1" }, { "code": null, "e": 4849, "s": 4835, "text": "Explanation: " }, { "code": null, "e": 4876, "s": 4849, "text": "val res = list.contains(0)" }, { "code": null, "e": 4980, "s": 4876, "text": "Checks whether the list contains 0 or not and returns true or false (her true) that is stored in res. " }, { "code": null, "e": 5026, "s": 4980, "text": " val result = list.containsAll(listOf(3, -1))" }, { "code": null, "e": 5077, "s": 5026, "text": "Checks whether the list contains 3 and -1 or not. " }, { "code": null, "e": 5093, "s": 5077, "text": "simranarora5sos" }, { "code": null, "e": 5112, "s": 5093, "text": "Kotlin Collections" }, { "code": null, "e": 5119, "s": 5112, "text": "Picked" }, { "code": null, "e": 5126, "s": 5119, "text": "Kotlin" } ]
PySpark Count Distinct from DataFrame
06 Apr, 2022 In this article, we will discuss how to count distinct values present in the Pyspark DataFrame. In Pyspark, there are two ways to get the count of distinct values. We can use distinct() and count() functions of DataFrame to get the count distinct of PySpark DataFrame. Another way is to use SQL countDistinct() function which will provide the distinct value count of all the selected columns. Let’s understand both the ways to count distinct from DataFrame with examples. The distinct and count are the two different functions that can be applied to DataFrames. distinct() will eliminate all the duplicate values or records by checking all columns of a Row from DataFrame and count() will return the count of records on DataFrame. By chaining these two functions one after the other we can get the count distinct of PySpark DataFrame. Example 1: Pyspark Count Distinct from DataFrame using distinct().count() In this example, we will create a DataFrame df which contains Student details like Name, Course, and Marks. The DataFrame contains some duplicate values also. And we will apply the distinct().count() to find out all the distinct values count present in the DataFrame df. Python3 # importing moduleimport pyspark # importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving# app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # giving rows value for dataframedata = [("Ram", "MCA", 80), ("Riya", "MBA", 85), ("Jiya", "B.E", 60), ("Maria", "B.Tech", 65), ("Shreya", "B.sc", 91), ("Ram", "MCA", 80), ("John", "M.E", 85), ("Shyam", "BA", 70), ("Kumar", "B.sc", 78), ("Maria", "B.Tech", 65)] # giving column names of dataframecolumns = ["Name", "Course", "Marks"] # creating a dataframe dfdf = spark.createDataFrame(data, columns) # show dfdf.show() # counting the total number of values# in dfprint("Total number of records in df:", df.count()) Output: This is the DataFrame df that we have created, and it contains total of 10 records. Now, we apply distinct().count() to find out the total distinct value count present in the DataFrame df. Python3 # applying distinct().count() on dfprint('Distinct count in DataFrame df is :', df.distinct().count()) Output: Distinct count in DataFrame df is : 8 In this output, we can see that there are 8 distinct values present in the DataFrame df. This function provides the count of distinct elements present in a group of selected columns. countDistinct() is an SQL function that will provide the distinct value count of all the selected columns. Example 1: Pyspark Count Distinct from DataFrame using countDistinct(). In this example, we will create a DataFrame df that contains employee details like Emp_name, Department, and Salary. The DataFrame contains some duplicate values also. And we will apply the countDistinct() to find out all the distinct values count present in the DataFrame df. Python3 # importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving# app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # giving rows value for dataframedata = [("Ram", "IT", 80000), ("Shyam", "Sales", 70000), ("Jiya", "Sales", 60000), ("Maria", "Accounts", 65000), ("Ramesh", "IT", 80000), ("John", "Management", 80000), ("Shyam", "Sales", 70000), ("Kumar", "Sales", 78000), ("Maria", "Accounts", 65000)] # giving column names of dataframecolumns = ["Emp_name", "Depart", "Salary"] # creating a dataframe dfdf = spark.createDataFrame(data, columns) # show dfdf.show() # counting the total number of values in dfprint("Total number of records in df:", df.count()) This is the DataFrame df that we have created, and it contains total of 9 records. Now, we will apply countDistinct() to find out the total distinct value count present in the DataFrame df. To apply this function we will import the function from pyspark.sql.functions module. Python3 # importing countDistinct from# pyspark.sql.functionsfrom pyspark.sql.functions import countDistinct # applying the function countDistinct()# on df using select()df2 = df.select(countDistinct("Emp_name", "Depart", "Salary")) # show df2df2.show() Output: +----------------------------------------+ |count(DISTINCT Emp_name, Depart, Salary)| +----------------------------------------+ | 7| +----------------------------------------+ There are 7 distinct records present in DataFrame df. The countDistinct() provides the distinct count value in the column format as shown in the output as it’s an SQL function. Now, let’s see the distinct values count based on one particular column. We will count the distinct values present in the Department column of employee details df. Python3 # importing countDistinct from# pyspark.sql.functionsfrom pyspark.sql.functions import countDistinct # applying the function countDistinct()# on df using select()df3 = df.select(countDistinct("Depart")) # show df2df3.show() Output: +----------------------+ |count(DISTINCT Depart)| +----------------------+ | 4| +----------------------+ There are 4 distinct values present in the department column. In this example, we have applied countDistinct() only on Depart column. Example 2: Pyspark Count Distinct from DataFrame using SQL query. In this example, we have created a dataframe containing employee details like Emp_name, Depart, Age, and Salary. Now, we will count the distinct records in the dataframe using a simple SQL query as we use in SQL. Let’s see the example and understand it: Python3 # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # giving rows value for dataframedata = [("Ram", "IT", 44, 80000), ("Shyam", "Sales", 45, 70000), ("Jiya", "Sales", 30, 60000), ("Maria", "Accounts", 29, 65000), ("Ram", "IT", 38, 80000), ("John", "Management", 35, 80000), ("Shyam", "Sales", 45, 70000), ("Kumar", "Sales", 27, 70000), ("Maria", "Accounts", 32, 65000), ("Ria", "Management", 32, 65000)] # giving column names of dataframecolumns = ["Emp_name", "Depart", "Age", "Salary"] # creating a dataframe dfdf = spark.createDataFrame(data, columns) # show dfdf.show() # counting the total number of values in dfprint("Total number of records in df:", df.count()) Output: This is the dataframe that contains total of 10 records along with some duplicate records also. Now, we will use an SQL query and find out how many distinct records are found in this dataframe. It is as simple as we do in SQL. Python3 # creating a temporary view of# Dataframe and storing it into df2df.createOrReplaceTempView("df2") # using the SQL query to count all# distinct records and display the# count on the screenspark.sql("select count(distinct(*)) from df2").show() +---------------------------------------------+ |count(DISTINCT Emp_name, Depart, Age, Salary)| +---------------------------------------------+ | 9| +---------------------------------------------+ There are 9 distinct records found in the entire dataframe df. Now let’s find the distinct values count in two columns i.e. Emp_name and Salary using the below SQL query. Python3 # using the SQL query to count distinct# records in 2 columns only display the# count on the screenspark.sql("select count(distinct(Emp_name, Salary)) from df2").show() Output: +----------------------------------------------------------------+ |count(DISTINCT named_struct(Emp_name, Emp_name, Salary, Salary))| +----------------------------------------------------------------+ | 7| +----------------------------------------------------------------+ There are 7 distinct values found in Emp_name and Salary column. As SQL provides the output of all the operations performed on the data in the tabular format. We got the answer in the column that contains two rows, the first row has the heading, and second row contains a distinct count of records. In Example2 also got output in the same format as, countDistinct() is also an SQL function. kashishsoda Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Apr, 2022" }, { "code": null, "e": 125, "s": 28, "text": "In this article, we will discuss how to count distinct values present in the Pyspark DataFrame. " }, { "code": null, "e": 501, "s": 125, "text": "In Pyspark, there are two ways to get the count of distinct values. We can use distinct() and count() functions of DataFrame to get the count distinct of PySpark DataFrame. Another way is to use SQL countDistinct() function which will provide the distinct value count of all the selected columns. Let’s understand both the ways to count distinct from DataFrame with examples." }, { "code": null, "e": 864, "s": 501, "text": "The distinct and count are the two different functions that can be applied to DataFrames. distinct() will eliminate all the duplicate values or records by checking all columns of a Row from DataFrame and count() will return the count of records on DataFrame. By chaining these two functions one after the other we can get the count distinct of PySpark DataFrame." }, { "code": null, "e": 938, "s": 864, "text": "Example 1: Pyspark Count Distinct from DataFrame using distinct().count()" }, { "code": null, "e": 1209, "s": 938, "text": "In this example, we will create a DataFrame df which contains Student details like Name, Course, and Marks. The DataFrame contains some duplicate values also. And we will apply the distinct().count() to find out all the distinct values count present in the DataFrame df." }, { "code": null, "e": 1217, "s": 1209, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving# app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # giving rows value for dataframedata = [(\"Ram\", \"MCA\", 80), (\"Riya\", \"MBA\", 85), (\"Jiya\", \"B.E\", 60), (\"Maria\", \"B.Tech\", 65), (\"Shreya\", \"B.sc\", 91), (\"Ram\", \"MCA\", 80), (\"John\", \"M.E\", 85), (\"Shyam\", \"BA\", 70), (\"Kumar\", \"B.sc\", 78), (\"Maria\", \"B.Tech\", 65)] # giving column names of dataframecolumns = [\"Name\", \"Course\", \"Marks\"] # creating a dataframe dfdf = spark.createDataFrame(data, columns) # show dfdf.show() # counting the total number of values# in dfprint(\"Total number of records in df:\", df.count())", "e": 2021, "s": 1217, "text": null }, { "code": null, "e": 2029, "s": 2021, "text": "Output:" }, { "code": null, "e": 2218, "s": 2029, "text": "This is the DataFrame df that we have created, and it contains total of 10 records. Now, we apply distinct().count() to find out the total distinct value count present in the DataFrame df." }, { "code": null, "e": 2226, "s": 2218, "text": "Python3" }, { "code": "# applying distinct().count() on dfprint('Distinct count in DataFrame df is :', df.distinct().count())", "e": 2329, "s": 2226, "text": null }, { "code": null, "e": 2337, "s": 2329, "text": "Output:" }, { "code": null, "e": 2375, "s": 2337, "text": "Distinct count in DataFrame df is : 8" }, { "code": null, "e": 2464, "s": 2375, "text": "In this output, we can see that there are 8 distinct values present in the DataFrame df." }, { "code": null, "e": 2666, "s": 2464, "text": "This function provides the count of distinct elements present in a group of selected columns. countDistinct() is an SQL function that will provide the distinct value count of all the selected columns. " }, { "code": null, "e": 2738, "s": 2666, "text": "Example 1: Pyspark Count Distinct from DataFrame using countDistinct()." }, { "code": null, "e": 3016, "s": 2738, "text": "In this example, we will create a DataFrame df that contains employee details like Emp_name, Department, and Salary. The DataFrame contains some duplicate values also. And we will apply the countDistinct() to find out all the distinct values count present in the DataFrame df. " }, { "code": null, "e": 3024, "s": 3016, "text": "Python3" }, { "code": "# importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving# app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # giving rows value for dataframedata = [(\"Ram\", \"IT\", 80000), (\"Shyam\", \"Sales\", 70000), (\"Jiya\", \"Sales\", 60000), (\"Maria\", \"Accounts\", 65000), (\"Ramesh\", \"IT\", 80000), (\"John\", \"Management\", 80000), (\"Shyam\", \"Sales\", 70000), (\"Kumar\", \"Sales\", 78000), (\"Maria\", \"Accounts\", 65000)] # giving column names of dataframecolumns = [\"Emp_name\", \"Depart\", \"Salary\"] # creating a dataframe dfdf = spark.createDataFrame(data, columns) # show dfdf.show() # counting the total number of values in dfprint(\"Total number of records in df:\", df.count())", "e": 3816, "s": 3024, "text": null }, { "code": null, "e": 4092, "s": 3816, "text": "This is the DataFrame df that we have created, and it contains total of 9 records. Now, we will apply countDistinct() to find out the total distinct value count present in the DataFrame df. To apply this function we will import the function from pyspark.sql.functions module." }, { "code": null, "e": 4100, "s": 4092, "text": "Python3" }, { "code": "# importing countDistinct from# pyspark.sql.functionsfrom pyspark.sql.functions import countDistinct # applying the function countDistinct()# on df using select()df2 = df.select(countDistinct(\"Emp_name\", \"Depart\", \"Salary\")) # show df2df2.show()", "e": 4346, "s": 4100, "text": null }, { "code": null, "e": 4354, "s": 4346, "text": "Output:" }, { "code": null, "e": 4569, "s": 4354, "text": "+----------------------------------------+\n|count(DISTINCT Emp_name, Depart, Salary)|\n+----------------------------------------+\n| 7|\n+----------------------------------------+" }, { "code": null, "e": 4746, "s": 4569, "text": "There are 7 distinct records present in DataFrame df. The countDistinct() provides the distinct count value in the column format as shown in the output as it’s an SQL function." }, { "code": null, "e": 4910, "s": 4746, "text": "Now, let’s see the distinct values count based on one particular column. We will count the distinct values present in the Department column of employee details df." }, { "code": null, "e": 4918, "s": 4910, "text": "Python3" }, { "code": "# importing countDistinct from# pyspark.sql.functionsfrom pyspark.sql.functions import countDistinct # applying the function countDistinct()# on df using select()df3 = df.select(countDistinct(\"Depart\")) # show df2df3.show()", "e": 5142, "s": 4918, "text": null }, { "code": null, "e": 5150, "s": 5142, "text": "Output:" }, { "code": null, "e": 5275, "s": 5150, "text": "+----------------------+\n|count(DISTINCT Depart)|\n+----------------------+\n| 4|\n+----------------------+" }, { "code": null, "e": 5409, "s": 5275, "text": "There are 4 distinct values present in the department column. In this example, we have applied countDistinct() only on Depart column." }, { "code": null, "e": 5475, "s": 5409, "text": "Example 2: Pyspark Count Distinct from DataFrame using SQL query." }, { "code": null, "e": 5729, "s": 5475, "text": "In this example, we have created a dataframe containing employee details like Emp_name, Depart, Age, and Salary. Now, we will count the distinct records in the dataframe using a simple SQL query as we use in SQL. Let’s see the example and understand it:" }, { "code": null, "e": 5737, "s": 5729, "text": "Python3" }, { "code": "# importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # giving rows value for dataframedata = [(\"Ram\", \"IT\", 44, 80000), (\"Shyam\", \"Sales\", 45, 70000), (\"Jiya\", \"Sales\", 30, 60000), (\"Maria\", \"Accounts\", 29, 65000), (\"Ram\", \"IT\", 38, 80000), (\"John\", \"Management\", 35, 80000), (\"Shyam\", \"Sales\", 45, 70000), (\"Kumar\", \"Sales\", 27, 70000), (\"Maria\", \"Accounts\", 32, 65000), (\"Ria\", \"Management\", 32, 65000)] # giving column names of dataframecolumns = [\"Emp_name\", \"Depart\", \"Age\", \"Salary\"] # creating a dataframe dfdf = spark.createDataFrame(data, columns) # show dfdf.show() # counting the total number of values in dfprint(\"Total number of records in df:\", df.count())", "e": 6608, "s": 5737, "text": null }, { "code": null, "e": 6616, "s": 6608, "text": "Output:" }, { "code": null, "e": 6843, "s": 6616, "text": "This is the dataframe that contains total of 10 records along with some duplicate records also. Now, we will use an SQL query and find out how many distinct records are found in this dataframe. It is as simple as we do in SQL." }, { "code": null, "e": 6851, "s": 6843, "text": "Python3" }, { "code": "# creating a temporary view of# Dataframe and storing it into df2df.createOrReplaceTempView(\"df2\") # using the SQL query to count all# distinct records and display the# count on the screenspark.sql(\"select count(distinct(*)) from df2\").show()", "e": 7094, "s": 6851, "text": null }, { "code": null, "e": 7334, "s": 7094, "text": "+---------------------------------------------+\n|count(DISTINCT Emp_name, Depart, Age, Salary)|\n+---------------------------------------------+\n| 9|\n+---------------------------------------------+" }, { "code": null, "e": 7398, "s": 7334, "text": "There are 9 distinct records found in the entire dataframe df. " }, { "code": null, "e": 7506, "s": 7398, "text": "Now let’s find the distinct values count in two columns i.e. Emp_name and Salary using the below SQL query." }, { "code": null, "e": 7514, "s": 7506, "text": "Python3" }, { "code": "# using the SQL query to count distinct# records in 2 columns only display the# count on the screenspark.sql(\"select count(distinct(Emp_name, Salary)) from df2\").show()", "e": 7683, "s": 7514, "text": null }, { "code": null, "e": 7691, "s": 7683, "text": "Output:" }, { "code": null, "e": 8026, "s": 7691, "text": "+----------------------------------------------------------------+\n|count(DISTINCT named_struct(Emp_name, Emp_name, Salary, Salary))|\n+----------------------------------------------------------------+\n| 7|\n+----------------------------------------------------------------+" }, { "code": null, "e": 8092, "s": 8026, "text": "There are 7 distinct values found in Emp_name and Salary column. " }, { "code": null, "e": 8418, "s": 8092, "text": "As SQL provides the output of all the operations performed on the data in the tabular format. We got the answer in the column that contains two rows, the first row has the heading, and second row contains a distinct count of records. In Example2 also got output in the same format as, countDistinct() is also an SQL function." }, { "code": null, "e": 8430, "s": 8418, "text": "kashishsoda" }, { "code": null, "e": 8437, "s": 8430, "text": "Picked" }, { "code": null, "e": 8452, "s": 8437, "text": "Python-Pyspark" }, { "code": null, "e": 8459, "s": 8452, "text": "Python" } ]
Directives in JSP
16 Jun, 2022 JSP directives are the elements of a JSP source code that guide the web container on how to translate the JSP page into it’s respective servlet. Syntax : @ <%@ directive attribute = "value"%> Directives can have a number of attributes which you can list down as key-value pairs and separated by commas. The blanks between the @ symbol and the directive name, and between the last attribute and the closing %>, are optional. Different types of JSP directives : There are three different JSP directives available. They are as follows: Page Directives : JSP page directive is used to define the properties applying the JSP page, such as the size of the allocated buffer, imported packages and classes/interfaces, defining what type of page it is etc. The syntax of JSP page directive is as follows: <%@page attribute = "value"%> Different properties/attributes : The following are the different properties that can be defined using page directive :import: This tells the container what packages/classes are needed to be imported into the program.Syntax: import: This tells the container what packages/classes are needed to be imported into the program.Syntax: <%@page import = "value"%> Example : html <%-- JSP code to demonstrate how to use page directive to import a package --%> <%@page import = "java.util.Date"%><%Date d = new Date();%><%=d%> Output: contentType: This defines the format of data that is being exchanged between the client and the server. It does the same thing as the setContentType method in servlet used to.Syntax: <%@page contentType="value"%> Usage Example: html <%-- JSP code to demonstrate how to usepage directive to set the type of content --%> <%@page contentType = "text/html" %><% = "This is sparta" %> Output : info: Defines the string which can be printed using the ‘getServletInfo()’ method.Syntax: <%@page info="value"%> Usage Example: html <%-- JSP code to demonstrate how to use page directive to set the page information --%> <%@page contentType = "text/html" %><% = getServletInfo()%> Output: buffer: Defines the size of the buffer that is allocated for handling the JSP page. The size is defined in Kilo Bytes.Syntax: <%@page buffer = "size in kb"%> language: Defines the scripting language used in the page. By default, this attribute contains the value ‘java’. isELIgnored: This attribute tells if the page supports expression language. By default, it is set to false. If set to true, it will disable expression language.Syntax: <%@page isElIgnored = "true/false"%> Usage Example: html <%-- JSP code to demonstrate how to use pagedirective to ignore expression language --%> <%@page contentType = "text/html" %><%@page isELIgnored = "true"%><body bgcolor = "blue"><c:out value = "${'This is sparta}"/></body> Output: (blank page) errorPage: Defines which page to redirect to, in case the current page encounters an exception. Syntax: <%@page errorPage = "true/false"%> Usage Example: html //JSP code to divide two numbers<%@ page errorPage = "error.jsp" %> <% // dividing the numbersint z = 1/0; // resultout.print("division of numbers is: " + z); %> isErrorPage: It classifies whether the page is an error page or not. By classifying a page as an error page, it can use the implicit object ‘exception’ which can be used to display exceptions that have occurred.Syntax: <%@page isErrorPage="true/false"%> Usage example: html //JSP code for error page, which displays the exception<%@ page isErrorPage = "true" %> <h1>Exception caught</h1> The exception is: <% = exception %>Output: Output: Include directive : JSP include directive is used to include other files into the current jsp page. These files can be html files, other sp files etc. The advantage of using an include directive is that it allows code re-usability.The syntax of an include directive is as follows: <@%include file = "file location"%> Usage example: In the following code, we’re including the contents of an html file into a jsp page.a.html html <h1>This is the content of a.html</h1> index.jsp html <% = Local content%><%@include file = "a.html"%><% = local content%> Output : Taglib Directive : The taglib directive is used to mention the library whose custom-defined tags are being used in the JSP page. It’s major application is JSTL(JSP standard tag library). Syntax: <@%taglib uri = "library url" prefix="the prefix to identify the tags of this library with"%> Usage Example: html <%-- JSP code to demonstratetaglib directive--%><%@ taglib uri = "http://java.sun.com/jsp/jstl/core"prefix = "c" %> <c:out value = "${'This is Sparta'}"/> In the above code, we’ve used to taglib directive to point to the JSTL library which is a set of some custom-defined tags in JSP that can be used in place of the scirptlet tag (<%..%>). The prefix attribute is used to define the prefix that is used to identify the tags of this library. Here, the prefix c is used in the <c:out> tag to tell the container that this tag belongs to the library mentioned above.Output: Akanksha_Rai sooda367 jeetpurohit989 nikhatkhan11 Java-JSP Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Node.js fs.readFileSync() Method Roadmap to Learn JavaScript For Beginners How to float three div side by side using CSS? How to create footer to stay at the bottom of a Web page? Difference Between PUT and PATCH Request
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 208, "s": 52, "text": "JSP directives are the elements of a JSP source code that guide the web container on how to translate the JSP page into it’s respective servlet. Syntax : @" }, { "code": null, "e": 244, "s": 208, "text": "<%@ directive attribute = \"value\"%>" }, { "code": null, "e": 586, "s": 244, "text": "Directives can have a number of attributes which you can list down as key-value pairs and separated by commas. The blanks between the @ symbol and the directive name, and between the last attribute and the closing %>, are optional. Different types of JSP directives : There are three different JSP directives available. They are as follows: " }, { "code": null, "e": 851, "s": 586, "text": "Page Directives : JSP page directive is used to define the properties applying the JSP page, such as the size of the allocated buffer, imported packages and classes/interfaces, defining what type of page it is etc. The syntax of JSP page directive is as follows: " }, { "code": null, "e": 881, "s": 851, "text": "<%@page attribute = \"value\"%>" }, { "code": null, "e": 1106, "s": 881, "text": "Different properties/attributes : The following are the different properties that can be defined using page directive :import: This tells the container what packages/classes are needed to be imported into the program.Syntax:" }, { "code": null, "e": 1212, "s": 1106, "text": "import: This tells the container what packages/classes are needed to be imported into the program.Syntax:" }, { "code": null, "e": 1239, "s": 1212, "text": "<%@page import = \"value\"%>" }, { "code": null, "e": 1250, "s": 1239, "text": "Example : " }, { "code": null, "e": 1255, "s": 1250, "text": "html" }, { "code": "<%-- JSP code to demonstrate how to use page directive to import a package --%> <%@page import = \"java.util.Date\"%><%Date d = new Date();%><%=d%>", "e": 1401, "s": 1255, "text": null }, { "code": null, "e": 1410, "s": 1401, "text": "Output: " }, { "code": null, "e": 1593, "s": 1410, "text": "contentType: This defines the format of data that is being exchanged between the client and the server. It does the same thing as the setContentType method in servlet used to.Syntax:" }, { "code": null, "e": 1623, "s": 1593, "text": "<%@page contentType=\"value\"%>" }, { "code": null, "e": 1639, "s": 1623, "text": "Usage Example: " }, { "code": null, "e": 1644, "s": 1639, "text": "html" }, { "code": "<%-- JSP code to demonstrate how to usepage directive to set the type of content --%> <%@page contentType = \"text/html\" %><% = \"This is sparta\" %>", "e": 1791, "s": 1644, "text": null }, { "code": null, "e": 1801, "s": 1791, "text": "Output : " }, { "code": null, "e": 1891, "s": 1801, "text": "info: Defines the string which can be printed using the ‘getServletInfo()’ method.Syntax:" }, { "code": null, "e": 1914, "s": 1891, "text": "<%@page info=\"value\"%>" }, { "code": null, "e": 1930, "s": 1914, "text": "Usage Example: " }, { "code": null, "e": 1935, "s": 1930, "text": "html" }, { "code": "<%-- JSP code to demonstrate how to use page directive to set the page information --%> <%@page contentType = \"text/html\" %><% = getServletInfo()%>", "e": 2083, "s": 1935, "text": null }, { "code": null, "e": 2092, "s": 2083, "text": "Output: " }, { "code": null, "e": 2219, "s": 2092, "text": "buffer: Defines the size of the buffer that is allocated for handling the JSP page. The size is defined in Kilo Bytes.Syntax: " }, { "code": null, "e": 2251, "s": 2219, "text": "<%@page buffer = \"size in kb\"%>" }, { "code": null, "e": 2364, "s": 2251, "text": "language: Defines the scripting language used in the page. By default, this attribute contains the value ‘java’." }, { "code": null, "e": 2532, "s": 2364, "text": "isELIgnored: This attribute tells if the page supports expression language. By default, it is set to false. If set to true, it will disable expression language.Syntax:" }, { "code": null, "e": 2569, "s": 2532, "text": "<%@page isElIgnored = \"true/false\"%>" }, { "code": null, "e": 2585, "s": 2569, "text": "Usage Example: " }, { "code": null, "e": 2590, "s": 2585, "text": "html" }, { "code": "<%-- JSP code to demonstrate how to use pagedirective to ignore expression language --%> <%@page contentType = \"text/html\" %><%@page isELIgnored = \"true\"%><body bgcolor = \"blue\"><c:out value = \"${'This is sparta}\"/></body>", "e": 2813, "s": 2590, "text": null }, { "code": null, "e": 2835, "s": 2813, "text": "Output: (blank page) " }, { "code": null, "e": 2939, "s": 2835, "text": "errorPage: Defines which page to redirect to, in case the current page encounters an exception. Syntax:" }, { "code": null, "e": 2974, "s": 2939, "text": "<%@page errorPage = \"true/false\"%>" }, { "code": null, "e": 2990, "s": 2974, "text": "Usage Example: " }, { "code": null, "e": 2995, "s": 2990, "text": "html" }, { "code": "//JSP code to divide two numbers<%@ page errorPage = \"error.jsp\" %> <% // dividing the numbersint z = 1/0; // resultout.print(\"division of numbers is: \" + z); %> ", "e": 3163, "s": 2995, "text": null }, { "code": null, "e": 3382, "s": 3163, "text": "isErrorPage: It classifies whether the page is an error page or not. By classifying a page as an error page, it can use the implicit object ‘exception’ which can be used to display exceptions that have occurred.Syntax:" }, { "code": null, "e": 3417, "s": 3382, "text": "<%@page isErrorPage=\"true/false\"%>" }, { "code": null, "e": 3433, "s": 3417, "text": "Usage example: " }, { "code": null, "e": 3438, "s": 3433, "text": "html" }, { "code": "//JSP code for error page, which displays the exception<%@ page isErrorPage = \"true\" %> <h1>Exception caught</h1> The exception is: <% = exception %>Output:", "e": 3603, "s": 3438, "text": null }, { "code": null, "e": 3612, "s": 3603, "text": "Output: " }, { "code": null, "e": 3633, "s": 3612, "text": "Include directive : " }, { "code": null, "e": 3896, "s": 3633, "text": "JSP include directive is used to include other files into the current jsp page. These files can be html files, other sp files etc. The advantage of using an include directive is that it allows code re-usability.The syntax of an include directive is as follows: " }, { "code": null, "e": 3932, "s": 3896, "text": "<@%include file = \"file location\"%>" }, { "code": null, "e": 4039, "s": 3932, "text": "Usage example: In the following code, we’re including the contents of an html file into a jsp page.a.html " }, { "code": null, "e": 4044, "s": 4039, "text": "html" }, { "code": "<h1>This is the content of a.html</h1>", "e": 4083, "s": 4044, "text": null }, { "code": null, "e": 4094, "s": 4083, "text": "index.jsp " }, { "code": null, "e": 4099, "s": 4094, "text": "html" }, { "code": "<% = Local content%><%@include file = \"a.html\"%><% = local content%>", "e": 4168, "s": 4099, "text": null }, { "code": null, "e": 4178, "s": 4168, "text": "Output : " }, { "code": null, "e": 4374, "s": 4178, "text": "Taglib Directive : The taglib directive is used to mention the library whose custom-defined tags are being used in the JSP page. It’s major application is JSTL(JSP standard tag library). Syntax: " }, { "code": null, "e": 4469, "s": 4374, "text": "<@%taglib uri = \"library url\" prefix=\"the prefix to \nidentify the tags of this library with\"%>" }, { "code": null, "e": 4485, "s": 4469, "text": "Usage Example: " }, { "code": null, "e": 4490, "s": 4485, "text": "html" }, { "code": "<%-- JSP code to demonstratetaglib directive--%><%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\"prefix = \"c\" %> <c:out value = \"${'This is Sparta'}\"/>", "e": 4648, "s": 4490, "text": null }, { "code": null, "e": 5066, "s": 4648, "text": "In the above code, we’ve used to taglib directive to point to the JSTL library which is a set of some custom-defined tags in JSP that can be used in place of the scirptlet tag (<%..%>). The prefix attribute is used to define the prefix that is used to identify the tags of this library. Here, the prefix c is used in the <c:out> tag to tell the container that this tag belongs to the library mentioned above.Output: " }, { "code": null, "e": 5079, "s": 5066, "text": "Akanksha_Rai" }, { "code": null, "e": 5088, "s": 5079, "text": "sooda367" }, { "code": null, "e": 5103, "s": 5088, "text": "jeetpurohit989" }, { "code": null, "e": 5116, "s": 5103, "text": "nikhatkhan11" }, { "code": null, "e": 5125, "s": 5116, "text": "Java-JSP" }, { "code": null, "e": 5142, "s": 5125, "text": "Web Technologies" }, { "code": null, "e": 5240, "s": 5142, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5301, "s": 5240, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5344, "s": 5301, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 5416, "s": 5344, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5456, "s": 5416, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5480, "s": 5456, "text": "REST API (Introduction)" }, { "code": null, "e": 5513, "s": 5480, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 5555, "s": 5513, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 5602, "s": 5555, "text": "How to float three div side by side using CSS?" }, { "code": null, "e": 5660, "s": 5602, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Redux – Basic Understanding of the Concepts for Beginners
24 Feb, 2021 Redux is one of the most confusing and probably a difficult topic for someone who is trying to learn it from scratch. But why?? Is the reason is the number of boilerplates or the terminologies in Redux that turned you off from learning it? You are searching for a Redux guide, you read some blogs/tutorials, you watch some YouTube videos but things become more confusing and complicated when you find that different videos are telling some different approaches to build an application. Store, Reducer, Action, Dispatch, Subscribe, and a lot of terminologies in Redux force you to think that why do we need to go with such a long process if things can be solved straightforward. You might be thinking that instead of simplifying the things it’s just increasing the complexity of an application. You might have also come across some libraries such as Redux, React-Redux, Redux-thunk, Redux-saga, Redux-promise, Reselect, Recompose, and many more. Routing, authentication, server-side rendering, bundling....oh gosh!!! A lot of things are there to learn and it’s overwhelming for you. At some point, you start losing your mind... Relax! You’re not alone who is experiencing this problem and struggling with learning Redux. If you are searching for a single resource to understand all the basics, keeping everything else aside which is not important to learn then we are here to help you and in this blog, we will try our best to make you understand all the basic concepts of Redux without making you confused with a bunch of terminologies. Let’s start with that... Firstly keep aside all the extra bit stuff and let’s just go with the Redux only. Right now we will only introduce the minimum things in Redux to learn now. There is no need to go in deep initially with some concepts like React-router, Redux-form, Reselect, Ajax, Webpack, Authentication, Testing, etc. Remember that you don’t run in one day, you firstly need to learn to walk. Before you start learning Redux, make sure you know the basics of React. In the official documentation, Redux is defined as... Redux is a predictable state container for JavaScript apps. Well, at first these 9 words give you the feeling of 90 incomplete sentences where you don’t get anything. Well, the documentation has explanatory stuff when you start reading it. Take an example of the React application. Most of the time you define the state in your application at the top-level of the component but have you noticed that when your application grows, all your state in a top-level component is no longer sufficient for you and now it’s difficult to manage all your state in the application? You may also have a lot of data changing in your application over time. Redux is introduced to solve all these problems. State management is a big concern in large applications and Redux solves this problem. Some nice things you can do with Redux are logging, hot reloading, time travel, universal apps, record, and replay, etc. We will keep it simple for you and let’s understand it first without using the technical jargon. Let’s consider a real-life scenario of banks. You want to withdraw some cash from your bank account. You go to the bank branch with one intention/action in your mind i.e. WITHDRAW_MONEY. When you enter the bank you go straight to the counter of Cashier to make your request. But....why do you need to talk to the cashier? Why you just don’t enter into the bank vault to get your money? You’re aware that there is a process that you need to follow to withdraw your money. When you talk to the cashier, he takes some time, checks some details, enters some commands, and handover the cash to you. Let’s relate this example to Redux and understand some of its terminologies. 1. Consider the Redux Store as a bank vault and the State of your application is like money. The entire user interface of your application is a function of your state. Just like your money is safe in the bank vault, the state of your application is safe in the Redux Store. Now, this leads to the first principle of Redux... Single source of truth: The state of your whole application is stored in an object tree within a single store. Let’s simplify this statement more. Instead of littering your money everywhere in the bank, keep money in one vault. So in Redux, it is advisable to store the application state in a single object managed by the Redux store. 2. You visit the bank with action in your mind i.e WITHDRAW_MONEY. No one is going to give you money if you just roam around here and there. A similar thing happens in Redux. If you want to update the state of your Redux (like you do with setState in React) you need to let Redux know about your action. Just like you follow a process to withdraw money from your bank, Redux also follows a process to change/update the state of your application. This leads to the second principle of Redux. State is read-only The only way to change the state is to emit an action an object describing what happened. The meaning of the above statement is quite simple. In Redux your action WITHDRAW_MONEY will be represented by an object and it looks something like below... { type: "WITHDRAW_MONEY", amount: "$10,000" } The above object is an action in the Redux application that has a type field describing the action you want to perform. So whenever you need to change/update the state of your Redux application, you need to dispatch an action. 3. Consider your cashier in the bank as a Reducer in your Redux application. To WITHDRAW_MONEY from your bank vault, you need to convey your intention/action to the cashier first. Now the cashier will follow some process and it will communicate to the bank vault that holds all the bank’s money. A similar thing happens in Redux. To update the state of your application you need to convey your action to the reducer. Now the reducer will take your action, it will perform its job and it will ensure that you get your money. Your Reducer always returns your new state. Sending off the action to the reducer is called dispatching an action. This leads to the last or the third principle of Redux. To specify how the state tree is transformed by actions, you write pure reducers. We will understand the pure Reducer later in this blog. Hope we have explained well about three main terminologies of Redux: The Store, The Reducer, and an Action. With a real-life example, we understood the principles and some common terminologies of Redux but how to introduce all these things in an application? To deepen your fundamental concepts in Redux let’s take an example of a simple React application, and we will refactor the app to introduce Redux in it. If you’re familiar with React then you won’t have a problem in understanding the structure of the above React application. You can create this application using the create-react-app command. In your application, the main App component is importing a <HelloTech /> component and renders the information in its body. The <HelloTech /> component takes in a tech prop, and this prop displays different technologies to the user. For example <HelloTech tech=”Redux” /> will display the below result to the user.... Below is the code for App component... src/App.js Javascript import React, { Component } from "react";import HelloTech from "./HelloTech"; class App extends Component { state = { tech : "React"}render() { return <HelloTech tech={this.state.tech}/>}} export default App; We are passing the tech as a prop into the HelloTech component as shown below: <HelloTech tech={this.state.tech}/> For now, forget about the HelloTech component implementation. It’s just taking the tech prop and using some CSS for styling purposes. The main concern here is to refactor the App component and use Redux in it. Redux is the state manager for our application, so we need to take away the state object, and we want it to be managed by Redux. Remember the example of the bank vault, it keeps all the money. In a similar way, the Redux store manages the overall application state and it keeps the application state object. So we need to firstly remove the current state object from App.js and we need to install Redux by running npm install –save redux from the command-line interface. Javascript import React, { Component } from "react";import HelloTech from "./HelloTech"; class App extends Component { // the state object has been removed. render() { return <HelloTech tech={this.state.tech}/>}} export default App; In the case of the bank vault, some engineers might be hired to create a secure money keeping facility. Similarly, here in Redux, Some APIs are provided by the Redux library to create the Store facility. Below is the code to create a Store in Redux... import { createStore } from "redux"; //an import from the redux library const store = createStore(); We have imported the createStore factory function from Redux, and then we have invoked the createStore() function to create the store. When you visit the bank to withdraw your money and let your action known to the cashier you do not get the money instantly. Firstly the cashier checks your account that if you have enough money to perform the transaction or not. It communicates with the bank vault for this information. In a nutshell, the Cashier and Vault are always in sync. A similar thing happens in Redux. The Store (Bank Vault) and the Reducer (Cashier) communicate with each other, and they are always in sync. But how to write this logic in our code??? We pass the reducer as an argument in createStore() function and below is the complete code for App.js App.js Javascript import React, { Component } from "react";import HelloTech from "./HelloTech"; import { createStore } from "redux"; const store = createStore (reducer); class App extends Component { render() { return <HelloTech tech={this.state.tech}/> }} export default App; If you hear the word Reducer it sounds like it is a reducing function that performs ‘Reduce’ kind of job. Well, In JavaScript, you already use Reducer and that is an Array.reduce() method (you might be aware of this method). This method takes two values accumulator and currentValue. Take a look at the example given below... let arr = [1, 2, 3, 4, 5] let sum = arr.reduce((x,y) => x + y) console.log(sum) // 15 Here x is the accumulator and y is the currentValue. A similar thing happens in Redux. Reducer is a function in Redux that takes two parameters. One is STATE of the app and the other is ACTION. Now we need to include the Reducer in our app which we haven’t done yet. So create a directory reducer and create a file index.js in it. The path for the reducer function will be src/reducers/index.js. Right now we will just pass Store as an argument in Reducer, and we will just export a simple function. The code looks like below... export default (state) => { } In Array.reduce() we returned the sum of the accumulator and current value. If you take the example of our bank scenario then after withdrawal, the money in your bank vault is no longer the same. It will be updated and again, the Cashier and Vault will remain in sync with the balance left in your account. Just like the cashier the reducer always returns the new state of your application. We will talk about changing/updating the state later in this blog. Right now consider a case that you visit the bank and you didn’t perform any action so the bank balance remains the same. In Redux if you won’t perform any action and you don’t pass the Action as an argument in Reducer than the state will remain the same and the reducer will return the same state as a new state. At this point keep a new state being returned as the same state passed in. export default (state) => { return state } When you created an account in your bank, you might have deposited some amount in your account, and if you ask the cashier your bank balance they’ll look it up and tell it to you. In the same way, when you create a Redux Store you do a similar kind of initial deposit which is known as initialState. We will represent this initialState as a second argument passed into the createStore. const store = createStore(reducer, initialState); So the initialState is like an initial deposit in your Store (bank vault) and if you don’t perform any action this initialState will be returned as the state of the application. Below is the updated code in App.js with initialState in our application. App.js Javascript import React, { Component } from "react";import HelloTech from "./HelloTech";import reducer from "./reducers";import { createStore } from "redux"; const initialState = { tech: "React " };const store = createStore(reducer, initialState); class App extends Component { render() { return <HelloTech tech={this.state.tech}/> } } export default App; At this point, your application will throw an error if you run it because the tech prop still reads, this.state.tech. We have removed the state object from our application so it will be undefined. Right now the state is entirely managed by Store so we need to replace this line with the getState() method which is available when you create a store with createStore() method. If we call the getState method on the created store, we will get the current state of our application. The INITIAL STATE passed into the createStore() is represented by the object {tech: React}. So in our case store.getState() will return this object. Below is the updated code for App.js App.js Javascript import React, { Component } from "react";import HelloTech from "./HelloTech";import { createStore } from "redux"; const initialState = { tech: "React " };const store = createStore(reducer, initialState); class App extends Component { render() { return <HelloTech tech={store.getState().tech}/> }} Congratulations!!! We just have refactored a simple React application to use Redux. Now the state is managed by the Redux. Now let’s move to the next topic which is Actions in Redux. In our bank case scenario, your intention/action was WITHDRAW_MONEY. You have to let your action known to the cashier and the cashier will be responsible for updating your money in your account and handover it to you. The same thing happens in the Redux reducer. In a pure React application, we use the setState method to update the state in our application but here we need to let our action known to the Reducer to update the state in your application. But how?? By dispatching and action! And how to do that??? We just need to describe the action by a plain JavaScript object and this object must have a type field to describe the intent of the action. The code will look like something below... { type: "withdraw_money" } You won’t get the money if you only tell your action to withdraw money to the cashier. You also need to mention the amount. Many times in our application we also need to add some additional information for full details. So we will add one more information amount in our code and it looks something like below... { type: "withdraw_money", amount: "$3000" } We can include some more information but for now, it’s sufficient and ignore the other details. It’s really up to you that how you structure your action but a standard/common approach in Redux is using the payload field. We put all the required data/information in the payload object that describes the action and it looks something like below... { type: "withdraw_money", payload: { amount: "$3000" } } We have discussed that Reducer takes two arguments in order to update the application. One is the state and the other is action. So a simple Reducer looks something like below... function reducer(state, action) { // return new state } Now to handle the action passed into the Reducer we typically use switch statements in Redux which is nothing but basically, an if/else statement. Javascript function reducer (state, action) { switch (action.type) { case "withdraw_money": //do something break; case "deposit-money": //do something break; default: return state; } } In the above example, we have taken two actions. One is withdraw_money and the other one is deposit_money. In your Redux application based on the requirement, you can define as many actions as you want but every action flows through the reducer and that’s what we have done in the above code. In the above code, both actions pass through the same reducer and the reducer differentiates each of them by switching over the action.type. This is how each action can be handled separately in Reducer without any inconvenience. Further in the above code, we just need to define the do something part to return a new state. Let’s go back to the previous example of HelloTech and understand how to update the state of the application. Look at the image given below. There are three buttons and our aim is to change the text/technology whenever a specific button is clicked. To do, so we need to dispatch an action, and the state of the application needs to be updated. For example, if button React-redux is clicked it should look something like below... From the above image, it is clear that we need to describe three actions... For the React button: { type: "SET_TECHNOLOGY", text: "React" } For the React-Redux button: { type: "SET_TECHNOLOGY", text: "React-redux" } For the Elm button: { type: "SET_TECHNOLOGY", text: "Elm" } All three buttons do the same thing. That is the reason we have defined all the three actions with the same type of field. Treat them like customers in a bank with the same intent/action of depositing money (type) but the different amounts (text). If you look at the code we have written for creating actions you’ll notice that few things are repeated in the code. For example, the same type of field is written multiple times which is not good as per the DRY principle in programming. To keep our code DRY we need to look at the new term Action Creators. What are those....??? Let’s discuss that. Actions creators are just simple functions that help you to create actions keeping your code DRY and it returns action objects. Below is the code... export function setTechnology (text) { return { type: "SET_TECHNOLOGY", tech: text } } In the above function, we just need to call the function setTechnology and we will get the action back. There is no need to duplicate the code everywhere. We can simplify this more, and we can write the same above code using the ES6 feature. const setTechnology = text => ({ type: "SET_TECHNOLOGY", text }); In this section, we will talk about the folder structure, and we will see how to put everything in specific folders/files to keep the things organized. If we talk about our bank case scenario then you will notice that things are organized at their own place. For example, the cashier sits in their own cubicle/office and vault is safe in separate secure rooms. We will do a similar thing in Redux. It’s totally up to you how you want to structure your project but a common approach in Redux is to create a separate folder/directory for the major components such as reducer, actions, and store. Create three different folders reducers, stores, and actions. In each of the folders create an index.js file that will be the entry point for each of the Redux components. Now refactor the application we have built before and put everything at its own place. store/index.js import { createStore } from "redux"; import reducer from "../reducers"; const initialState = { tech: "React " }; export const store = createStore(reducer, initialState); Whenever we need Store anywhere in our app we can import the above file mentioning the path import store from “./store”; Now the file App.js will have a slight difference in its code. Javascript import React, { Component } from "react";import HelloTech from "./HelloTech";import ButtonGroup from "./ButtonGroup";import { store } from "./store"; class App extends Component { render() { return [ <HelloTech key={1} tech={store.getState().tech} />, <ButtonGroup key={2} technologies={["React", "Elm", "React-redux"]} /> ]; }} export default App; In the above code line, 4 has been changed according to the path of Store. We have also imported a component ButtonGroup which is basically responsible for rendering the three buttons. <ButtonGroup /> component takes an array of technologies and spits out buttons. Another thing you need to notice that the App component returns an array. In React 16 you don’t need to use <div> to wrap the JSX element. like we were doing earlier in React. We can use an array and pass the key prop to each element in the array to perform the same job. Let’s move to the ButtonGroup component. It’s a stateless component that takes in an array of technologies which is denoted by technologies. ButtonGroup.js Javascript import React from "react"; const ButtonGroup = ({ technologies }) => ( <div> {technologies.map((tech, i) => ( <button data-tech={tech} key={`btn-${i}`} className="hello-btn" > {tech} </button> ))} </div>); export default ButtonGroup; In the above code the buttons array passed in is [“React”, “Elm”, “React-redux”]. We need to loop over this array using map to render each of the tech in <button></button>. Generated buttons have few attributes as well such as key and data-tech. A completely rendered button will look like this: <button data-tech="React-redux" key="btn-1" className="hello-btn"> React </button> This will render all the buttons but nothing will happen if you click the buttons. We need to use the onClick handler within the render function. Javascript <div> {technologies.map((tech, i) => ( <button data-tech={tech} key={`btn-${i}`} className="hello-btn" onClick={dispatchBtnAction} > {tech} </button> ))} </div> Now, remember the code to dispatch the action for individual tech React, React-redux, Elm. { type: "SET_TECHNOLOGY", tech: "React" } and for React-redux it will be like.... { type: "SET_TECHNOLOGY", tech: "React-redux" } So now we need to write the code for dispacthBtnAction function to dispatch the action whenever we click any button. Below is the code... function dispatchBtnAction(e) { const tech = e.target.dataset.tech; store.dispatch(setTechnology(tech)); } The above code doesn’t make sense to you....right??? Here is the explanation... e.target.dataset.tech get the data attribute set on the button data-tech. Hence, the tech will hold the value of the text. store.dispatch() defines how you dispatch an action in Redux. setTechnology() is the action creator we wrote earlier. Now, remember the same bank case scenario. For your action WITHDRAW_MONEY, you interact with the cashier...yeah??? This means if you want your money, your action needs to be passed through the cashier. The same thing is happening in the above code. When you are dispatching an action, it passes through the Reducer (cashier). Till now the cashier in the bank did nothing with WITHDRAW_MONEY action. We expect the cashier to update the money in the bank vault and hand over the money to you. In our Redux app, we also want our Reducer to return a new state which should have the action text in there. What exactly we mean is that if the current state is { tech: “React”} then with a new action given below... { type: "SET_TECHNOLOGY", text: "React-Redux" } We expect the new state to be {tech: “React-Redux”} We have discussed earlier that to handle different action types we can use switch statements in our Reducer code with different actions in mind. In our bank case scenario, the cashier will respond according to the intent/action given by the customer. These actions could be WITHDRAW_MONEY, DEPOSIT_MONEY, or just SAY_HELLO. Similarly, the reducer will respond based on your intent. Right now we just have one case SET_TECHNOLOGY so the code will look like something below...(Our cashier that actually gives us money) Javascript export default (state, action) => { switch (action.type) { case "SET_TECHNOLOGY": return { ...state, tech: action.text }; default: return state; }}; Here notice that we are returning a new copy of the state, a new object using the ES6 spread operator ...state. We are not supposed to mutate the state received in our Reducer. Technically you should not write the code something like below... export default (state, action) => { switch (action.type) { case "SET_TECHNOLOGY": state.tech = action.text; return state; default: return state; } }; Also, Reducer should be pure functions in our code with no side effects — No API calls or updating a value outside the scope of the function. Now the cashier is responding to your action and giving you the money you requested for. But again if you click the button you can not see the text updated on your screen.... let’s discuss it with a new term subscribe. Well, you have received your money from the cashier but what about some sort of personal receipt or notification/alert via email/mobile. Most likely you receive a notification regarding your transaction and the balance left in your account. You receive that because you have subscribed to receive transaction notifications from the bank either by email/text. A similar thing happens in Redux. To receive an update after the successful action initiated, you need to subscribe to them. Now the question is...how? Redux provides subscribe method to do this job. We need to use the store.subscribe() function, and we need to pass the argument in it. Whenever there’s a state update this argument will be invoked. We need to keep in mind that the argument passed into it should be a function. Once the state is updated we expect our application to re-render the new state values. The entire application renders in the main index.js file of our application. If you open this file you will find the code given below... ReactDOM.render(<App />, document.getElementById("root") The above function can be also written using the ES6 feature. const render = () => ReactDOM.render(<App />, document.getElementById("root")); render(); In the above code, we just have represented the app into a function, and then we have invoked the function to render the app. Now we can pass the above-refactored render logic into our store.subscribe() function. store.subscribe(render); Now the <App /> will be re-rendered with new state value whenever there’s a successful state update to the store. Below is the <App/> component. Javascript class App extends Component { render() { return [ <HelloTech key={1} tech={store.getState().tech} />, <ButtonGroup key={2} technologies={["React", "Elm", "React-redux"]} /> ]; }} store.getState() in line 4 will fetch the updated state whenever a re-render occurs. Now the app will work as you expect it to work and you will see the updated technology whenever you will click a specific button. Congratulations!!! We are successfully dispatching an action, receiving money from the Cashier, and then subscribing to receive notifications. That’s it for now... We have discussed all the main terminology of Redux, and we have tried our best to explain each one of them in the simplest way. But the journey of learning Redux doesn’t end here. We suggest you practice some more exercises on Redux and build some more complex projects. Also, don’t get afraid of so many libraries available in Redux. Each library has its own specific job that you will understand slowly and gradually. We hope Redux won’t scare you anymore!!! Redux GBlog ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Feb, 2021" }, { "code": null, "e": 182, "s": 54, "text": "Redux is one of the most confusing and probably a difficult topic for someone who is trying to learn it from scratch. But why??" }, { "code": null, "e": 295, "s": 182, "text": "Is the reason is the number of boilerplates or the terminologies in Redux that turned you off from learning it? " }, { "code": null, "e": 542, "s": 295, "text": "You are searching for a Redux guide, you read some blogs/tutorials, you watch some YouTube videos but things become more confusing and complicated when you find that different videos are telling some different approaches to build an application. " }, { "code": null, "e": 1183, "s": 542, "text": "Store, Reducer, Action, Dispatch, Subscribe, and a lot of terminologies in Redux force you to think that why do we need to go with such a long process if things can be solved straightforward. You might be thinking that instead of simplifying the things it’s just increasing the complexity of an application. You might have also come across some libraries such as Redux, React-Redux, Redux-thunk, Redux-saga, Redux-promise, Reselect, Recompose, and many more. Routing, authentication, server-side rendering, bundling....oh gosh!!! A lot of things are there to learn and it’s overwhelming for you. At some point, you start losing your mind..." }, { "code": null, "e": 1276, "s": 1183, "text": "Relax! You’re not alone who is experiencing this problem and struggling with learning Redux." }, { "code": null, "e": 1618, "s": 1276, "text": "If you are searching for a single resource to understand all the basics, keeping everything else aside which is not important to learn then we are here to help you and in this blog, we will try our best to make you understand all the basic concepts of Redux without making you confused with a bunch of terminologies. Let’s start with that..." }, { "code": null, "e": 1997, "s": 1618, "text": "Firstly keep aside all the extra bit stuff and let’s just go with the Redux only. Right now we will only introduce the minimum things in Redux to learn now. There is no need to go in deep initially with some concepts like React-router, Redux-form, Reselect, Ajax, Webpack, Authentication, Testing, etc. Remember that you don’t run in one day, you firstly need to learn to walk. " }, { "code": null, "e": 2070, "s": 1997, "text": "Before you start learning Redux, make sure you know the basics of React." }, { "code": null, "e": 2124, "s": 2070, "text": "In the official documentation, Redux is defined as..." }, { "code": null, "e": 2184, "s": 2124, "text": "Redux is a predictable state container for JavaScript apps." }, { "code": null, "e": 2815, "s": 2184, "text": "Well, at first these 9 words give you the feeling of 90 incomplete sentences where you don’t get anything. Well, the documentation has explanatory stuff when you start reading it. Take an example of the React application. Most of the time you define the state in your application at the top-level of the component but have you noticed that when your application grows, all your state in a top-level component is no longer sufficient for you and now it’s difficult to manage all your state in the application? You may also have a lot of data changing in your application over time. Redux is introduced to solve all these problems. " }, { "code": null, "e": 3023, "s": 2815, "text": "State management is a big concern in large applications and Redux solves this problem. Some nice things you can do with Redux are logging, hot reloading, time travel, universal apps, record, and replay, etc." }, { "code": null, "e": 3506, "s": 3023, "text": "We will keep it simple for you and let’s understand it first without using the technical jargon. Let’s consider a real-life scenario of banks. You want to withdraw some cash from your bank account. You go to the bank branch with one intention/action in your mind i.e. WITHDRAW_MONEY. When you enter the bank you go straight to the counter of Cashier to make your request. But....why do you need to talk to the cashier? Why you just don’t enter into the bank vault to get your money?" }, { "code": null, "e": 3792, "s": 3506, "text": "You’re aware that there is a process that you need to follow to withdraw your money. When you talk to the cashier, he takes some time, checks some details, enters some commands, and handover the cash to you. Let’s relate this example to Redux and understand some of its terminologies. " }, { "code": null, "e": 4117, "s": 3792, "text": "1. Consider the Redux Store as a bank vault and the State of your application is like money. The entire user interface of your application is a function of your state. Just like your money is safe in the bank vault, the state of your application is safe in the Redux Store. Now, this leads to the first principle of Redux..." }, { "code": null, "e": 4228, "s": 4117, "text": "Single source of truth: The state of your whole application is stored in an object tree within a single store." }, { "code": null, "e": 4453, "s": 4228, "text": "Let’s simplify this statement more. Instead of littering your money everywhere in the bank, keep money in one vault. So in Redux, it is advisable to store the application state in a single object managed by the Redux store. " }, { "code": null, "e": 4946, "s": 4455, "text": "2. You visit the bank with action in your mind i.e WITHDRAW_MONEY. No one is going to give you money if you just roam around here and there. A similar thing happens in Redux. If you want to update the state of your Redux (like you do with setState in React) you need to let Redux know about your action. Just like you follow a process to withdraw money from your bank, Redux also follows a process to change/update the state of your application. This leads to the second principle of Redux." }, { "code": null, "e": 4965, "s": 4946, "text": "State is read-only" }, { "code": null, "e": 5055, "s": 4965, "text": "The only way to change the state is to emit an action an object describing what happened." }, { "code": null, "e": 5213, "s": 5055, "text": "The meaning of the above statement is quite simple. In Redux your action WITHDRAW_MONEY will be represented by an object and it looks something like below..." }, { "code": null, "e": 5265, "s": 5213, "text": "{ \n type: \"WITHDRAW_MONEY\",\n amount: \"$10,000\"\n}\n\n" }, { "code": null, "e": 5492, "s": 5265, "text": "The above object is an action in the Redux application that has a type field describing the action you want to perform. So whenever you need to change/update the state of your Redux application, you need to dispatch an action." }, { "code": null, "e": 6190, "s": 5494, "text": "3. Consider your cashier in the bank as a Reducer in your Redux application. To WITHDRAW_MONEY from your bank vault, you need to convey your intention/action to the cashier first. Now the cashier will follow some process and it will communicate to the bank vault that holds all the bank’s money. A similar thing happens in Redux. To update the state of your application you need to convey your action to the reducer. Now the reducer will take your action, it will perform its job and it will ensure that you get your money. Your Reducer always returns your new state. Sending off the action to the reducer is called dispatching an action. This leads to the last or the third principle of Redux." }, { "code": null, "e": 6272, "s": 6190, "text": "To specify how the state tree is transformed by actions, you write pure reducers." }, { "code": null, "e": 6436, "s": 6272, "text": "We will understand the pure Reducer later in this blog. Hope we have explained well about three main terminologies of Redux: The Store, The Reducer, and an Action." }, { "code": null, "e": 6741, "s": 6436, "text": "With a real-life example, we understood the principles and some common terminologies of Redux but how to introduce all these things in an application? To deepen your fundamental concepts in Redux let’s take an example of a simple React application, and we will refactor the app to introduce Redux in it. " }, { "code": null, "e": 7250, "s": 6741, "text": "If you’re familiar with React then you won’t have a problem in understanding the structure of the above React application. You can create this application using the create-react-app command. In your application, the main App component is importing a <HelloTech /> component and renders the information in its body. The <HelloTech /> component takes in a tech prop, and this prop displays different technologies to the user. For example <HelloTech tech=”Redux” /> will display the below result to the user...." }, { "code": null, "e": 7289, "s": 7250, "text": "Below is the code for App component..." }, { "code": null, "e": 7300, "s": 7289, "text": "src/App.js" }, { "code": null, "e": 7311, "s": 7300, "text": "Javascript" }, { "code": "import React, { Component } from \"react\";import HelloTech from \"./HelloTech\"; class App extends Component { state = { tech : \"React\"}render() { return <HelloTech tech={this.state.tech}/>}} export default App;", "e": 7525, "s": 7311, "text": null }, { "code": null, "e": 7606, "s": 7527, "text": "We are passing the tech as a prop into the HelloTech component as shown below:" }, { "code": null, "e": 7643, "s": 7606, "text": "<HelloTech tech={this.state.tech}/>\n" }, { "code": null, "e": 8325, "s": 7643, "text": "For now, forget about the HelloTech component implementation. It’s just taking the tech prop and using some CSS for styling purposes. The main concern here is to refactor the App component and use Redux in it. Redux is the state manager for our application, so we need to take away the state object, and we want it to be managed by Redux. Remember the example of the bank vault, it keeps all the money. In a similar way, the Redux store manages the overall application state and it keeps the application state object. So we need to firstly remove the current state object from App.js and we need to install Redux by running npm install –save redux from the command-line interface. " }, { "code": null, "e": 8336, "s": 8325, "text": "Javascript" }, { "code": "import React, { Component } from \"react\";import HelloTech from \"./HelloTech\"; class App extends Component { // the state object has been removed. render() { return <HelloTech tech={this.state.tech}/>}} export default App;", "e": 8561, "s": 8336, "text": null }, { "code": null, "e": 8813, "s": 8561, "text": "In the case of the bank vault, some engineers might be hired to create a secure money keeping facility. Similarly, here in Redux, Some APIs are provided by the Redux library to create the Store facility. Below is the code to create a Store in Redux..." }, { "code": null, "e": 8916, "s": 8813, "text": "import { createStore } from \"redux\"; //an import from the redux library\nconst store = createStore(); \n" }, { "code": null, "e": 9052, "s": 8916, "text": "We have imported the createStore factory function from Redux, and then we have invoked the createStore() function to create the store. " }, { "code": null, "e": 9683, "s": 9052, "text": "When you visit the bank to withdraw your money and let your action known to the cashier you do not get the money instantly. Firstly the cashier checks your account that if you have enough money to perform the transaction or not. It communicates with the bank vault for this information. In a nutshell, the Cashier and Vault are always in sync. A similar thing happens in Redux. The Store (Bank Vault) and the Reducer (Cashier) communicate with each other, and they are always in sync. But how to write this logic in our code??? We pass the reducer as an argument in createStore() function and below is the complete code for App.js" }, { "code": null, "e": 9690, "s": 9683, "text": "App.js" }, { "code": null, "e": 9701, "s": 9690, "text": "Javascript" }, { "code": "import React, { Component } from \"react\";import HelloTech from \"./HelloTech\"; import { createStore } from \"redux\"; const store = createStore (reducer); class App extends Component { render() { return <HelloTech tech={this.state.tech}/> }} export default App;", "e": 9971, "s": 9701, "text": null }, { "code": null, "e": 10297, "s": 9971, "text": "If you hear the word Reducer it sounds like it is a reducing function that performs ‘Reduce’ kind of job. Well, In JavaScript, you already use Reducer and that is an Array.reduce() method (you might be aware of this method). This method takes two values accumulator and currentValue. Take a look at the example given below..." }, { "code": null, "e": 10384, "s": 10297, "text": "let arr = [1, 2, 3, 4, 5]\nlet sum = arr.reduce((x,y) => x + y)\nconsole.log(sum) // 15\n" }, { "code": null, "e": 10580, "s": 10384, "text": "Here x is the accumulator and y is the currentValue. A similar thing happens in Redux. Reducer is a function in Redux that takes two parameters. One is STATE of the app and the other is ACTION. " }, { "code": null, "e": 10915, "s": 10580, "text": "Now we need to include the Reducer in our app which we haven’t done yet. So create a directory reducer and create a file index.js in it. The path for the reducer function will be src/reducers/index.js. Right now we will just pass Store as an argument in Reducer, and we will just export a simple function. The code looks like below..." }, { "code": null, "e": 10946, "s": 10915, "text": "export default (state) => {\n}\n" }, { "code": null, "e": 11793, "s": 10946, "text": "In Array.reduce() we returned the sum of the accumulator and current value. If you take the example of our bank scenario then after withdrawal, the money in your bank vault is no longer the same. It will be updated and again, the Cashier and Vault will remain in sync with the balance left in your account. Just like the cashier the reducer always returns the new state of your application. We will talk about changing/updating the state later in this blog. Right now consider a case that you visit the bank and you didn’t perform any action so the bank balance remains the same. In Redux if you won’t perform any action and you don’t pass the Action as an argument in Reducer than the state will remain the same and the reducer will return the same state as a new state. At this point keep a new state being returned as the same state passed in." }, { "code": null, "e": 11843, "s": 11793, "text": "export default (state) => {\n return state \n}\n" }, { "code": null, "e": 12229, "s": 11843, "text": "When you created an account in your bank, you might have deposited some amount in your account, and if you ask the cashier your bank balance they’ll look it up and tell it to you. In the same way, when you create a Redux Store you do a similar kind of initial deposit which is known as initialState. We will represent this initialState as a second argument passed into the createStore." }, { "code": null, "e": 12280, "s": 12229, "text": "const store = createStore(reducer, initialState);\n" }, { "code": null, "e": 12533, "s": 12280, "text": "So the initialState is like an initial deposit in your Store (bank vault) and if you don’t perform any action this initialState will be returned as the state of the application. Below is the updated code in App.js with initialState in our application. " }, { "code": null, "e": 12540, "s": 12533, "text": "App.js" }, { "code": null, "e": 12551, "s": 12540, "text": "Javascript" }, { "code": "import React, { Component } from \"react\";import HelloTech from \"./HelloTech\";import reducer from \"./reducers\";import { createStore } from \"redux\"; const initialState = { tech: \"React \" };const store = createStore(reducer, initialState); class App extends Component { render() { return <HelloTech tech={this.state.tech}/> } } export default App;", "e": 12903, "s": 12551, "text": null }, { "code": null, "e": 13569, "s": 12905, "text": "At this point, your application will throw an error if you run it because the tech prop still reads, this.state.tech. We have removed the state object from our application so it will be undefined. Right now the state is entirely managed by Store so we need to replace this line with the getState() method which is available when you create a store with createStore() method. If we call the getState method on the created store, we will get the current state of our application. The INITIAL STATE passed into the createStore() is represented by the object {tech: React}. So in our case store.getState() will return this object. Below is the updated code for App.js" }, { "code": null, "e": 13576, "s": 13569, "text": "App.js" }, { "code": null, "e": 13587, "s": 13576, "text": "Javascript" }, { "code": "import React, { Component } from \"react\";import HelloTech from \"./HelloTech\";import { createStore } from \"redux\"; const initialState = { tech: \"React \" };const store = createStore(reducer, initialState); class App extends Component { render() { return <HelloTech tech={store.getState().tech}/> }}", "e": 13892, "s": 13587, "text": null }, { "code": null, "e": 14077, "s": 13894, "text": "Congratulations!!! We just have refactored a simple React application to use Redux. Now the state is managed by the Redux. Now let’s move to the next topic which is Actions in Redux." }, { "code": null, "e": 14543, "s": 14077, "text": "In our bank case scenario, your intention/action was WITHDRAW_MONEY. You have to let your action known to the cashier and the cashier will be responsible for updating your money in your account and handover it to you. The same thing happens in the Redux reducer. In a pure React application, we use the setState method to update the state in our application but here we need to let our action known to the Reducer to update the state in your application. But how?? " }, { "code": null, "e": 14592, "s": 14543, "text": "By dispatching and action! And how to do that???" }, { "code": null, "e": 14777, "s": 14592, "text": "We just need to describe the action by a plain JavaScript object and this object must have a type field to describe the intent of the action. The code will look like something below..." }, { "code": null, "e": 14806, "s": 14777, "text": "{\n type: \"withdraw_money\"\n}\n" }, { "code": null, "e": 15118, "s": 14806, "text": "You won’t get the money if you only tell your action to withdraw money to the cashier. You also need to mention the amount. Many times in our application we also need to add some additional information for full details. So we will add one more information amount in our code and it looks something like below..." }, { "code": null, "e": 15165, "s": 15118, "text": "{\n type: \"withdraw_money\",\n amount: \"$3000\"\n}\n" }, { "code": null, "e": 15513, "s": 15165, "text": "We can include some more information but for now, it’s sufficient and ignore the other details. It’s really up to you that how you structure your action but a standard/common approach in Redux is using the payload field. We put all the required data/information in the payload object that describes the action and it looks something like below..." }, { "code": null, "e": 15578, "s": 15513, "text": "{\n type: \"withdraw_money\",\n payload: {\n amount: \"$3000\"\n }\n}\n" }, { "code": null, "e": 15757, "s": 15578, "text": "We have discussed that Reducer takes two arguments in order to update the application. One is the state and the other is action. So a simple Reducer looks something like below..." }, { "code": null, "e": 15816, "s": 15757, "text": "function reducer(state, action) {\n\n // return new state\n}\n" }, { "code": null, "e": 15963, "s": 15816, "text": "Now to handle the action passed into the Reducer we typically use switch statements in Redux which is nothing but basically, an if/else statement." }, { "code": null, "e": 15974, "s": 15963, "text": "Javascript" }, { "code": "function reducer (state, action) { switch (action.type) { case \"withdraw_money\": //do something break; case \"deposit-money\": //do something break; default: return state; } }", "e": 16245, "s": 15974, "text": null }, { "code": null, "e": 16865, "s": 16247, "text": "In the above example, we have taken two actions. One is withdraw_money and the other one is deposit_money. In your Redux application based on the requirement, you can define as many actions as you want but every action flows through the reducer and that’s what we have done in the above code. In the above code, both actions pass through the same reducer and the reducer differentiates each of them by switching over the action.type. This is how each action can be handled separately in Reducer without any inconvenience. Further in the above code, we just need to define the do something part to return a new state. " }, { "code": null, "e": 17210, "s": 16865, "text": "Let’s go back to the previous example of HelloTech and understand how to update the state of the application. Look at the image given below. There are three buttons and our aim is to change the text/technology whenever a specific button is clicked. To do, so we need to dispatch an action, and the state of the application needs to be updated. " }, { "code": null, "e": 17295, "s": 17210, "text": "For example, if button React-redux is clicked it should look something like below..." }, { "code": null, "e": 17371, "s": 17295, "text": "From the above image, it is clear that we need to describe three actions..." }, { "code": null, "e": 17393, "s": 17371, "text": "For the React button:" }, { "code": null, "e": 17442, "s": 17393, "text": "{\n type: \"SET_TECHNOLOGY\",\n text: \"React\"\n}\n" }, { "code": null, "e": 17470, "s": 17442, "text": "For the React-Redux button:" }, { "code": null, "e": 17527, "s": 17470, "text": "{\n type: \"SET_TECHNOLOGY\",\n text: \"React-redux\"\n}\n" }, { "code": null, "e": 17547, "s": 17527, "text": "For the Elm button:" }, { "code": null, "e": 17590, "s": 17547, "text": "{\n type: \"SET_TECHNOLOGY\",\n text: \"Elm\"\n}\n" }, { "code": null, "e": 17839, "s": 17590, "text": "All three buttons do the same thing. That is the reason we have defined all the three actions with the same type of field. Treat them like customers in a bank with the same intent/action of depositing money (type) but the different amounts (text). " }, { "code": null, "e": 18190, "s": 17839, "text": "If you look at the code we have written for creating actions you’ll notice that few things are repeated in the code. For example, the same type of field is written multiple times which is not good as per the DRY principle in programming. To keep our code DRY we need to look at the new term Action Creators. What are those....??? Let’s discuss that. " }, { "code": null, "e": 18339, "s": 18190, "text": "Actions creators are just simple functions that help you to create actions keeping your code DRY and it returns action objects. Below is the code..." }, { "code": null, "e": 18438, "s": 18339, "text": "export function setTechnology (text) {\n return {\n type: \"SET_TECHNOLOGY\",\n tech: text\n }\n}\n" }, { "code": null, "e": 18681, "s": 18438, "text": "In the above function, we just need to call the function setTechnology and we will get the action back. There is no need to duplicate the code everywhere. We can simplify this more, and we can write the same above code using the ES6 feature. " }, { "code": null, "e": 18748, "s": 18681, "text": "const setTechnology = text => ({ type: \"SET_TECHNOLOGY\", text });\n" }, { "code": null, "e": 19343, "s": 18748, "text": "In this section, we will talk about the folder structure, and we will see how to put everything in specific folders/files to keep the things organized. If we talk about our bank case scenario then you will notice that things are organized at their own place. For example, the cashier sits in their own cubicle/office and vault is safe in separate secure rooms. We will do a similar thing in Redux. It’s totally up to you how you want to structure your project but a common approach in Redux is to create a separate folder/directory for the major components such as reducer, actions, and store. " }, { "code": null, "e": 19603, "s": 19343, "text": "Create three different folders reducers, stores, and actions. In each of the folders create an index.js file that will be the entry point for each of the Redux components. Now refactor the application we have built before and put everything at its own place. " }, { "code": null, "e": 19618, "s": 19603, "text": "store/index.js" }, { "code": null, "e": 19790, "s": 19618, "text": "import { createStore } from \"redux\";\nimport reducer from \"../reducers\";\n\nconst initialState = { tech: \"React \" };\nexport const store = createStore(reducer, initialState);\n" }, { "code": null, "e": 19911, "s": 19790, "text": "Whenever we need Store anywhere in our app we can import the above file mentioning the path import store from “./store”;" }, { "code": null, "e": 19974, "s": 19911, "text": "Now the file App.js will have a slight difference in its code." }, { "code": null, "e": 19985, "s": 19974, "text": "Javascript" }, { "code": "import React, { Component } from \"react\";import HelloTech from \"./HelloTech\";import ButtonGroup from \"./ButtonGroup\";import { store } from \"./store\"; class App extends Component { render() { return [ <HelloTech key={1} tech={store.getState().tech} />, <ButtonGroup key={2} technologies={[\"React\", \"Elm\", \"React-redux\"]} /> ]; }} export default App;", "e": 20354, "s": 19985, "text": null }, { "code": null, "e": 20622, "s": 20356, "text": "In the above code line, 4 has been changed according to the path of Store. We have also imported a component ButtonGroup which is basically responsible for rendering the three buttons. <ButtonGroup /> component takes an array of technologies and spits out buttons. " }, { "code": null, "e": 20895, "s": 20622, "text": "Another thing you need to notice that the App component returns an array. In React 16 you don’t need to use <div> to wrap the JSX element. like we were doing earlier in React. We can use an array and pass the key prop to each element in the array to perform the same job. " }, { "code": null, "e": 21036, "s": 20895, "text": "Let’s move to the ButtonGroup component. It’s a stateless component that takes in an array of technologies which is denoted by technologies." }, { "code": null, "e": 21052, "s": 21036, "text": "ButtonGroup.js " }, { "code": null, "e": 21063, "s": 21052, "text": "Javascript" }, { "code": "import React from \"react\"; const ButtonGroup = ({ technologies }) => ( <div> {technologies.map((tech, i) => ( <button data-tech={tech} key={`btn-${i}`} className=\"hello-btn\" > {tech} </button> ))} </div>); export default ButtonGroup;", "e": 21350, "s": 21063, "text": null }, { "code": null, "e": 21648, "s": 21352, "text": "In the above code the buttons array passed in is [“React”, “Elm”, “React-redux”]. We need to loop over this array using map to render each of the tech in <button></button>. Generated buttons have few attributes as well such as key and data-tech. A completely rendered button will look like this:" }, { "code": null, "e": 21742, "s": 21648, "text": "<button \n data-tech=\"React-redux\" \n key=\"btn-1\" \n className=\"hello-btn\"> React \n</button>\n" }, { "code": null, "e": 21889, "s": 21742, "text": "This will render all the buttons but nothing will happen if you click the buttons. We need to use the onClick handler within the render function. " }, { "code": null, "e": 21900, "s": 21889, "text": "Javascript" }, { "code": "<div> {technologies.map((tech, i) => ( <button data-tech={tech} key={`btn-${i}`} className=\"hello-btn\" onClick={dispatchBtnAction} > {tech} </button> ))} </div>", "e": 22118, "s": 21900, "text": null }, { "code": null, "e": 22210, "s": 22118, "text": "Now, remember the code to dispatch the action for individual tech React, React-redux, Elm. " }, { "code": null, "e": 22261, "s": 22210, "text": " {\n type: \"SET_TECHNOLOGY\",\n tech: \"React\"\n }\n" }, { "code": null, "e": 22301, "s": 22261, "text": "and for React-redux it will be like...." }, { "code": null, "e": 22358, "s": 22301, "text": " {\n type: \"SET_TECHNOLOGY\",\n tech: \"React-redux\"\n }\n" }, { "code": null, "e": 22496, "s": 22358, "text": "So now we need to write the code for dispacthBtnAction function to dispatch the action whenever we click any button. Below is the code..." }, { "code": null, "e": 22606, "s": 22496, "text": "function dispatchBtnAction(e) {\n const tech = e.target.dataset.tech;\n store.dispatch(setTechnology(tech));\n}\n" }, { "code": null, "e": 22687, "s": 22606, "text": " The above code doesn’t make sense to you....right??? Here is the explanation..." }, { "code": null, "e": 22811, "s": 22687, "text": "e.target.dataset.tech get the data attribute set on the button data-tech. Hence, the tech will hold the value of the text. " }, { "code": null, "e": 22874, "s": 22811, "text": "store.dispatch() defines how you dispatch an action in Redux. " }, { "code": null, "e": 22931, "s": 22874, "text": "setTechnology() is the action creator we wrote earlier. " }, { "code": null, "e": 23259, "s": 22931, "text": "Now, remember the same bank case scenario. For your action WITHDRAW_MONEY, you interact with the cashier...yeah??? This means if you want your money, your action needs to be passed through the cashier. The same thing is happening in the above code. When you are dispatching an action, it passes through the Reducer (cashier). " }, { "code": null, "e": 23534, "s": 23259, "text": "Till now the cashier in the bank did nothing with WITHDRAW_MONEY action. We expect the cashier to update the money in the bank vault and hand over the money to you. In our Redux app, we also want our Reducer to return a new state which should have the action text in there. " }, { "code": null, "e": 23642, "s": 23534, "text": "What exactly we mean is that if the current state is { tech: “React”} then with a new action given below..." }, { "code": null, "e": 23699, "s": 23642, "text": "{\n type: \"SET_TECHNOLOGY\",\n text: \"React-Redux\"\n}\n" }, { "code": null, "e": 23751, "s": 23699, "text": "We expect the new state to be {tech: “React-Redux”}" }, { "code": null, "e": 24268, "s": 23751, "text": "We have discussed earlier that to handle different action types we can use switch statements in our Reducer code with different actions in mind. In our bank case scenario, the cashier will respond according to the intent/action given by the customer. These actions could be WITHDRAW_MONEY, DEPOSIT_MONEY, or just SAY_HELLO. Similarly, the reducer will respond based on your intent. Right now we just have one case SET_TECHNOLOGY so the code will look like something below...(Our cashier that actually gives us money)" }, { "code": null, "e": 24279, "s": 24268, "text": "Javascript" }, { "code": "export default (state, action) => { switch (action.type) { case \"SET_TECHNOLOGY\": return { ...state, tech: action.text }; default: return state; }};", "e": 24467, "s": 24279, "text": null }, { "code": null, "e": 24712, "s": 24469, "text": "Here notice that we are returning a new copy of the state, a new object using the ES6 spread operator ...state. We are not supposed to mutate the state received in our Reducer. Technically you should not write the code something like below..." }, { "code": null, "e": 24889, "s": 24712, "text": "export default (state, action) => {\n switch (action.type) {\n case \"SET_TECHNOLOGY\":\n state.tech = action.text; \n return state;\n\n default:\n return state;\n }\n};\n" }, { "code": null, "e": 25252, "s": 24889, "text": "Also, Reducer should be pure functions in our code with no side effects — No API calls or updating a value outside the scope of the function. Now the cashier is responding to your action and giving you the money you requested for. But again if you click the button you can not see the text updated on your screen.... let’s discuss it with a new term subscribe. " }, { "code": null, "e": 25763, "s": 25252, "text": "Well, you have received your money from the cashier but what about some sort of personal receipt or notification/alert via email/mobile. Most likely you receive a notification regarding your transaction and the balance left in your account. You receive that because you have subscribed to receive transaction notifications from the bank either by email/text. A similar thing happens in Redux. To receive an update after the successful action initiated, you need to subscribe to them. Now the question is...how?" }, { "code": null, "e": 26041, "s": 25763, "text": "Redux provides subscribe method to do this job. We need to use the store.subscribe() function, and we need to pass the argument in it. Whenever there’s a state update this argument will be invoked. We need to keep in mind that the argument passed into it should be a function. " }, { "code": null, "e": 26265, "s": 26041, "text": "Once the state is updated we expect our application to re-render the new state values. The entire application renders in the main index.js file of our application. If you open this file you will find the code given below..." }, { "code": null, "e": 26323, "s": 26265, "text": "ReactDOM.render(<App />, document.getElementById(\"root\")\n" }, { "code": null, "e": 26386, "s": 26323, "text": "The above function can be also written using the ES6 feature. " }, { "code": null, "e": 26477, "s": 26386, "text": "const render = () => ReactDOM.render(<App />, document.getElementById(\"root\"));\nrender();\n" }, { "code": null, "e": 26691, "s": 26477, "text": "In the above code, we just have represented the app into a function, and then we have invoked the function to render the app. Now we can pass the above-refactored render logic into our store.subscribe() function. " }, { "code": null, "e": 26717, "s": 26691, "text": "store.subscribe(render);\n" }, { "code": null, "e": 26862, "s": 26717, "text": "Now the <App /> will be re-rendered with new state value whenever there’s a successful state update to the store. Below is the <App/> component." }, { "code": null, "e": 26873, "s": 26862, "text": "Javascript" }, { "code": "class App extends Component { render() { return [ <HelloTech key={1} tech={store.getState().tech} />, <ButtonGroup key={2} technologies={[\"React\", \"Elm\", \"React-redux\"]} /> ]; }}", "e": 27070, "s": 26873, "text": null }, { "code": null, "e": 27288, "s": 27072, "text": "store.getState() in line 4 will fetch the updated state whenever a re-render occurs. Now the app will work as you expect it to work and you will see the updated technology whenever you will click a specific button. " }, { "code": null, "e": 27431, "s": 27288, "text": "Congratulations!!! We are successfully dispatching an action, receiving money from the Cashier, and then subscribing to receive notifications." }, { "code": null, "e": 27452, "s": 27431, "text": "That’s it for now..." }, { "code": null, "e": 27874, "s": 27452, "text": "We have discussed all the main terminology of Redux, and we have tried our best to explain each one of them in the simplest way. But the journey of learning Redux doesn’t end here. We suggest you practice some more exercises on Redux and build some more complex projects. Also, don’t get afraid of so many libraries available in Redux. Each library has its own specific job that you will understand slowly and gradually. " }, { "code": null, "e": 27915, "s": 27874, "text": "We hope Redux won’t scare you anymore!!!" }, { "code": null, "e": 27921, "s": 27915, "text": "Redux" }, { "code": null, "e": 27927, "s": 27921, "text": "GBlog" }, { "code": null, "e": 27935, "s": 27927, "text": "ReactJS" }, { "code": null, "e": 27952, "s": 27935, "text": "Web Technologies" } ]
tag_name element method – Selenium Python
30 Apr, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies This article revolves around how to use tag_name method in Selenium. tag_name method is used to get name of tag you are referring to. element.tag_name Example – <input type="text" name="passwd" id="passwd-id" /> To find an element one needs to use one of the locating strategies, For example, element = driver.find_element_by_id("passwd-id") element = driver.find_element_by_name("passwd") element = driver.find_element_by_xpath("//input[@id='passwd-id']") Also, to find multiple elements, we can use – elements = driver.find_elements_by_name("passwd") Now one can get tag name of this element with – element.tag_name Let’s try to get element and its tag_name at geeksforgeeks using tag_name method.Program – # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_id("gsc-i-id2") # get tag_nameprint(element.tag_name) Output- Terminal Output – Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Apr, 2020" }, { "code": null, "e": 585, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies" }, { "code": null, "e": 719, "s": 585, "text": "This article revolves around how to use tag_name method in Selenium. tag_name method is used to get name of tag you are referring to." }, { "code": null, "e": 736, "s": 719, "text": "element.tag_name" }, { "code": null, "e": 746, "s": 736, "text": "Example –" }, { "code": "<input type=\"text\" name=\"passwd\" id=\"passwd-id\" />", "e": 797, "s": 746, "text": null }, { "code": null, "e": 878, "s": 797, "text": "To find an element one needs to use one of the locating strategies, For example," }, { "code": null, "e": 1042, "s": 878, "text": "element = driver.find_element_by_id(\"passwd-id\")\nelement = driver.find_element_by_name(\"passwd\")\nelement = driver.find_element_by_xpath(\"//input[@id='passwd-id']\")" }, { "code": null, "e": 1088, "s": 1042, "text": "Also, to find multiple elements, we can use –" }, { "code": null, "e": 1138, "s": 1088, "text": "elements = driver.find_elements_by_name(\"passwd\")" }, { "code": null, "e": 1186, "s": 1138, "text": "Now one can get tag name of this element with –" }, { "code": null, "e": 1203, "s": 1186, "text": "element.tag_name" }, { "code": null, "e": 1294, "s": 1203, "text": "Let’s try to get element and its tag_name at geeksforgeeks using tag_name method.Program –" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_id(\"gsc-i-id2\") # get tag_nameprint(element.tag_name)", "e": 1570, "s": 1294, "text": null }, { "code": null, "e": 1578, "s": 1570, "text": "Output-" }, { "code": null, "e": 1596, "s": 1578, "text": "Terminal Output –" }, { "code": null, "e": 1612, "s": 1596, "text": "Python-selenium" }, { "code": null, "e": 1621, "s": 1612, "text": "selenium" }, { "code": null, "e": 1628, "s": 1621, "text": "Python" } ]
How to create pie chart in react using material UI and DevExpress ?
19 Jul, 2021 DevExpress: DevExpress is a package for controlling and building the user interface of the Window, Mobile, and other applications. Pie Charts: A pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. It depicts a special chart that uses “pie slices”, where each sector shows the relative sizes of data. Steps for creating React Application And Installing Module: Step 1: Create a React application using the following command.npx create-react-app foldername Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command.cd foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, install the required modules using the following command.npm i --save @devexpress/dx-react-core @devexpress/dx-react-chart npm install @material-ui/core npm i --save @devexpress/dx-react-chart-material-ui Step 3: After creating the ReactJS application, install the required modules using the following command. npm i --save @devexpress/dx-react-core @devexpress/dx-react-chart npm install @material-ui/core npm i --save @devexpress/dx-react-chart-material-ui Project Structure: It will look like the following : Project Structure Example: Now write down the following code in the App.js file. Here, the App is our default component where we have written our code. App.js import React from "react";import Paper from '@material-ui/core/Paper';import { Chart, PieSeries, Title} from '@devexpress/dx-react-chart-material-ui'; const App = () => { // Sample dataconst data = [ { argument:'Monday', value:10 }, { argument:'Tuesday', value:40 }, { argument:'Wednesday', value:10 }, { argument:'Thursday', value:20 }, { argument:'Friday', value:20 },];return ( <Paper> <Chart data={data} > <PieSeries valueField="value" argumentField="argument" /> <Title text="Studies per day"/> </Chart> </Paper>);} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Output Material-UI Picked React-Questions JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request How to fetch data from an API in ReactJS ? Axios in React: A Guide for Beginners How to redirect to another page in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jul, 2021" }, { "code": null, "e": 159, "s": 28, "text": "DevExpress: DevExpress is a package for controlling and building the user interface of the Window, Mobile, and other applications." }, { "code": null, "e": 388, "s": 159, "text": "Pie Charts: A pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. It depicts a special chart that uses “pie slices”, where each sector shows the relative sizes of data. " }, { "code": null, "e": 448, "s": 388, "text": "Steps for creating React Application And Installing Module:" }, { "code": null, "e": 543, "s": 448, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 607, "s": 543, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 639, "s": 607, "text": "npx create-react-app foldername" }, { "code": null, "e": 755, "s": 641, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command.cd foldername" }, { "code": null, "e": 856, "s": 755, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command." }, { "code": null, "e": 870, "s": 856, "text": "cd foldername" }, { "code": null, "e": 1123, "s": 870, "text": "Step 3: After creating the ReactJS application, install the required modules using the following command.npm i --save @devexpress/dx-react-core @devexpress/dx-react-chart\nnpm install @material-ui/core\nnpm i --save @devexpress/dx-react-chart-material-ui" }, { "code": null, "e": 1229, "s": 1123, "text": "Step 3: After creating the ReactJS application, install the required modules using the following command." }, { "code": null, "e": 1377, "s": 1229, "text": "npm i --save @devexpress/dx-react-core @devexpress/dx-react-chart\nnpm install @material-ui/core\nnpm i --save @devexpress/dx-react-chart-material-ui" }, { "code": null, "e": 1430, "s": 1377, "text": "Project Structure: It will look like the following :" }, { "code": null, "e": 1448, "s": 1430, "text": "Project Structure" }, { "code": null, "e": 1582, "s": 1448, "text": "Example: Now write down the following code in the App.js file. Here, the App is our default component where we have written our code." }, { "code": null, "e": 1589, "s": 1582, "text": "App.js" }, { "code": "import React from \"react\";import Paper from '@material-ui/core/Paper';import { Chart, PieSeries, Title} from '@devexpress/dx-react-chart-material-ui'; const App = () => { // Sample dataconst data = [ { argument:'Monday', value:10 }, { argument:'Tuesday', value:40 }, { argument:'Wednesday', value:10 }, { argument:'Thursday', value:20 }, { argument:'Friday', value:20 },];return ( <Paper> <Chart data={data} > <PieSeries valueField=\"value\" argumentField=\"argument\" /> <Title text=\"Studies per day\"/> </Chart> </Paper>);} export default App;", "e": 2171, "s": 1589, "text": null }, { "code": null, "e": 2284, "s": 2171, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2294, "s": 2284, "text": "npm start" }, { "code": null, "e": 2393, "s": 2294, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2400, "s": 2393, "text": "Output" }, { "code": null, "e": 2412, "s": 2400, "text": "Material-UI" }, { "code": null, "e": 2419, "s": 2412, "text": "Picked" }, { "code": null, "e": 2435, "s": 2419, "text": "React-Questions" }, { "code": null, "e": 2446, "s": 2435, "text": "JavaScript" }, { "code": null, "e": 2454, "s": 2446, "text": "ReactJS" }, { "code": null, "e": 2471, "s": 2454, "text": "Web Technologies" }, { "code": null, "e": 2569, "s": 2471, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2630, "s": 2569, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2702, "s": 2630, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2742, "s": 2702, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2784, "s": 2742, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2825, "s": 2784, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2868, "s": 2825, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2906, "s": 2868, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2951, "s": 2906, "text": "How to redirect to another page in ReactJS ?" } ]
Fakemailer – Send email anonymously in Kali Linux
23 Aug, 2021 Anonymity plays an important role in the life of a cybersecurity researchers and law and enforcement agencies. Sometimes a situation occurs in which you have to send an email anonymously to another security researcher in order to maintain integrity which is a third important part of the CIA model. So here Fakemailer plays an important role to send mails anonymously. Fakemailer is a free and open-source tool available on GitHub. Fakemailer provides a command-line interface that you can run on Kali Linux. The interactive console provides a number of helpful features, such as command completion and contextual help. Fakemailer helps law and enforcement agencies to investigate cybercrimes such as cyber grooming, cyberstalking, cyberbullying, and spreading misinformation. Step 1: Open your kali linux operating system terminal and use the following command to install the tool. git clone https://github.com/htr-tech/fake-mailer cd fake-mailer Step 2: Now you are in the directory of Fakemailer tool. Now use the following command to run the tool. python2 mailer.py Now we will see an example to use the tool. You can see we have provided the necessary details to the tool and the tool has sent the mail anonymously. This is a very useful tool for security researchers. Similarly, you can perform experiments. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples SORT command in Linux/Unix with examples Conditional Statements | Shell Script 'crontab' in Linux with Examples TCP Server-Client implementation in C Tail command in Linux with examples Docker - COPY Instruction scp command in Linux with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2021" }, { "code": null, "e": 805, "s": 28, "text": "Anonymity plays an important role in the life of a cybersecurity researchers and law and enforcement agencies. Sometimes a situation occurs in which you have to send an email anonymously to another security researcher in order to maintain integrity which is a third important part of the CIA model. So here Fakemailer plays an important role to send mails anonymously. Fakemailer is a free and open-source tool available on GitHub. Fakemailer provides a command-line interface that you can run on Kali Linux. The interactive console provides a number of helpful features, such as command completion and contextual help. Fakemailer helps law and enforcement agencies to investigate cybercrimes such as cyber grooming, cyberstalking, cyberbullying, and spreading misinformation." }, { "code": null, "e": 911, "s": 805, "text": "Step 1: Open your kali linux operating system terminal and use the following command to install the tool." }, { "code": null, "e": 976, "s": 911, "text": "git clone https://github.com/htr-tech/fake-mailer\ncd fake-mailer" }, { "code": null, "e": 1080, "s": 976, "text": "Step 2: Now you are in the directory of Fakemailer tool. Now use the following command to run the tool." }, { "code": null, "e": 1098, "s": 1080, "text": "python2 mailer.py" }, { "code": null, "e": 1142, "s": 1098, "text": "Now we will see an example to use the tool." }, { "code": null, "e": 1342, "s": 1142, "text": "You can see we have provided the necessary details to the tool and the tool has sent the mail anonymously. This is a very useful tool for security researchers. Similarly, you can perform experiments." }, { "code": null, "e": 1353, "s": 1342, "text": "Kali-Linux" }, { "code": null, "e": 1365, "s": 1353, "text": "Linux-Tools" }, { "code": null, "e": 1376, "s": 1365, "text": "Linux-Unix" }, { "code": null, "e": 1474, "s": 1376, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1509, "s": 1474, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 1544, "s": 1509, "text": "tar command in Linux with examples" }, { "code": null, "e": 1580, "s": 1544, "text": "curl command in Linux with Examples" }, { "code": null, "e": 1621, "s": 1580, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 1659, "s": 1621, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 1692, "s": 1659, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 1730, "s": 1692, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 1766, "s": 1730, "text": "Tail command in Linux with examples" }, { "code": null, "e": 1792, "s": 1766, "text": "Docker - COPY Instruction" } ]
Python | Search elements in a Matrix
30 Dec, 2020 Python supports a list as its list element and hence a matrix can be formed. Sometimes we might have a utility in which we require to perform a search in that list of list i.e matrix and its a very common in all the domains of coding. Let’s discuss certain ways in which this can be performed. Method #1 : Using any() + list comprehensionThe any function can be used to perform the task of if condition and the check for each element in the nested list can be computed using the list comprehension. # Python3 code to demonstrate# Search in Matrix# using any() + list comprehension # initializing listtest_list = [[4, 5, 6], [10, 2, 13], [1, 11, 18]] # printing original list print("The original list : " + str(test_list)) # using any() + list comprehension# to Search in Matrixres = any(13 in sub for sub in test_list) # printing resultprint("Is 13 present in Matrix ? : " + str(res)) The original list : [[4, 5, 6], [10, 2, 13], [1, 11, 18]] Is 13 present in Matrix ? : True Method #2 : Using set.issubset() + itertools.chain()The issubset method can be used to check for the membership in sublist and chain function can be used to perform this task for the each element in the Matrix, in a faster way as it works on iterators. # Python3 code to demonstrate# Search in Matrix# using set.issubset() + itertools.chain()from itertools import chain # initializing listtest_list = [[4, 5, 6], [10, 2, 13], [1, 11, 18]] # printing original list print("The original list : " + str(test_list)) # using set.issubset() + itertools.chain()# to Search in Matrixres = {13}.issubset(chain.from_iterable(test_list)) # printing resultprint("Is 13 present in Matrix ? : " + str(res)) The original list : [[4, 5, 6], [10, 2, 13], [1, 11, 18]] Is 13 present in Matrix ? : True Marketing Python list-programs Python matrix-program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Dec, 2020" }, { "code": null, "e": 322, "s": 28, "text": "Python supports a list as its list element and hence a matrix can be formed. Sometimes we might have a utility in which we require to perform a search in that list of list i.e matrix and its a very common in all the domains of coding. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 527, "s": 322, "text": "Method #1 : Using any() + list comprehensionThe any function can be used to perform the task of if condition and the check for each element in the nested list can be computed using the list comprehension." }, { "code": "# Python3 code to demonstrate# Search in Matrix# using any() + list comprehension # initializing listtest_list = [[4, 5, 6], [10, 2, 13], [1, 11, 18]] # printing original list print(\"The original list : \" + str(test_list)) # using any() + list comprehension# to Search in Matrixres = any(13 in sub for sub in test_list) # printing resultprint(\"Is 13 present in Matrix ? : \" + str(res))", "e": 941, "s": 527, "text": null }, { "code": null, "e": 1033, "s": 941, "text": "The original list : [[4, 5, 6], [10, 2, 13], [1, 11, 18]]\nIs 13 present in Matrix ? : True\n" }, { "code": null, "e": 1288, "s": 1035, "text": "Method #2 : Using set.issubset() + itertools.chain()The issubset method can be used to check for the membership in sublist and chain function can be used to perform this task for the each element in the Matrix, in a faster way as it works on iterators." }, { "code": "# Python3 code to demonstrate# Search in Matrix# using set.issubset() + itertools.chain()from itertools import chain # initializing listtest_list = [[4, 5, 6], [10, 2, 13], [1, 11, 18]] # printing original list print(\"The original list : \" + str(test_list)) # using set.issubset() + itertools.chain()# to Search in Matrixres = {13}.issubset(chain.from_iterable(test_list)) # printing resultprint(\"Is 13 present in Matrix ? : \" + str(res))", "e": 1755, "s": 1288, "text": null }, { "code": null, "e": 1847, "s": 1755, "text": "The original list : [[4, 5, 6], [10, 2, 13], [1, 11, 18]]\nIs 13 present in Matrix ? : True\n" }, { "code": null, "e": 1857, "s": 1847, "text": "Marketing" }, { "code": null, "e": 1878, "s": 1857, "text": "Python list-programs" }, { "code": null, "e": 1900, "s": 1878, "text": "Python matrix-program" }, { "code": null, "e": 1907, "s": 1900, "text": "Python" }, { "code": null, "e": 1923, "s": 1907, "text": "Python Programs" } ]
How to get Time Difference in Minutes in PHP ?
26 May, 2021 In this article, we will learn how to get time difference in minutes using PHP. We will be using the built-in function date_diff() to get the time difference in minutes. For this, we will be needed a start date and end date to calculate their time difference in minutes using the date_diff() function. Syntax: date_diff($datetime1, $datetime2); Parameters: The date_diff() function accepts two parameters as mentioned above and described below. $datetime1: This is a mandatory parameter as it specifies the start/first DateTime object. $datetime2: This is a mandatory parameter as it specifies the end/second DateTime object. Return Value: This function returns the difference between the first DateTime object and the second DateTime object otherwise it returns false on failure. Example 1: The below program illustrates the date_diff() function to get the time difference in minutes. PHP <?php // PHP Program to illustrate//date_diff() function // Creating DateTime Objects$dateTimeObject1 = date_create('2019-05-18'); $dateTimeObject2 = date_create('2020-05-18'); // Calculating the difference between DateTime Objects$interval = date_diff($dateTimeObject1, $dateTimeObject2); echo ("Difference in days is: "); // Printing the result in days formatecho $interval->format('%R%a days');echo "\n<br/>";$min = $interval->days * 24 * 60;$min += $interval->h * 60;$min += $interval->i; // Printing the Result in Minutes format.echo("Difference in minutes is: ");echo $min.' minutes';?> Output: Difference in days is: +366 days Difference in minutes is: 527040 minutes Example 2: PHP <?php // PHP Program to illustrate // date_diff() function // Creating DateTime Objects $dateTimeObject1 = date_create('2020-05-14'); $dateTimeObject2 = date_create('2021-02-14'); // Calculating the difference between DateTime Objects $interval = date_diff($dateTimeObject1, $dateTimeObject2); echo ("Difference in days is: "); // Printing the result in days format echo $interval->format('%R%a days'); echo "\n<br/>"; $min = $interval->days * 24 * 60; $min += $interval->h * 60; $min += $interval->i; // Printing the Result in Minutes format. echo("Difference in minutes is: "); echo $min.' minutes';?> Output: Difference in days is: +276 days Difference in minutes is: 397440 minutes Example 3: PHP <?php // PHP program to illustrate // date_diff() function // Creating DateTime objects$dateTimeObject1 = date_create('19:15:00'); $dateTimeObject2 = date_create('12:15:00'); // Calculating the difference between DateTime objects$interval = date_diff($dateTimeObject1, $dateTimeObject2); // Printing result in hoursecho ("Difference in hours is:");echo $interval->h;echo "\n<br/>";$minutes = $interval->days * 24 * 60;$minutes += $interval->h * 60;$minutes += $interval->i; //Printing result in minutesecho("Difference in minutes is:");echo $minutes.' minutes';?> Output: Difference in hours is:7 Difference in minutes is:420 minutes PHP-date-time PHP-function PHP-Questions Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to delete an array element based on key in PHP? PHP in_array() Function How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2021" }, { "code": null, "e": 109, "s": 28, "text": "In this article, we will learn how to get time difference in minutes using PHP. " }, { "code": null, "e": 331, "s": 109, "text": "We will be using the built-in function date_diff() to get the time difference in minutes. For this, we will be needed a start date and end date to calculate their time difference in minutes using the date_diff() function." }, { "code": null, "e": 339, "s": 331, "text": "Syntax:" }, { "code": null, "e": 374, "s": 339, "text": "date_diff($datetime1, $datetime2);" }, { "code": null, "e": 474, "s": 374, "text": "Parameters: The date_diff() function accepts two parameters as mentioned above and described below." }, { "code": null, "e": 565, "s": 474, "text": "$datetime1: This is a mandatory parameter as it specifies the start/first DateTime object." }, { "code": null, "e": 655, "s": 565, "text": "$datetime2: This is a mandatory parameter as it specifies the end/second DateTime object." }, { "code": null, "e": 810, "s": 655, "text": "Return Value: This function returns the difference between the first DateTime object and the second DateTime object otherwise it returns false on failure." }, { "code": null, "e": 915, "s": 810, "text": "Example 1: The below program illustrates the date_diff() function to get the time difference in minutes." }, { "code": null, "e": 919, "s": 915, "text": "PHP" }, { "code": "<?php // PHP Program to illustrate//date_diff() function // Creating DateTime Objects$dateTimeObject1 = date_create('2019-05-18'); $dateTimeObject2 = date_create('2020-05-18'); // Calculating the difference between DateTime Objects$interval = date_diff($dateTimeObject1, $dateTimeObject2); echo (\"Difference in days is: \"); // Printing the result in days formatecho $interval->format('%R%a days');echo \"\\n<br/>\";$min = $interval->days * 24 * 60;$min += $interval->h * 60;$min += $interval->i; // Printing the Result in Minutes format.echo(\"Difference in minutes is: \");echo $min.' minutes';?>", "e": 1521, "s": 919, "text": null }, { "code": null, "e": 1529, "s": 1521, "text": "Output:" }, { "code": null, "e": 1603, "s": 1529, "text": "Difference in days is: +366 days\nDifference in minutes is: 527040 minutes" }, { "code": null, "e": 1614, "s": 1603, "text": "Example 2:" }, { "code": null, "e": 1618, "s": 1614, "text": "PHP" }, { "code": "<?php // PHP Program to illustrate // date_diff() function // Creating DateTime Objects $dateTimeObject1 = date_create('2020-05-14'); $dateTimeObject2 = date_create('2021-02-14'); // Calculating the difference between DateTime Objects $interval = date_diff($dateTimeObject1, $dateTimeObject2); echo (\"Difference in days is: \"); // Printing the result in days format echo $interval->format('%R%a days'); echo \"\\n<br/>\"; $min = $interval->days * 24 * 60; $min += $interval->h * 60; $min += $interval->i; // Printing the Result in Minutes format. echo(\"Difference in minutes is: \"); echo $min.' minutes';?>", "e": 2251, "s": 1618, "text": null }, { "code": null, "e": 2259, "s": 2251, "text": "Output:" }, { "code": null, "e": 2333, "s": 2259, "text": "Difference in days is: +276 days\nDifference in minutes is: 397440 minutes" }, { "code": null, "e": 2344, "s": 2333, "text": "Example 3:" }, { "code": null, "e": 2348, "s": 2344, "text": "PHP" }, { "code": "<?php // PHP program to illustrate // date_diff() function // Creating DateTime objects$dateTimeObject1 = date_create('19:15:00'); $dateTimeObject2 = date_create('12:15:00'); // Calculating the difference between DateTime objects$interval = date_diff($dateTimeObject1, $dateTimeObject2); // Printing result in hoursecho (\"Difference in hours is:\");echo $interval->h;echo \"\\n<br/>\";$minutes = $interval->days * 24 * 60;$minutes += $interval->h * 60;$minutes += $interval->i; //Printing result in minutesecho(\"Difference in minutes is:\");echo $minutes.' minutes';?>", "e": 2920, "s": 2348, "text": null }, { "code": null, "e": 2928, "s": 2920, "text": "Output:" }, { "code": null, "e": 2990, "s": 2928, "text": "Difference in hours is:7\nDifference in minutes is:420 minutes" }, { "code": null, "e": 3004, "s": 2990, "text": "PHP-date-time" }, { "code": null, "e": 3017, "s": 3004, "text": "PHP-function" }, { "code": null, "e": 3031, "s": 3017, "text": "PHP-Questions" }, { "code": null, "e": 3038, "s": 3031, "text": "Picked" }, { "code": null, "e": 3042, "s": 3038, "text": "PHP" }, { "code": null, "e": 3059, "s": 3042, "text": "Web Technologies" }, { "code": null, "e": 3063, "s": 3059, "text": "PHP" }, { "code": null, "e": 3161, "s": 3063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3206, "s": 3161, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 3258, "s": 3206, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 3282, "s": 3258, "text": "PHP in_array() Function" }, { "code": null, "e": 3332, "s": 3282, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 3372, "s": 3332, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3405, "s": 3372, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3467, "s": 3405, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3517, "s": 3467, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3578, "s": 3517, "text": "Difference between var, let and const keywords in JavaScript" } ]
Importance of yield() method in Java?
A yield() method is a static method of Thread class and it can stop the currently executing thread and will give a chance to other waiting threads of the same priority. If in case there are no waiting threads or if all the waiting threads have low priority then the same thread will continue its execution. The advantage of yield() method is to get a chance to execute other waiting threads so if our current thread takes more time to execute and allocate processor to other threads. public static void yield() class MyThread extends Thread { public void run() { for (int i = 0; i < 5; ++i) { Thread.yield(); // By calling this method, MyThread stop its execution and giving a chance to a main thread System.out.println("Thread started:" + Thread.currentThread().getName()); } System.out.println("Thread ended:" + Thread.currentThread().getName()); } } public class YieldMethodTest { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); for (int i = 0; i < 5; ++i) { System.out.println("Thread started:" + Thread.currentThread().getName()); } System.out.println("Thread ended:" + Thread.currentThread().getName()); } } Thread started:main Thread started:Thread-0 Thread started:main Thread started:Thread-0 Thread started:main Thread started:Thread-0 Thread started:main Thread started:Thread-0 Thread started:main Thread started:Thread-0 Thread ended:main Thread ended:Thread-0
[ { "code": null, "e": 1546, "s": 1062, "text": "A yield() method is a static method of Thread class and it can stop the currently executing thread and will give a chance to other waiting threads of the same priority. If in case there are no waiting threads or if all the waiting threads have low priority then the same thread will continue its execution. The advantage of yield() method is to get a chance to execute other waiting threads so if our current thread takes more time to execute and allocate processor to other threads." }, { "code": null, "e": 1573, "s": 1546, "text": "public static void yield()" }, { "code": null, "e": 2306, "s": 1573, "text": "class MyThread extends Thread {\n public void run() {\n for (int i = 0; i < 5; ++i) {\n Thread.yield(); // By calling this method, MyThread stop its execution and giving a chance to a main thread\n System.out.println(\"Thread started:\" + Thread.currentThread().getName());\n }\n System.out.println(\"Thread ended:\" + Thread.currentThread().getName());\n }\n}\npublic class YieldMethodTest {\n public static void main(String[] args) {\n MyThread thread = new MyThread();\n thread.start();\n for (int i = 0; i < 5; ++i) {\n System.out.println(\"Thread started:\" + Thread.currentThread().getName());\n }\n System.out.println(\"Thread ended:\" + Thread.currentThread().getName());\n }\n}" }, { "code": null, "e": 2566, "s": 2306, "text": "Thread started:main\nThread started:Thread-0\nThread started:main\nThread started:Thread-0\nThread started:main\nThread started:Thread-0\nThread started:main\nThread started:Thread-0\nThread started:main\nThread started:Thread-0\nThread ended:main\nThread ended:Thread-0" } ]
JavaScript Array reduce() Method
Javascript array reduce() method applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value. Its syntax is as follows − array.reduce(callback[, initialValue]); callback − Function to execute on each value in the array. callback − Function to execute on each value in the array. initialValue − Object to use as the first argument to the first call of the callback. initialValue − Object to use as the first argument to the first call of the callback. Returns the reduced single value of the array. This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script. if (!Array.prototype.reduce) { Array.prototype.reduce = function(fun /*, initial*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); // no value to return if no initial value and an empty array if (len == 0 && arguments.length == 1) throw new TypeError(); var i = 0; if (arguments.length >= 2) { var rv = arguments[1]; } else { do { if (i in this) { rv = this[i++]; break; } // if array contains no values, no initial value to return if (++i >= len) throw new TypeError(); } while (true); } for (; i < len; i++) { if (i in this) rv = fun.call(null, rv, this[i], i, this); } return rv; }; } Try the following example. <html> <head> <title>JavaScript Array reduce Method</title> </head> <body> <script type = "text/javascript"> if (!Array.prototype.reduce) { Array.prototype.reduce = function(fun /*, initial*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); // no value to return if no initial value and an empty array if (len == 0 && arguments.length == 1) throw new TypeError(); var i = 0; if (arguments.length >= 2) { var rv = arguments[1]; } else { do { if (i in this) { rv = this[i++]; break; } // if array contains no values, no initial value to return if (++i >= len) throw new TypeError(); } while (true); } for (; i < len; i++) { if (i in this) rv = fun.call(null, rv, this[i], i, this); } return rv; }; } var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; }); document.write("total is : " + total ); </script> </body> </html> total is : 6 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2621, "s": 2466, "text": "Javascript array reduce() method applies a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value." }, { "code": null, "e": 2648, "s": 2621, "text": "Its syntax is as follows −" }, { "code": null, "e": 2689, "s": 2648, "text": "array.reduce(callback[, initialValue]);\n" }, { "code": null, "e": 2748, "s": 2689, "text": "callback − Function to execute on each value in the array." }, { "code": null, "e": 2807, "s": 2748, "text": "callback − Function to execute on each value in the array." }, { "code": null, "e": 2893, "s": 2807, "text": "initialValue − Object to use as the first argument to the first call of the callback." }, { "code": null, "e": 2979, "s": 2893, "text": "initialValue − Object to use as the first argument to the first call of the callback." }, { "code": null, "e": 3026, "s": 2979, "text": "Returns the reduced single value of the array." }, { "code": null, "e": 3241, "s": 3026, "text": "This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script." }, { "code": null, "e": 4122, "s": 3241, "text": "if (!Array.prototype.reduce) {\n Array.prototype.reduce = function(fun /*, initial*/) {\n var len = this.length;\n \n if (typeof fun != \"function\")\n throw new TypeError();\n \n // no value to return if no initial value and an empty array\n if (len == 0 && arguments.length == 1)\n throw new TypeError();\n \n var i = 0;\n if (arguments.length >= 2) {\n var rv = arguments[1];\n } else {\n do {\n if (i in this) {\n rv = this[i++];\n break;\n }\n \n // if array contains no values, no initial value to return\n if (++i >= len)\n throw new TypeError();\n }\n while (true);\n }\n for (; i < len; i++) {\n if (i in this)\n rv = fun.call(null, rv, this[i], i, this);\n }\n return rv;\n };\n}" }, { "code": null, "e": 4149, "s": 4122, "text": "Try the following example." }, { "code": null, "e": 5639, "s": 4149, "text": "<html>\n <head>\n <title>JavaScript Array reduce Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n if (!Array.prototype.reduce) {\n Array.prototype.reduce = function(fun /*, initial*/) {\n var len = this.length;\n \n if (typeof fun != \"function\")\n throw new TypeError();\n \n // no value to return if no initial value and an empty array\n if (len == 0 && arguments.length == 1)\n throw new TypeError();\n \n var i = 0;\n if (arguments.length >= 2) {\n var rv = arguments[1];\n } else {\n do {\n if (i in this) {\n rv = this[i++];\n break;\n }\n \n // if array contains no values, no initial value to return\n if (++i >= len)\n throw new TypeError();\n }\n while (true);\n }\n for (; i < len; i++) {\n if (i in this)\n rv = fun.call(null, rv, this[i], i, this);\n }\n return rv;\n };\n }\n var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });\n document.write(\"total is : \" + total ); \n </script> \n </body>\n</html>" }, { "code": null, "e": 5653, "s": 5639, "text": "total is : 6\n" }, { "code": null, "e": 5688, "s": 5653, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5702, "s": 5688, "text": " Anadi Sharma" }, { "code": null, "e": 5736, "s": 5702, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 5750, "s": 5736, "text": " Lets Kode It" }, { "code": null, "e": 5785, "s": 5750, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5802, "s": 5785, "text": " Frahaan Hussain" }, { "code": null, "e": 5837, "s": 5802, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5854, "s": 5837, "text": " Frahaan Hussain" }, { "code": null, "e": 5887, "s": 5854, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 5915, "s": 5887, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5949, "s": 5915, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 5977, "s": 5949, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5984, "s": 5977, "text": " Print" }, { "code": null, "e": 5995, "s": 5984, "text": " Add Notes" } ]
Pascal - Relational Operators
Following table shows all the relational operators supported by Pascal. Assume variable A holds 10 and variable B holds 20, then − Try the following example to understand all the relational operators available in Pascal programming language − program showRelations; var a, b: integer; begin a := 21; b := 10; if a = b then writeln('Line 1 - a is equal to b' ) else writeln('Line 1 - a is not equal to b' ); if a < b then writeln('Line 2 - a is less than b' ) else writeln('Line 2 - a is not less than b' ); if a > b then writeln('Line 3 - a is greater than b' ) else writeln('Line 3 - a is greater than b' ); (* Lets change value of a and b *) a := 5; b := 20; if a <= b then writeln('Line 4 - a is either less than or equal to b' ); if ( b >= a ) then writeln('Line 5 - b is either greater than or equal to ' ); end. When the above code is compiled and executed, it produces the following result: Line 1 - a is not equal to b Line 2 - a is not less than b Line 3 - a is greater than b Line 4 - a is either less than or equal to b Line 5 - b is either greater than or equal to b 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2214, "s": 2083, "text": "Following table shows all the relational operators supported by Pascal. Assume variable A holds 10 and variable B holds 20, then −" }, { "code": null, "e": 2326, "s": 2214, "text": "Try the following example to understand all the relational operators available in Pascal programming language −" }, { "code": null, "e": 3016, "s": 2326, "text": "program showRelations;\nvar\na, b: integer;\n\nbegin\n a := 21;\n b := 10;\n \n if a = b then\n writeln('Line 1 - a is equal to b' )\n else\n writeln('Line 1 - a is not equal to b' );\n \n if a < b then\n writeln('Line 2 - a is less than b' )\n else\n writeln('Line 2 - a is not less than b' );\n \n if a > b then\n writeln('Line 3 - a is greater than b' )\n else\n writeln('Line 3 - a is greater than b' );\n \n (* Lets change value of a and b *)\n a := 5;\n b := 20;\n \n if a <= b then\n writeln('Line 4 - a is either less than or equal to b' );\n \n if ( b >= a ) then\n writeln('Line 5 - b is either greater than or equal to ' );\nend." }, { "code": null, "e": 3096, "s": 3016, "text": "When the above code is compiled and executed, it produces the following result:" }, { "code": null, "e": 3278, "s": 3096, "text": "Line 1 - a is not equal to b\nLine 2 - a is not less than b\nLine 3 - a is greater than b\nLine 4 - a is either less than or equal to b\nLine 5 - b is either greater than or equal to b\n" }, { "code": null, "e": 3313, "s": 3278, "text": "\n 94 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3336, "s": 3313, "text": " Stone River ELearning" }, { "code": null, "e": 3343, "s": 3336, "text": " Print" }, { "code": null, "e": 3354, "s": 3343, "text": " Add Notes" } ]
Code Coverage Tutorial (Branch, Statement, Decision, FSM)
The ultimate goal of any software development company is to provide high-quality software. The software must be properly tested in order to reach this goal. As a result, testing is an important aspect of the software development process. As a result, it's critical that the software generated be evaluated by the developer (during the unit testing phase) and then delivered to the QC team to be extensively tested to guarantee that it has few or no flaws. Before being delivered to the actual test team for testing, the software is unit tested. This testing is done by the developer because it involves testing at the code level. This is done to guarantee that each component of the code being tested functions properly. Code coverage is a metric that describes how thoroughly the program's source code has been tested. It's a type of white box testing that looks for sections of the software that aren't being tested by a set of test cases. It also constructs some test cases in order to boost coverage and determine a quantitative code coverage measure. In most circumstances, the code coverage system collects data about the currently running program. It also combines this information with source code information to provide a report on the code coverage of the test suite. Code Coverage is important for a variety of reasons, some of which are stated below − When compared to software that does not have a good Code Coverage, it helps to ensure that the software has fewer errors. When compared to software that does not have a good Code Coverage, it helps to ensure that the software has fewer errors. It indirectly aids in the delivery of better ‘quality software by assisting in the improvement of code quality. It indirectly aids in the delivery of better ‘quality software by assisting in the improvement of code quality. It is a metric that can be used to determine the effectiveness of a test (effectiveness of the unit tests that are written to test the code). It is a metric that can be used to determine the effectiveness of a test (effectiveness of the unit tests that are written to test the code). It assists in identifying areas of the source code that might otherwise go unexplored. It assists in identifying areas of the source code that might otherwise go unexplored. It aids in determining whether present testing (unit testing) is adequate and whether additional tests are required. It aids in determining whether present testing (unit testing) is adequate and whether additional tests are required. Here are some of the most compelling reasons to use code coverage − It assists you in determining the effectiveness of test implementation. It assists you in determining the effectiveness of test implementation. It provides a quantitative evaluation. It provides a quantitative evaluation. It indicates how thoroughly the source code has been tested. It indicates how thoroughly the source code has been tested. Take two values, such as a=0 and b=1. Take two values, such as a=0 and b=1. Calculate the total of these two numbers. Calculate the total of these two numbers. "This is the positive result," print if the sum is greater than 0. "This is the positive result," print if the sum is greater than 0. "This is the negative result," print if the sum is less than 0. "This is the negative result," print if the sum is less than 0. In this section, we'll go over the many ways for measuring Code Coverage that are/can be utilized. To get to know these methodologies, let’s take a look at the below code snippet − Add (int a, int b) { if (b > a) { b = b - a print b } if (a > b) { b = a – b print b } else print '0' } This methodology is a metric that determines if all possible executable statements in source code have been run at least once. It's a technique for ensuring that each line of source code is tested at least once. While this may appear to be a straightforward task, it is important to proceed with caution while determining Statement Coverage. The reason for this is that based on the input values, a condition in a source code may or may not be executed. This would imply that testing would not cover all lines of code. As a result, various input value sets may be required to cover all such circumstances in the source code. In the preceding source code, for example, if the input values are 2 and 3, the ‘Else' section of the code will not be run. The ‘If' part of the code, on the other hand, will not be run if the input values are of types 3 and 2. This means that our Statement Coverage would not be 100% with either set of data. In this scenario, we may need to run the tests with all three sets of data [(2, 3), (3, 2), (0, 0)] to ensure 100 percent Statement Coverage. This methodology measures the extent to which the functions included in the source code are covered during testing, as the name implies. During the test run, all functions in the source code are tested. Again, we must ensure that we test these functions for varied values in order to guarantee that the function is adequately tested. There may be several functions in a source code file, and depending on the input values provided, a function may or may not be called. As a result, the goal of Function Coverage is to ensure that we have all of the functions required. If our tests call the ‘Add' function even once in the source code above, we would refer to it as a full Function coverage. Wherever we have a condition in the source code, the result is a Boolean value of true or false. The goal of condition coverage is to see if the tests cover both true and false values. When each occurring condition in the source code is assessed for both true and false states, the code's Condition Coverage is said to be complete. For example, if value sets (2, 3) and (4, 2) are utilized in the following code, Condition Coverage will be 100%. When data sets (2, 3) are used, (b > a) becomes true and (a > b) becomes false. When using data set (4, 2), (b > a) evaluates to false, but (a > b) evaluates to true. As a result, both conditions have both true and false values covered. As a result, the Condition Coverage would be 100%. This methodology seeks to make sure that each conditional structure's branch is performed in source code. For example, in the preceding code, the test should cover all of the ‘If' statements as well as any accompanying ‘Else' statements for 100% Branch Coverage. For example, if value sets (2, 3), (4, 2), (1, 1) are utilized in the given code, Branch Coverage will be 100%. When data sets (2, 3) are used, the first ‘If' branch is run and (b > a). When data set (4, 2) is used, (a > b) evaluates to true, which causes the second ‘If' branch to be executed. The ‘Else' branch then evaluates to true with the data set (1, 1) and is executed. As a result, 100% Branch Coverage is ensured. The following are some of the benefits of branch coverage testing − Allows you to validate all of the code's branches, ensuring that none of them lead to any abnormalities in the program's execution. Allows you to validate all of the code's branches, ensuring that none of them lead to any abnormalities in the program's execution. The branch coverage method eliminates difficulties that arise as a result of statement coverage testing. The branch coverage method eliminates difficulties that arise as a result of statement coverage testing. Allows you to find places that aren't covered by other techniques of testing. Allows you to find places that aren't covered by other techniques of testing. It enables you to calculate a numerical measure of code coverage. It enables you to calculate a numerical measure of code coverage. Branch coverage does not take into account branches within Boolean expressions. Branch coverage does not take into account branches within Boolean expressions. The most difficult sort of code coverage method is finite state machine coverage. This is because it affects the design's behavior. This coverage approach requires you to count the number of time-specific states that are visited and transited. It also determines how many sequences a finite state machine contains. This is without a doubt the hardest response to offer. In order to choose a coverage approach, the tester must first ensure that the requirements are met. There are one or more undetected faults in the code under test. There are one or more undetected faults in the code under test. The cost of a potential penalty, The cost of a potential penalty, the cost of a damaged reputation, the cost of a damaged reputation, the cost of a missed sale, and so on. the cost of a missed sale, and so on. The more likely faults will result in costly production failures, the more severe the amount of coverage you should choose. The more likely faults will result in costly production failures, the more severe the amount of coverage you should choose. As previously stated, it is an extremely valuable test metric for the following reasons − It aids in identifying portions of a source code that might otherwise go untested or discovered by the tests. It aids in identifying portions of a source code that might otherwise go untested or discovered by the tests. It is useful for identifying used/dead code and thereby increasing code quality. It is useful for identifying used/dead code and thereby increasing code quality. Code Coverage can be used to determine the effectiveness of unit tests. Code Coverage can be used to determine the effectiveness of unit tests. These measurements can be used to deliver higher-quality software. These measurements can be used to deliver higher-quality software. Code coverage still reports 100 percent coverage even if a certain feature is not implemented in the design. Code coverage still reports 100 percent coverage even if a certain feature is not implemented in the design. Code coverage does not allow us to tell whether we tested all possible values for a feature. Code coverage does not allow us to tell whether we tested all possible values for a feature. Additionally, code coverage does not indicate how much or how well you have covered your logic. Additionally, code coverage does not indicate how much or how well you have covered your logic. When a stated function isn't implemented or isn't included in the specification, structure-based approaches are unable to detect the problem. When a stated function isn't implemented or isn't included in the specification, structure-based approaches are unable to detect the problem. Here, is a list that contains Important code coverage Tools − Code coverage is a metric that reflects how thoroughly the program's source code has been tested. Code coverage is a metric that reflects how thoroughly the program's source code has been tested. It assists you in determining the effectiveness of test implementation. It assists you in determining the effectiveness of test implementation. There are five different ways to measure code coverage. 1.) Coverage of Statement 2.) Condition Protection 3) Coverage of all branches 4) Coverage toggle 5) Coverage by the FSM There are five different ways to measure code coverage. 1.) Coverage of Statement 2.) Condition Protection 3) Coverage of all branches 4) Coverage toggle 5) Coverage by the FSM Statement coverage entails running all of the source code's executable statements at least once. Decision coverage gives the true or false results of each Boolean expression. Statement coverage entails running all of the source code's executable statements at least once. Decision coverage gives the true or false results of each Boolean expression. Every result from a code module is tested in the branch coverage. Every result from a code module is tested in the branch coverage. The variables or subexpressions in the conditional statement will be evaluated in this way. The variables or subexpressions in the conditional statement will be evaluated in this way. The most difficult sort of code coverage method is finite state machine coverage. The most difficult sort of code coverage method is finite state machine coverage. To choose a coverage approach, the tester must consider the cost of a potential penalty, lost reputation, lost sale, and other factors. To choose a coverage approach, the tester must consider the cost of a potential penalty, lost reputation, lost sale, and other factors. Code coverage indicates how thoroughly your test bench has exercised the source code. The term "functional coverage" refers to how well the design's functionality has been covered. Code coverage indicates how thoroughly your test bench has exercised the source code. The term "functional coverage" refers to how well the design's functionality has been covered. Among the most popular code coverage tools are Cobertura, JTest, Clover, Emma, and Kalistick. Among the most popular code coverage tools are Cobertura, JTest, Clover, Emma, and Kalistick. You can use Code Coverage to add more test cases to your coverage. You can use Code Coverage to add more test cases to your coverage. Code coverage does not tell you whether we tested all of a feature's conceivable values. Code coverage does not tell you whether we tested all of a feature's conceivable values.
[ { "code": null, "e": 1219, "s": 1062, "text": "The ultimate goal of any software development company is to provide high-quality software. The software must be properly tested in order to reach this goal." }, { "code": null, "e": 1518, "s": 1219, "text": "As a result, testing is an important aspect of the software development process. As a result, it's critical that the software generated be evaluated by the developer (during the unit testing phase) and then delivered to the QC team to be extensively tested to guarantee that it has few or no flaws." }, { "code": null, "e": 1783, "s": 1518, "text": "Before being delivered to the actual test team for testing, the software is unit tested. This testing is done by the developer because it involves testing at the code level. This is done to guarantee that each component of the code being tested functions properly." }, { "code": null, "e": 2118, "s": 1783, "text": "Code coverage is a metric that describes how thoroughly the program's source code has been tested. It's a type of white box testing that looks for sections of the software that aren't being tested by a set of test cases. It also constructs some test cases in order to boost coverage and determine a quantitative code coverage measure." }, { "code": null, "e": 2340, "s": 2118, "text": "In most circumstances, the code coverage system collects data about the currently running program. It also combines this information with source code information to provide a report on the code coverage of the test suite." }, { "code": null, "e": 2426, "s": 2340, "text": "Code Coverage is important for a variety of reasons, some of which are stated below −" }, { "code": null, "e": 2548, "s": 2426, "text": "When compared to software that does not have a good Code Coverage, it helps to ensure that the software has fewer errors." }, { "code": null, "e": 2670, "s": 2548, "text": "When compared to software that does not have a good Code Coverage, it helps to ensure that the software has fewer errors." }, { "code": null, "e": 2782, "s": 2670, "text": "It indirectly aids in the delivery of better ‘quality software by assisting in the improvement of code quality." }, { "code": null, "e": 2894, "s": 2782, "text": "It indirectly aids in the delivery of better ‘quality software by assisting in the improvement of code quality." }, { "code": null, "e": 3036, "s": 2894, "text": "It is a metric that can be used to determine the effectiveness of a test (effectiveness of the unit tests that are written to test the code)." }, { "code": null, "e": 3178, "s": 3036, "text": "It is a metric that can be used to determine the effectiveness of a test (effectiveness of the unit tests that are written to test the code)." }, { "code": null, "e": 3265, "s": 3178, "text": "It assists in identifying areas of the source code that might otherwise go unexplored." }, { "code": null, "e": 3352, "s": 3265, "text": "It assists in identifying areas of the source code that might otherwise go unexplored." }, { "code": null, "e": 3469, "s": 3352, "text": "It aids in determining whether present testing (unit testing) is adequate and whether additional tests are required." }, { "code": null, "e": 3586, "s": 3469, "text": "It aids in determining whether present testing (unit testing) is adequate and whether additional tests are required." }, { "code": null, "e": 3654, "s": 3586, "text": "Here are some of the most compelling reasons to use code coverage −" }, { "code": null, "e": 3726, "s": 3654, "text": "It assists you in determining the effectiveness of test implementation." }, { "code": null, "e": 3798, "s": 3726, "text": "It assists you in determining the effectiveness of test implementation." }, { "code": null, "e": 3837, "s": 3798, "text": "It provides a quantitative evaluation." }, { "code": null, "e": 3876, "s": 3837, "text": "It provides a quantitative evaluation." }, { "code": null, "e": 3937, "s": 3876, "text": "It indicates how thoroughly the source code has been tested." }, { "code": null, "e": 3998, "s": 3937, "text": "It indicates how thoroughly the source code has been tested." }, { "code": null, "e": 4036, "s": 3998, "text": "Take two values, such as a=0 and b=1." }, { "code": null, "e": 4074, "s": 4036, "text": "Take two values, such as a=0 and b=1." }, { "code": null, "e": 4116, "s": 4074, "text": "Calculate the total of these two numbers." }, { "code": null, "e": 4158, "s": 4116, "text": "Calculate the total of these two numbers." }, { "code": null, "e": 4225, "s": 4158, "text": "\"This is the positive result,\" print if the sum is greater than 0." }, { "code": null, "e": 4292, "s": 4225, "text": "\"This is the positive result,\" print if the sum is greater than 0." }, { "code": null, "e": 4356, "s": 4292, "text": "\"This is the negative result,\" print if the sum is less than 0." }, { "code": null, "e": 4420, "s": 4356, "text": "\"This is the negative result,\" print if the sum is less than 0." }, { "code": null, "e": 4519, "s": 4420, "text": "In this section, we'll go over the many ways for measuring Code Coverage that are/can be utilized." }, { "code": null, "e": 4601, "s": 4519, "text": "To get to know these methodologies, let’s take a look at the below code snippet −" }, { "code": null, "e": 4744, "s": 4601, "text": "Add (int a, int b) {\n if (b > a) {\n b = b - a\n print b\n }\n if (a > b) {\n b = a – b\n print b\n }\n else print '0'\n}" }, { "code": null, "e": 4956, "s": 4744, "text": "This methodology is a metric that determines if all possible executable statements in source code have been run at least once. It's a technique for ensuring that each line of source code is tested at least once." }, { "code": null, "e": 5369, "s": 4956, "text": "While this may appear to be a straightforward task, it is important to proceed with caution while determining Statement Coverage. The reason for this is that based on the input values, a condition in a source code may or may not be executed. This would imply that testing would not cover all lines of code. As a result, various input value sets may be required to cover all such circumstances in the source code." }, { "code": null, "e": 5821, "s": 5369, "text": "In the preceding source code, for example, if the input values are 2 and 3, the ‘Else' section of the code will not be run. The ‘If' part of the code, on the other hand, will not be run if the input values are of types 3 and 2. This means that our Statement Coverage would not be 100% with either set of data. In this scenario, we may need to run the tests with all three sets of data [(2, 3), (3, 2), (0, 0)] to ensure 100 percent Statement Coverage." }, { "code": null, "e": 6155, "s": 5821, "text": "This methodology measures the extent to which the functions included in the source code are covered during testing, as the name implies. During the test run, all functions in the source code are tested. Again, we must ensure that we test these functions for varied values in order to guarantee that the function is adequately tested." }, { "code": null, "e": 6390, "s": 6155, "text": "There may be several functions in a source code file, and depending on the input values provided, a function may or may not be called. As a result, the goal of Function Coverage is to ensure that we have all of the functions required." }, { "code": null, "e": 6513, "s": 6390, "text": "If our tests call the ‘Add' function even once in the source code above, we would refer to it as a full Function coverage." }, { "code": null, "e": 6845, "s": 6513, "text": "Wherever we have a condition in the source code, the result is a Boolean value of true or false. The goal of condition coverage is to see if the tests cover both true and false values. When each occurring condition in the source code is assessed for both true and false states, the code's Condition Coverage is said to be complete." }, { "code": null, "e": 7247, "s": 6845, "text": "For example, if value sets (2, 3) and (4, 2) are utilized in the following code, Condition Coverage will be 100%. When data sets (2, 3) are used, (b > a) becomes true and (a > b) becomes false. When using data set (4, 2), (b > a) evaluates to false, but (a > b) evaluates to true. As a result, both conditions have both true and false values covered. As a result, the Condition Coverage would be 100%." }, { "code": null, "e": 7510, "s": 7247, "text": "This methodology seeks to make sure that each conditional structure's branch is performed in source code. For example, in the preceding code, the test should cover all of the ‘If' statements as well as any accompanying ‘Else' statements for 100% Branch Coverage." }, { "code": null, "e": 7805, "s": 7510, "text": "For example, if value sets (2, 3), (4, 2), (1, 1) are utilized in the given code, Branch Coverage will be 100%. When data sets (2, 3) are used, the first ‘If' branch is run and (b > a). When data set (4, 2) is used, (a > b) evaluates to true, which causes the second ‘If' branch to be executed." }, { "code": null, "e": 7934, "s": 7805, "text": "The ‘Else' branch then evaluates to true with the data set (1, 1) and is executed. As a result, 100% Branch Coverage is ensured." }, { "code": null, "e": 8002, "s": 7934, "text": "The following are some of the benefits of branch coverage testing −" }, { "code": null, "e": 8134, "s": 8002, "text": "Allows you to validate all of the code's branches, ensuring that none of them lead to any abnormalities in the program's execution." }, { "code": null, "e": 8266, "s": 8134, "text": "Allows you to validate all of the code's branches, ensuring that none of them lead to any abnormalities in the program's execution." }, { "code": null, "e": 8371, "s": 8266, "text": "The branch coverage method eliminates difficulties that arise as a result of statement coverage testing." }, { "code": null, "e": 8476, "s": 8371, "text": "The branch coverage method eliminates difficulties that arise as a result of statement coverage testing." }, { "code": null, "e": 8554, "s": 8476, "text": "Allows you to find places that aren't covered by other techniques of testing." }, { "code": null, "e": 8632, "s": 8554, "text": "Allows you to find places that aren't covered by other techniques of testing." }, { "code": null, "e": 8698, "s": 8632, "text": "It enables you to calculate a numerical measure of code coverage." }, { "code": null, "e": 8764, "s": 8698, "text": "It enables you to calculate a numerical measure of code coverage." }, { "code": null, "e": 8844, "s": 8764, "text": "Branch coverage does not take into account branches within Boolean expressions." }, { "code": null, "e": 8924, "s": 8844, "text": "Branch coverage does not take into account branches within Boolean expressions." }, { "code": null, "e": 9239, "s": 8924, "text": "The most difficult sort of code coverage method is finite state machine coverage. This is because it affects the design's behavior. This coverage approach requires you to count the number of time-specific states that are visited and transited. It also determines how many sequences a finite state machine contains." }, { "code": null, "e": 9394, "s": 9239, "text": "This is without a doubt the hardest response to offer. In order to choose a coverage approach, the tester must first ensure that the requirements are met." }, { "code": null, "e": 9458, "s": 9394, "text": "There are one or more undetected faults in the code under test." }, { "code": null, "e": 9522, "s": 9458, "text": "There are one or more undetected faults in the code under test." }, { "code": null, "e": 9555, "s": 9522, "text": "The cost of a potential penalty," }, { "code": null, "e": 9588, "s": 9555, "text": "The cost of a potential penalty," }, { "code": null, "e": 9622, "s": 9588, "text": "the cost of a damaged reputation," }, { "code": null, "e": 9656, "s": 9622, "text": "the cost of a damaged reputation," }, { "code": null, "e": 9694, "s": 9656, "text": "the cost of a missed sale, and so on." }, { "code": null, "e": 9732, "s": 9694, "text": "the cost of a missed sale, and so on." }, { "code": null, "e": 9856, "s": 9732, "text": "The more likely faults will result in costly production failures, the more severe the amount of coverage you should choose." }, { "code": null, "e": 9980, "s": 9856, "text": "The more likely faults will result in costly production failures, the more severe the amount of coverage you should choose." }, { "code": null, "e": 10070, "s": 9980, "text": "As previously stated, it is an extremely valuable test metric for the following reasons −" }, { "code": null, "e": 10180, "s": 10070, "text": "It aids in identifying portions of a source code that might otherwise go untested or discovered by the tests." }, { "code": null, "e": 10290, "s": 10180, "text": "It aids in identifying portions of a source code that might otherwise go untested or discovered by the tests." }, { "code": null, "e": 10371, "s": 10290, "text": "It is useful for identifying used/dead code and thereby increasing code quality." }, { "code": null, "e": 10452, "s": 10371, "text": "It is useful for identifying used/dead code and thereby increasing code quality." }, { "code": null, "e": 10524, "s": 10452, "text": "Code Coverage can be used to determine the effectiveness of unit tests." }, { "code": null, "e": 10596, "s": 10524, "text": "Code Coverage can be used to determine the effectiveness of unit tests." }, { "code": null, "e": 10663, "s": 10596, "text": "These measurements can be used to deliver higher-quality software." }, { "code": null, "e": 10730, "s": 10663, "text": "These measurements can be used to deliver higher-quality software." }, { "code": null, "e": 10839, "s": 10730, "text": "Code coverage still reports 100 percent coverage even if a certain feature is not implemented in the design." }, { "code": null, "e": 10948, "s": 10839, "text": "Code coverage still reports 100 percent coverage even if a certain feature is not implemented in the design." }, { "code": null, "e": 11041, "s": 10948, "text": "Code coverage does not allow us to tell whether we tested all possible values for a feature." }, { "code": null, "e": 11134, "s": 11041, "text": "Code coverage does not allow us to tell whether we tested all possible values for a feature." }, { "code": null, "e": 11230, "s": 11134, "text": "Additionally, code coverage does not indicate how much or how well you have covered your logic." }, { "code": null, "e": 11326, "s": 11230, "text": "Additionally, code coverage does not indicate how much or how well you have covered your logic." }, { "code": null, "e": 11468, "s": 11326, "text": "When a stated function isn't implemented or isn't included in the specification, structure-based approaches are unable to detect the problem." }, { "code": null, "e": 11610, "s": 11468, "text": "When a stated function isn't implemented or isn't included in the specification, structure-based approaches are unable to detect the problem." }, { "code": null, "e": 11672, "s": 11610, "text": "Here, is a list that contains Important code coverage Tools −" }, { "code": null, "e": 11770, "s": 11672, "text": "Code coverage is a metric that reflects how thoroughly the program's source code has been tested." }, { "code": null, "e": 11868, "s": 11770, "text": "Code coverage is a metric that reflects how thoroughly the program's source code has been tested." }, { "code": null, "e": 11940, "s": 11868, "text": "It assists you in determining the effectiveness of test implementation." }, { "code": null, "e": 12012, "s": 11940, "text": "It assists you in determining the effectiveness of test implementation." }, { "code": null, "e": 12189, "s": 12012, "text": "There are five different ways to measure code coverage. 1.) Coverage of Statement 2.) Condition Protection 3) Coverage of all branches 4) Coverage toggle 5) Coverage by the FSM" }, { "code": null, "e": 12366, "s": 12189, "text": "There are five different ways to measure code coverage. 1.) Coverage of Statement 2.) Condition Protection 3) Coverage of all branches 4) Coverage toggle 5) Coverage by the FSM" }, { "code": null, "e": 12541, "s": 12366, "text": "Statement coverage entails running all of the source code's executable statements at least once. Decision coverage gives the true or false results of each Boolean expression." }, { "code": null, "e": 12716, "s": 12541, "text": "Statement coverage entails running all of the source code's executable statements at least once. Decision coverage gives the true or false results of each Boolean expression." }, { "code": null, "e": 12782, "s": 12716, "text": "Every result from a code module is tested in the branch coverage." }, { "code": null, "e": 12848, "s": 12782, "text": "Every result from a code module is tested in the branch coverage." }, { "code": null, "e": 12940, "s": 12848, "text": "The variables or subexpressions in the conditional statement will be evaluated in this way." }, { "code": null, "e": 13032, "s": 12940, "text": "The variables or subexpressions in the conditional statement will be evaluated in this way." }, { "code": null, "e": 13114, "s": 13032, "text": "The most difficult sort of code coverage method is finite state machine coverage." }, { "code": null, "e": 13196, "s": 13114, "text": "The most difficult sort of code coverage method is finite state machine coverage." }, { "code": null, "e": 13332, "s": 13196, "text": "To choose a coverage approach, the tester must consider the cost of a potential penalty, lost reputation, lost sale, and other factors." }, { "code": null, "e": 13468, "s": 13332, "text": "To choose a coverage approach, the tester must consider the cost of a potential penalty, lost reputation, lost sale, and other factors." }, { "code": null, "e": 13649, "s": 13468, "text": "Code coverage indicates how thoroughly your test bench has exercised the source code. The term \"functional coverage\" refers to how well the design's functionality has been covered." }, { "code": null, "e": 13830, "s": 13649, "text": "Code coverage indicates how thoroughly your test bench has exercised the source code. The term \"functional coverage\" refers to how well the design's functionality has been covered." }, { "code": null, "e": 13924, "s": 13830, "text": "Among the most popular code coverage tools are Cobertura, JTest, Clover, Emma, and Kalistick." }, { "code": null, "e": 14018, "s": 13924, "text": "Among the most popular code coverage tools are Cobertura, JTest, Clover, Emma, and Kalistick." }, { "code": null, "e": 14085, "s": 14018, "text": "You can use Code Coverage to add more test cases to your coverage." }, { "code": null, "e": 14152, "s": 14085, "text": "You can use Code Coverage to add more test cases to your coverage." }, { "code": null, "e": 14241, "s": 14152, "text": "Code coverage does not tell you whether we tested all of a feature's conceivable values." }, { "code": null, "e": 14330, "s": 14241, "text": "Code coverage does not tell you whether we tested all of a feature's conceivable values." } ]
Jython - Quick Guide
Jython is the JVM implementation of the Python programming language. It is designed to run on the Java platform. A Jython program can import and use any Java class. Just as Java, Jython program compiles to bytecode. One of the main advantages is that a user interface designed in Python can use GUI elements of AWT, Swing or SWT Package. Jython, which started as JPython and was later renamed, follows closely the standard Python implementation called CPython as created by Guido Van Rossum. Jython was created in 1997 by Jim Hugunin. Jython 2.0 was released in 1999. Since then, Jython 2.x releases correspond to equivalent CPython releases. Jython 2.7.0 released in May 2015, corresponds to CPython 2.7. Development of Jython 3.x is under progress. Following are the differences between Python and Java − Python is a dynamically typed language. Hence, the type declaration of variable is not needed. Java on the other hand is a statically typed language, which means that the type declaration of variable is mandatory and cannot be changed. Python is a dynamically typed language. Hence, the type declaration of variable is not needed. Java on the other hand is a statically typed language, which means that the type declaration of variable is mandatory and cannot be changed. Python has only unchecked exceptions, whereas Java has both checked and unchecked exceptions. Python has only unchecked exceptions, whereas Java has both checked and unchecked exceptions. Python uses indents for scoping, while Java uses matching curly brackets. Python uses indents for scoping, while Java uses matching curly brackets. Since Python is an interpreter-based language, it has no separate compilation steps. A Java program however needs to be compiled to bytecode and is in turn executed by a JVM. Since Python is an interpreter-based language, it has no separate compilation steps. A Java program however needs to be compiled to bytecode and is in turn executed by a JVM. Python supports multiple inheritance, but in Java, multiple inheritance is not possible. It however has implementation of an interface. Python supports multiple inheritance, but in Java, multiple inheritance is not possible. It however has implementation of an interface. Compared to Java, Python has a richer built-in data structures (lists, dicts, tuples, everything is an object). Compared to Java, Python has a richer built-in data structures (lists, dicts, tuples, everything is an object). Following are the differences between Python and Jython − Reference implementation of Python, called CPython, is written in C language. Jython on the other hand is completely written in Java and is a JVM implementation. Reference implementation of Python, called CPython, is written in C language. Jython on the other hand is completely written in Java and is a JVM implementation. Standard Python is available on multiple platforms. Jython is available for any platform with a JVM installed on it. Standard Python is available on multiple platforms. Jython is available for any platform with a JVM installed on it. Standard Python code compiles to a .pyc file, while Jython program compiles to a .class file. Standard Python code compiles to a .pyc file, while Jython program compiles to a .class file. Python extensions can be written in C language. Extensions for Jython are written in Java. Python extensions can be written in C language. Extensions for Jython are written in Java. Jython is truly multi-threaded in nature. Python however uses the Global Interpreter Lock (GIL) mechanism for the purpose. Jython is truly multi-threaded in nature. Python however uses the Global Interpreter Lock (GIL) mechanism for the purpose. Both implementations have different garbage collection mechanisms. Both implementations have different garbage collection mechanisms. In the next chapter, we will learn how to import the Java libraries in Jython. Before installation of Jython 2.7, ensure that the system has JDK 7 or more installed. Jython is available in the form of an executable jar file. Download it from - http://www.jython.org/downloads.html and either double click on its icon or run the following command − java -jar jython_installer-2.7.0.jar An installation wizard will commence with which installation options have to be given. Here is the systematic installation procedure. The first step in the wizard asks you to select the language. The second step prompts you to accept the licence agreement. In the next step, choose the installation type. It is recommended to choose the Standard installation. The next screen asks your confirmation about your options and proceeds to complete the installation. The installation procedure might take some time to complete. After the installation is complete, invoke jython.exe from the bin directory inside the destination directory. Assuming that Jython is installed in C:\jython27, execute the following from the command line. C:\jython27\bin\jython A Python prompt (>>>) will appear, in front of which any Python statement or Python script can be executed. One of the most important features of Jython is its ability to import Java classes in a Python program. We can import any java package or class in Jython, just as we do in a Java program. The following example shows how the java.util packages are imported in Python (Jython) script to declare an object of the Date class. from java.util import Date d = Date() print d Save and run the above code as UtilDate.py from the command line. Instance of the current date and time will be displayed. C:\jython27\bin>jython UtilDate.py Sun Jul 09 00:05:43 IST 2017 The following packages from the Java library are more often imported in a Jython program mainly because standard Python library either does not have their equivalents or are not as good. Servlets JMS J2EE Javadoc Swing is considered superior to other GUI toolkits Any Java package for that matter can be imported in a Jython script. Here, the following java program is stored and compiled in a package called foo. package foo; public class HelloWorld { public void hello() { System.out.println("Hello World!"); } public void hello(String name) { System.out.printf("Hello %s!", name); } } This HelloWorld.class is imported in the following Jython Script. Methods in this class can be called from the Jython script importex.py. from foo import HelloWorld h = HelloWorld() h.hello() h.hello("TutorialsPoint") Save and execute the above script from the command line to get following output. C:\jython27\bin>jython importex.py Hello World! Hello TutorialsPoint! Variables are named locations in computer’s memory. Each variable can hold one piece of data in it. Unlike Java, Python is a dynamically typed language. Hence while using Jython also; prior declaration of data type of variable is not done. Rather than the type of variable deciding which data can be stored in it, the data decides the type of variable. In the following example, a variable is assigned an integer value. Using the type() built-in function, we can verify that the type of variable is an integer. But, if the same variable is assigned a string, the type() function will string as the type of same variable. > x = 10 >>> type(x) <class 'int'> >>> x = "hello" >>> type(x) <class 'str'> This explains why Python is called a dynamically typed language. The following Python built-in data types can also be used in Jython − Number String List Tuple Dictionary Python recognizes numeric data as a number, which may be an integer, a real number with floating point or a complex number. String, List and Tuple data types are called sequences. In Python, any signed integer is said to be of type ‘int’. To express a long integer, letter ‘L’ is attached to it. A number with a decimal point separating the integer part from a fractional component is called ‘float’. The fractional part may contain an exponent expressed in the scientific notation using ‘E’ or ‘e’. A Complex number is also defined as numeric data type in Python. A complex number contains a real part (a floating-point number) and an imaginary part having ‘j’ attached to it. In order to express a number in the Octal or the Hexadecimal representation, 0O or 0X is prefixed to it. The following code block gives examples of different representations of numbers in Python. int -> 10, 100, -786, 80 long -> 51924361L, -0112L, 47329487234L float -> 15.2, -21.9, 32.3+e18, -3.25E+101 complex -> 3.14j, 45.j, 3e+26J, 9.322e-36j A string is any sequence of characters enclosed in single (e.g. ‘hello’), double (e.g. “hello”) or triple (e.g. ‘“hello’” o “““hello”””) quotation marks. Triple quotes are especially useful if content of the string spans over multiple lines. The Escape sequence characters can be included verbatim in triple quoted string. The following examples show different ways to declare a string in Python. str = ’hello how are you?’ str = ”Hello how are you?” str = """this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up. """ The third string when printed, will give the following output. this is a long string that is made up of several lines and non-printable characters such as TAB ( ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ ], or just a NEWLINE within the variable assignment will also show up. A List is a sequence data type. It is a collection of comma-separated items, not necessarily of the same type, stored in square brackets. Individual item from the List can be accessed using the zero based index. The following code block summarizes the usage of a List in Python. list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5, 6, 7 ]; print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5] The following table describes some of the most common Jython Expressions related to Jython Lists. A tuple is an immutable collection of comma-separated data items stored in parentheses. It is not possible to delete or modify an element in tuple, nor is it possible to add an element to the tuple collection. The following code block shows Tuple operations. tup1 = ('physics','chemistry‘,1997,2000); tup2 = (1, 2, 3, 4, 5, 6, 7 ); print "tup1[0]: ", tup1[0] print "tup2[1:5]: ", tup2[1:5] The Jython Dictionary is similar to Map class in Java Collection framework. It is a collection of key-value pairs. Pairs separated by comma are enclosed in curly brackets. A Dictionary object does not follow zero based index to retrieve element inside it as they are stored by hashing technique. The same key cannot appear more than once in a dictionary object. However, more than one key can have same associated values. Different functions available with Dictionary object are explained below − dict = {'011':'New Delhi','022':'Mumbai','033':'Kolkata'} print "dict[‘011’]: ",dict['011'] print "dict['Age']: ", dict['Age'] The following table describes some of the most common Jython Expressions related to Dictionary. In addition to Python’s built-in data types, Jython has the benefit of using Java collection classes by importing the java.util package. The following code describes the classes given below − Java ArrayList object with add() remove() get() and set() methods of the ArrayList class. import java.util.ArrayList as ArrayList arr = ArrayList() arr.add(10) arr.add(20) print "ArrayList:",arr arr.remove(10) #remove 10 from arraylist arr.add(0,5) #add 5 at 0th index print "ArrayList:",arr print "element at index 1:",arr.get(1) #retrieve item at index 1 arr.set(0,100) #set item at 0th index to 100 print "ArrayList:",arr The above Jython script produces the following output − C:\jython27\bin>jython arrlist.py ArrayList: [10, 20] ArrayList: [5, 20] element at index 1: 20 ArrayList: [100, 20] Jython also implements the Jarray Object, which allows construction of a Java array in Python. In order to work with a jarray, simply define a sequence type in Jython and pass it to the jarrayobject along with the type of object contained within the sequence. All values within a jarray must be of the same type. The following table shows the character typecodes used with a jarray. The following example shows construction of jarray. my_seq = (1,2,3,4,5) from jarray import array arr1 = array(my_seq,'i') print arr1 myStr = "Hello Jython" arr2 = array(myStr,'c') print arr2 Here my_seq is defined as a tuple of integers. It is converted to Jarray arr1. The second example shows that Jarray arr2 is constructed from mySttr string sequence. The output of the above script jarray.py is as follows − array('i', [1, 2, 3, 4, 5]) array('c', 'Hello Jython') Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed, if the condition is determined to be true, and optionally, other statements to be executed, if the condition is determined to be false. The following illustration shows the general form of a typical decision making structure found in most of the programming languages − Jython does not use curly brackets to indicate blocks of statements to be executed when the condition is true or false (as is the case in Java). Instead, uniform indent (white space from left margin) is used to form block of statements. Such a uniformly indented block makes the conditional code to be executed when a condition given in ‘if’ statement is true. A similar block may be present after an optional ‘else’ statement. Jython also provides the elif statement using which successive conditions can be tested. Here, the else clause will appear last and will be executed only when all the preceding conditions fail. The general syntax of using if..elif..else is as follows. if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s) In the following example, if ..elif ..else construct is used to calculate discount on different values of amount input by user. discount = 0 amount = input("enter Amount") if amount>1000: discount = amount*0.10 elif amount>500: discount = amount*0.05 else: discount = 0 print 'Discount = ',discount print 'Net amount = ',amount-discount The output of above code will be as shown below. enter Amount1500 Discount = 150.0 Net amount = 1350.0 enter Amount600 Discount = 30.0 Net amount = 570.0 enter Amount200 Discount = 0 Net amount = 200 In general, statements in a program are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Statements that provide such repetition capability are called looping statements. In Jython, a loop can be formed by two statements, which are − The while statement and The while statement and The for statement The for statement A while loop statement in Jython is similar to that in Java. It repeatedly executes a block of statements as long as a given condition is true. The following flowchart describes the behavior of a while loop. The general syntax of the while statement is given below. while expression: statement(s) The following Jython code uses the while loop to repeatedly increment and print value of a variable until it is less than zero. count = 0 while count<10: count = count+1 print "count = ",count print "Good Bye!" Output − The output would be as follows. count = 1 count = 2 count = 3 count = 4 count = 5 count = 6 count = 7 count = 8 count = 9 count = 10 Good Bye! The FOR loop in Jython is not a counted loop as in Java. Instead, it has the ability to traverse elements in a sequence data type such as string, list or tuple. The general syntax of the FOR statement in Jython is as shown below − for iterating_var in sequence: statements(s) We can display each character in a string, as well as each item in a List or Tuple by using the FOR statement as shown below − #each letter in string for letter in 'Python': print 'Current Letter :', letter Output − The output would be as follows. Current Letter : P Current Letter : y Current Letter : t Current Letter : h Current Letter : o Current Letter : n Let us consider another instance as follows. #each item in list libs = [‘PyQt’, 'WxPython', 'Tkinter'] for lib in libs: # Second Example print 'Current library :', lib Output − The output will be as follows. Current library : PyQt Current library : WxPython Current library : Tkinter Here is another instance to consider. #each item in tuple libs = (‘PyQt’, 'WxPython', 'Tkinter') for lib in libs: # Second Example print 'Current library :', lib Output − The output of the above program is as follows. Current library : PyQt Current library : WxPython Current library : Tkinter In Jython, the for statement is also used to iterate over a list of numbers generated by range() function. The range() function takes following form − range[([start],stop,[step]) The start and step parameters are 0 and 1 by default. The last number generated is stop step. The FOR statement traverses the list formed by the range() function. For example − for num in range(5): print num It produces the following output − 0 1 2 3 4 A complex programming logic is broken into one or more independent and reusable blocks of statements called as functions. Python’s standard library contains large numbers of built-in functions. One can also define their own function using the def keyword. User defined name of the function is followed by a block of statements that forms its body, which ends with the return statement. Once defined, it can be called from any environment any number of times. Let us consider the following code to make the point clear. #definition of function defSayHello(): "optional documentation string" print "Hello World" return #calling the function SayHello() A function can be designed to receive one or more parameters / arguments from the calling environment. While calling such a parameterized function, you need to provide the same number of parameters with similar data types used in the function definition, otherwise Jython interpreter throws a TypeError exception. #defining function with two arguments def area(l,b): area = l*b print "area = ",area return #calling function length = 10 breadth = 20 #with two arguments. This is OK area(length, breadth) #only one argument provided. This will throw TypeError area(length) The output will be as follows − area = 200 Traceback (most recent call last): File "area.py", line 11, in <module> area(length) TypeError: area() takes exactly 2 arguments (1 given) After performing the steps defined in it, the called function returns to the calling environment. It can return the data, if an expression is mentioned in front of the return keyword inside the definition of the function. #defining function def area(l,b): area = l*b print "area = ",area return area #calling function length = 10 breadth = 20 #calling function and obtaining its reurned value result = area(length, breadth) print "value returned by function : ", result The following output is obtained if the above script is executed from the Jython prompt. area = 200 value returned by function : 200 A module is a Jython script in which one or more related functions, classes or variables are defined. This allows a logical organization of the Jython code. The Program elements defined in a module can be used in another Jython script by importing either the module or the specific element (function/class) from it. In the following code (hello.py) a function SayHello() is defined. #definition of function defSayHello(str): print "Hello ", str return To use the SayHello() function from another script, import the hello.py module in it. import hello hello.SayHello("TutorialsPoint") However, this will import all functions defined in the module. In order to import specific function from module use following syntax. from modname import name1[, name2[,... nameN] For example, to import only the SayHello() function, change the above script as follows. from hello import SayHello SayHello("TutorialsPoint") There is no need to prefix the name of the module while calling the function. Any folder containing one or more Jython modules is recognized as a package. However, it must have a special file called __init__.py, which provides the index of functions to be used. Let us now understand, how to create and import package. Step 1 − Create a folder called package1, then create and save the following g modules in it. #fact.py def factorial(n): f = 1 for x in range(1,n+1): f = f*x return f #sum.py def add(x,y): s = x+y return s #mult.py def multiply(x,y): s = x*y return s Step 2 − In the package1 folder create and save the __init__.py file with the following content. #__init__.py from fact import factorial from sum import add from mult import multiply Step 3 − Create the following Jython script outside the package1 folder as test.py. # Import your Package. import package1 f = package1.factorial(5) print "factorial = ",f s = package1.add(10,20) print "addition = ",s m = package1.multiply(10,20) print "multiplication = ",m Step 4 − Execute test.py from Jython prompt. The following output will be obtained. factorial = 120 addition = 30 multiplication = 200 Download jython-standalone-2.7.0.jar - For embedding Jython in Java applications from their official downloads page: http://www.jython.org/downloads.html and include this jar file in Java CLASSPATH environment variable. This library contains the PythonInterpreter class. Using the object of this class, any Python script can be executed using the execfile() method. The PythonInterpreter enables you to make use of PyObjects directly. All objects known to the Jython runtime system are represented by an instance of the class PyObject or one of its subclasses. The PythonInterpreter class has some regularly used methods, which are explained in the table given below. setIn(PyObject) Set the Python object to use for the standard input stream setIn(java.io.Reader) Set a java.io.Reader to use for the standard input stream setIn(java.io.InputStream) Set a java.io.InputStream to use for the standard input stream setOut(PyObject) Set the Python object to use for the standard output stream setOut(java.io.Writer) Set the java.io.Writer to use for the standard output stream setOut(java,io.OutputStream) Set the java.io.OutputStream to use for the standard output stream setErr(PyObject) Set a Python error object to use for the standard error stream setErr(java.io.Writer Set a java.io.Writer to use for the standard error stream setErr(java.io.OutputStream) Set a java.io.OutputStream to use for the standard error stream eval(String) Evaluate a string as Python source and return the result eval(PyObject) Evaluate a Python code object and return the result exec(String) Execute a Python source string in the local namespace exec(PyObject) Execute a Python code object in the local namespace execfile(String filename) Execute a file of Python source in the local namespace execfile(java.io.InputStream) Execute an input stream of Python source in the local namespace compile(String) Compile a Python source string as an expression or module compile(script, filename) Compile a script of Python source as an expression or module set(String name, Object value) Set a variable of Object type in the local namespace set(String name, PyObject value) Set a variable of PyObject type in the local namespace get(String) Get the value of a variable in the local namespace get(String name, Classjavaclass Get the value of a variable in the local namespace. The value will be returned as an instance of the given Java class. The following code block is a Java program having an embedded Jython script “hello.py”.usingexecfile() method of the PythonInterpreter object. It also shows how a Python variable can be set or read using set() and get() methods. import org.python.util.PythonInterpreter; import org.python.core.*; public class SimpleEmbedded { public static void main(String []args) throws PyException { PythonInterpreter interp = new PythonInterpreter(); System.out.println("Hello, world from Java"); interp.execfile("hello.py"); interp.set("a", new PyInteger(42)); interp.exec("print a"); interp.exec("x = 2+2"); PyObject x = interp.get("x"); System.out.println("x: "+x); System.out.println("Goodbye "); } } Compile and run the above Java program to obtain the following output. Hello, world from Java hello world from Python 42 x: 4 Goodbye PyDev is an open source plugin for Eclipse IDE to enable development of projects in Python, Jython as well as IronPython. It is hosted at https://pydev.org. A step-by-step procedure to install PyDev plugin in Eclipse IDE is given below. Step 1 − Open Eclipse IDE and choose the Install New Software option from the Help menu. Step 2 − Enter http://pydev.org/updates in the textbox in front of work with label and click add. Choose all available entries in the list and click on Next. The Wizard will take a few minutes to complete the installation and it will prompt the IDE to be restarted. Step 3 − Now choose the preferences option from the Window menu. The Preferences dialog will open as shown below. Step 4 − Expand the Interpreters node and select Jython Interpreter in the left pane. On the right pane, click on new to give path to the jython.jar file. We are now ready to start a Jython project using Eclipse. To make a project in eclipse, we should follow the steps given below. Step 1 − Choose File ? New ? Project. Choose PyDev from the filter dialog. Give project name, project type and click on Finish. Step 2 − Hello project will now appear in the project explorer on the left. Right click to add hello.py in it. Step 3 − An empty hello.py will appear in the editor. Write the Jython code and save. Step 4 − Click on the Run button on the menu bar. The output will appear in the console window as shown below. Python and Jython support for NetBeans is available via the nbPython plugin. Download the plugin from following URL - http://plugins.netbeans.org/plugin/56795. Unzip the downloaded archive in some folder. For example - d:\nbplugin. To install the NetBeans Plugin, let us follow the steps given below. Step 1 − Start the Netbeans IDE and then go to Tools/Plugin to open the Plugin Manager. Choose ‘Downloaded’ tab and browse to the folder in which the downloaded file has been unzipped. The NetBeans window will appear as shown below. Step 2 − The next step is to select all the .nbm files and click open. Step 3 − Click on the Install button. Step 4 − Accept the following license agreement to continue. Ignore the warning about untrusted source of plugins and restart the IDE to proceed. Once restarted, start a new project by choosing File/New. Python category will now be available in the categories list. Choose it to proceed. If the system has Python installed, its version/versions will be automatically detected and shown in the Python platform dropdown list. However, Jython will not be listed. Click on the Manage button to add it. Click on the ‘New’ button to add a platform name and path to Jython executable. Jython will now be available in the platform list. Select from the dropdown list as shown in the following screenshot. We can now fill in the project name, location and main file in the next window. The project structure will appear in the projects window of the NetBeans IDE and a template Python code in the editor window. Build and execute the Jython project to obtain the following result in the output window of the NetBeans IDE. A Java servlet is the most widely used web development technique. We can use Jython to write servlets and this adds many more advantages beyond what Java has to offer because now we can make use of the Python language features as well. We shall use the NetBeans IDE to develop a Java web application with a Jython servlet. Ensure that the nbPython plugin is installed in the NetBeans installation. Start a new project to build a web application by choosing the following path - File → New Project → Java web → New Web Application. Provide the Project name and location. The IDE will create the project folder structure. Add a Java servlet file (ServletTest.java) under the source packages node in the Projects window. This will add servlet-api.jar in the lib folder of the project. Also, let the IDE create the web.xml descriptor file. Add the following code in ServletTest.java. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletTest extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType ("text/html"); PrintWriter toClient = response.getWriter(); toClient.println ( "<html> <head> <title>Servlet Test</title>" + " </head> <body> <h1>Servlet Test</h1> </body> </html>" ); } } The web.xml file created by NetBeans will be as shown below − <web-app> <servlet> <servlet-name>ServletTest</servlet-name> <servlet-class>ServletTest</servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletTest</servlet-name> <url-pattern>/ServletTest</url-pattern> </servlet-mapping> </web-app> Build and run the project to obtain the text Servlet Test appearing in <h1> tag in the browser window. Thus, we have added a regular Java servlet in the application. Now, we shall add the Jython Servlet. Jython servlets work by means of an intermediate Java servlet is also known as PyServlet. The PyServlet.class is present in the jython standalone.jar. Add it in the WEB-INF/lib folder. The next step is to configure the web.xml to invoke the PyServlet, whenever a request for any *.py file is raised. This should be done by adding the following xml code in it. <servlet> <servlet-name>PyServlet</servlet-name> <servlet-class>org.python.util.PyServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>PyServlet</servlet-name> <url-pattern>*.py</url-pattern> </servlet-mapping> The full web.xml code will look as shown below. <web-app> <servlet> <servlet-name>ServletTest</servlet-name> <servlet-class>ServletTest</servlet-class> </servlet> <servlet> <servlet-name>PyServlet</servlet-name> <servlet-class>org.python.util.PyServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ServletTest</servlet-name> <url-pattern>/ServletTest</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>PyServlet</servlet-name> <url-pattern>*.py</url-pattern> </servlet-mapping> </web-app> Place the following Jython code in the WEB-INF folder inside the project folder as JythonServlet.py, which is equivalent to the previous ServletTest.java. from javax.servlet.http import HttpServlet class JythonServlet1 (HttpServlet): def doGet(self,request,response): self.doPost (request,response) def doPost(self,request,response): toClient = response.getWriter() response.setContentType ("text/html") toClient.println ( "<html> <head> <title>Servlet Test</title>" + " </head> <body> <h1>Servlet Test</h1> </body> </html>" ) Build the project and in the browser open the following URL − http://localhost:8080/jythonwebapp/jythonservlet.py The browser will show the Servlet Test in <h1> tag as in case of Java Servlet output. Jython uses the zxJDBC package that provides an easy-to-use Python wrapper around JDBC. zxJDBC bridges two standards: JDBC is the standard platform for database access in Java, and DBI is the standard database API for Python apps. ZxJDBC provides a DBI 2.0 standard compliant interface to JDBC. Over 200 drivers are available for JDBC and they all work with zxJDBC. High performance drivers are available for all major relational databases, including − DB2 Derby MySQL Oracle PostgreSQL SQLite SQL Server and Sybase. The ZxJDBC package can be downloaded from https://sourceforge.net/projects/zxjdbc/ or http://www.ziclix.com/zxjdbc/. The downloaded archive contains the ZxJDBC.jar, which should be added to the CLASSPATH environment variable. We intend to establish database connectivity with MySQL database. For this purpose, the JDBC driver for MySQL is required. Download the MySQL J connector from the following link - https://dev.mysql.com/downloads/connector/j/ and include the mysql connector java-5.1.42-bin.jar in the CLASSPATH. Login to the MySQL server and create a student table in the test database with the following structure − Add a few records in it. Create the following Jython script as dbconnect.py. url = "jdbc:mysql://localhost/test" user = "root" password = "password" driver = "com.mysql.jdbc.Driver" mysqlConn = zxJDBC.connect(url, user, password, driver) mysqlConn = con.cursor() mysqlConn.execute(“select * from student) for a in mysql.fetchall(): print a Execute the above script from the Jython prompt. Records in the student table will be listed as shown below − (“Ravi”, 21, 78) (“Ashok”, 20, 65) (“Anil”,22,71) This explains the procedure of establishing JDBC in Jython. One of the major features of Jython is its ability to use the Swing GUI library in JDK. The Standard Python distribution (often called as CPython) has the Tkinter GUI library shipped with it. Other GUI libraries like PyQt and WxPython are also available for use with it, but the swing library offers a platform independent GUI toolkit. Using the swing library in Jython is much easier compared to using it in Java. In Java the anonymous classes have to be used to create event binding. In Jython, we can simply pass a function for the same purpose. The basic top-level window is created by declaring an object of the JFrame class and set its visible property to true. For that, the Jframe class needs to be imported from the swing package. from javax.swing import JFrame The JFrame class has multiple constructors with varying number of arguments. We shall use the one, which takes a string as argument and sets it as the title. frame = JFrame(“Hello”) Set the frame’s size and location properties before setting its visible property to true. Store the following code as frame.py. from javax.swing import JFrame frame = JFrame("Hello") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(300,200) frame.setVisible(True) Run the above script from the command prompt. It will display the following output showing a window. The swing GUI library is provided in the form of javax.swing package in Java. Its main container classes, JFrame and JDialog are respectively derived from Frame and Dialog classes, which are in the AWT library. Other GUI controls like JLabel, JButton, JTextField, etc., are derived from the JComponent class. The following illustration shows the Swing Package Class hierarchy. The following table summarizes different GUI control classes in a swing library − JLabel A JLabel object is a component for placing text in a container. JButton This class creates a labeled button. JColorChooser A JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color. JCheckBox A JCheckBox is a graphical component that can be in either an on (true) or off (false) state. JRadioButton The JRadioButton class is a graphical component that can be either in an on (true) or off (false) state. in a group. JList A JList component presents the user with a scrolling list of text items. JComboBox A JComboBox component presents the user with drop down list of items JTextField A JTextField object is a text component that allows for the editing of a single line of text. JPasswordField A JPasswordField object is a text component specialized for password entry. JTextArea A JTextArea object is a text component that allows editing of a multiple lines of text. ImageIcon A ImageIcon control is an implementation of the Icon interface that paints Icons from Images JScrollbar A Scrollbar control represents a scroll bar component in order to enable the user to select from range of values. JOptionPane JOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of something. JFileChooser A JFileChooser control represents a dialog window from which the user can select a file. JProgressBar As the task progresses towards completion, the progress bar displays the task's percentage of completion. JSlider A JSlider lets the user graphically select a value by sliding a knob within a bounded interval. JSpinner A JSpinner is a single line input field that lets the user select a number or an object value from an ordered sequence. We would be using some of these controls in subsequent examples. Layout managers in Java are classes those, which manage the placement of controls in the container objects like Frame, Dialog or Panel. Layout managers maintain the relative positioning of controls in a frame, even if the resolution changes or the frame itself is resized. These classes implement the Layout interface. The following Layout managers are defined in the AWT library − BorderLayout FlowLayout GridLayout CardLayout GridBagLayout The following Layout Managers are defined in the Swing library − BoxLayout GroupLayout ScrollPaneLayout SpringLayout We shall use AWT layout managers as well as swing layout managers in the following examples. Absolute Layout Flow Layout Grid Layout Border Layout Box Layout Group Layout Let us now discuss each of these in detail. Before we explore all the above Layout managers, we must look at absolute positioning of the controls in a container. We have to set the layout method of the frame object to ‘None’. frame.setLayout(None) Then place the control by calling the setBounds() method. It takes four arguments - x position, y position, width and height. For example - To place a button object at the absolute position and with the absolute size. btn = JButton("Add") btn.setBounds(60,80,60,20) Similarly, all controls can be placed by properly allocating position and size. This layout is relatively easy to use, but fails to retain its appearance when the window either is resized, or if the program is executed when screen resolution changes. In the following Jython script, three Jlabel objects are used to display text “phy”, “maths” and “Total” respectively. In front of these three - JTextField objects are placed. A Button object is placed above the “Total” label. First of all the JFrame window is created with a layout set to none. frame = JFrame("Hello") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(300,200) frame.setLayout(None) Then different controls are added according to their absolute position and size. The complete code is given below − from javax.swing import JFrame, JLabel, JButton, JTextField frame = JFrame("Hello") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(300,200) frame.setLayout(None) lbl1 = JLabel("Phy") lbl1.setBounds(60,20,40,20) txt1 = JTextField(10) txt1.setBounds(120,20,60,20) lbl2 = JLabel("Maths") lbl2.setBounds(60,50,40,20) txt2 = JTextField(10) txt2.setBounds(120, 50, 60,20) btn = JButton("Add") btn.setBounds(60,80,60,20) lbl3 = JLabel("Total") lbl3.setBounds(60,110,40,20) txt3 = JTextField(10) txt3.setBounds(120, 110, 60,20) frame.add(lbl1) frame.add(txt1) frame.add(lbl2) frame.add(txt2) frame.add(btn) frame.add(lbl3) frame.add(txt3) frame.setVisible(True) The output for the above code is as follows. The FlowLayout is the default layout manager for container classes. It arranges control from left to right and then from top to bottom direction. In following example, a Jlabel object, a JTextField object and a JButton object are to be displayed in a JFrame using FlowLayout manager. To start with, let us import the required classes from the javax.swing package and the java.awt package. from javax.swing import JFrame, JLabel, JButton, JTextField from java.awt import FlowLayout Then create a JFrame object and set its Location as well as the size properties. frame = JFrame("Hello") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(200,200) Set the layout manager for the frame as FlowLayout. frame.setLayout(FlowLayout()) Now declare objects for JLabel, JTextfield and JButton classes. label = JLabel("Welcome to Jython Swing") txt = JTextField(30) btn = JButton("ok") Finally add these controls in the frame by calling the add() method of the JFrame class. frame.add(label) frame.add(txt) frame.add(btn) To display the frame, set its visible property to true. The complete Jython script and its output is as given below − from javax.swing import JFrame, JLabel, JButton, JTextField from java.awt import FlowLayout frame = JFrame("Hello") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(200,200) frame.setLayout(FlowLayout()) label = JLabel("Welcome to Jython Swing") txt = JTextField(30) btn = JButton("ok") frame.add(label) frame.add(txt) frame.add(btn) frame.setVisible(True) The Gridlayout manager allows placement of controls in a rectangular grid. One control is placed in each cell of the grid. In following example, the GridLayout is applied to a JFrame object dividing it in to 4 rows and 4 columns. A JButton object is to be placed in each cell of the grid. Let us first import the required libraries − from javax.swing import JFrame, JButton from java.awt import GridLayout Then create the JFrame container − frame = JFrame("Hello") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,400) Now, apply GridLayout by specifying its dimensions as 4 by 4. frame.setLayout(GridLayout(4,4)) We should now use two FOR loops, each going from 1 to 4, so sixteen JButton objects are placed in subsequent cells. k = 0 frame.setLayout(GridLayout(4,4)) for i in range(1,5): for j in range(1,5): k = k+1 frame.add(JButton(str(k))) Finally set visibility of frame to true. The complete Jython code is given below. from javax.swing import JFrame, JButton from java.awt import GridLayout frame = JFrame("Hello") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,400) frame.setLayout(GridLayout(4,4)) k = 0 for i in range(1,5): for j in range(1,5): k = k+1 frame.add(JButton(str(k))) frame.setVisible(True) The output of the above code is as follows − The BorderLayout manager divides the container in five geographical regions and places with one component in each region. These regions are represented by defined constants as follows − BorderLayout.NORTH BorderLayout.SOUTH BorderLayout.EAST BorderLayout.WEST BorderLayout.CENTER Let us consider the following example − The BoxLayout class is defined in the javax.swing package. It is used to arrange components in the container either vertically or horizontally. The direction is determined by the following constants − X_AXIS Y_AXIS LINE_AXIS PAGE_AXIS The integer constant specifies the axis along which the container's components should be laid out. When the container has the default component orientation, LINE_AXIS specifies that the components be laid out from left to right, and PAGE_AXIS specifies that the components be laid out from top to bottom. In the following example, panel (of JPanel class) is added in a JFrame object. Vertical BoxLayout is applied to it and two more panels, top and bottom, are added to it. These two internal panels have two buttons each added in the horizontal Boxlayout. Let us first create the top-level JFrame window. frame = JFrame() frame.setTitle("Buttons") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(300, 150) The JPanel object is declared having a vertical BoxLayout. Add it in top-level frame. panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS)) frame.add(panel) In this panel, two more panels top and bottom are added to it. Each of them have two JButton objects added to them horizontally with a space holder of 25 pixels separating them. ###top panel top = JPanel() top.setLayout(BoxLayout(top, BoxLayout.X_AXIS)) b1 = JButton("OK") b2 = JButton("Close") top.add(Box.createVerticalGlue()) top.add(b1) top.add(Box.createRigidArea(Dimension(25, 0))) top.add(b2) Similarly, the bottom panel is constructed. ###bottom panel bottom = JPanel() bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS)) b3 = JButton("Open") b4 = JButton("Save") bottom.add(b3) bottom.add(Box.createRigidArea(Dimension(25, 0))) bottom.add(b4) bottom.add(Box.createVerticalGlue()) Note that the createRigidArea() function is used to create a space of 25 pixels between two buttons. Also the createVerticalGlue() function occupies the leading or the trailing space in the layout. To start with, add the top and bottom panels and set the visibility property of the frame to true. The complete code is as follows − from java.awt import Dimension from javax.swing import JButton, JFrame,JPanel,BoxLayout,Box frame = JFrame() frame.setTitle("Buttons") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setSize(300, 150) panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS)) frame.add(panel) ###top panel top = JPanel() top.setLayout(BoxLayout(top, BoxLayout.X_AXIS)) b1 = JButton("OK") b2 = JButton("Close") top.add(Box.createVerticalGlue()) top.add(b1) top.add(Box.createRigidArea(Dimension(25, 0))) top.add(b2) ###bottom panel bottom = JPanel() bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS)) b3 = JButton("Open") b4 = JButton("Save") bottom.add(b3) bottom.add(Box.createRigidArea(Dimension(25, 0))) bottom.add(b4) bottom.add(Box.createVerticalGlue()) panel.add(bottom) panel.add(top) frame.setVisible(True) The above code will generate the following output. The GroupLayout manager groups the components in a hierarchical manner. The grouping is done by two classes, SequentialGroup and ParallelGroup, both implement Group interface in Java. The layout procedure is divided in two steps. In one-step, components are placed along with the horizontal axis, and in second along vertical axis. Each component must be defined twice in the layout. There are two types of arrangements, sequential and parallel. In both, we can arrange components sequentially or in parallel. In horizontal arrangement, row is called sequential group and column is called parallel group. On the other hand, in parallel arrangement, row of element is a parallel group and a column, which is called sequential. In following example, five buttons are arranged in such a way that three each appear in row and column. To start with, Add a Jpanel object in a JFrame window and set its layout as Grouplayout. frame = JFrame() panel = JPanel() frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) layout = GroupLayout(panel) panel.setLayout(layout) Then construct the JButton objects − buttonD = JButton("D") buttonR = JButton("R") buttonY = JButton("Y") buttonO = JButton("O") buttonT = JButton("T") Next, we create a SequentialGroup named LeftToRight to which buttonD and buttonY are added. In between them, a ParallelGroup ColumnMiddle (with other three buttons added vertically) is placed. leftToRight = layout.createSequentialGroup() leftToRight.addComponent(buttonD) columnMiddle = layout.createParallelGroup() columnMiddle.addComponent(buttonR) columnMiddle.addComponent(buttonO) columnMiddle.addComponent(buttonT) leftToRight.addGroup(columnMiddle) leftToRight.addComponent(buttonY) Now comes the definition of vertical SequentialGroup called TopToBottom. Add a ParallelGroup row of three buttons and then rest two buttons vertically. topToBottom = layout.createSequentialGroup() rowTop = layout.createParallelGroup() rowTop.addComponent(buttonD) rowTop.addComponent(buttonR) rowTop.addComponent(buttonY) topToBottom.addGroup(rowTop) topToBottom.addComponent(buttonO) topToBottom.addComponent(buttonT) Finally, set LeftToRight group horizontally and TopToBottom group vertically to the layout object. The complete code is given below − from javax.swing import JButton, JFrame,JPanel,GroupLayout frame = JFrame() panel = JPanel() frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) layout = GroupLayout(panel) panel.setLayout(layout) buttonD = JButton("D") buttonR = JButton("R") buttonY = JButton("Y") buttonO = JButton("O") buttonT = JButton("T") leftToRight = layout.createSequentialGroup() leftToRight.addComponent(buttonD) columnMiddle = layout.createParallelGroup() columnMiddle.addComponent(buttonR) columnMiddle.addComponent(buttonO) columnMiddle.addComponent(buttonT) leftToRight.addGroup(columnMiddle) leftToRight.addComponent(buttonY) topToBottom = layout.createSequentialGroup() rowTop = layout.createParallelGroup() rowTop.addComponent(buttonD) rowTop.addComponent(buttonR) rowTop.addComponent(buttonY) topToBottom.addGroup(rowTop) topToBottom.addComponent(buttonO) topToBottom.addComponent(buttonT) layout.setHorizontalGroup(leftToRight) layout.setVerticalGroup(topToBottom) frame.add(panel) frame.pack() frame.setVisible(True) The output of the above code is as follows − Event handling in Java swing requires that the control (like JButton or JList etc.) should be registered with the respective event listener. The event listener interface or corresponding Adapter class needs to be either implemented or subclassed with its event handling method overridden. In Jython, the event handling is very simple. We can pass any function as property of event handling function corresponding to the control. Let us first see how a click event is handled in Java. To begin with, we have to import the java.awt.event package. Next, the class extending JFrame must implement ActionListener interface. public class btnclick extends JFrame implements ActionListener Then, we have to declare the JButton object, add it to the ContentPane of frame and then register it with ActionListener by the addActionListener() method. JButton b1 = new JButton("Click here"); getContentPane().add(b1); b1.addActionListener(this); Now, the actionPerformed() method of the ActionListener interface must be overridden to handle the ActionEvent. Following is entire Java code − import java.awt.event.*; import javax.swing.*; public class btnclick extends JFrame implements ActionListener { btnclick() { JButton b1 = new JButton("Click here"); getContentPane().add(b1); b1.addActionListener(this); } public void actionPerformed(ActionEvent e) { System.out.println("Clicked"); } public static void main(String args[]) { btnclick b = new btnclick(); b.setSize(300,200); b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); b.setVisible(true); } } Now, we will write the Jython code equivalent to the same code. To start with, we do not need to import the ActionEvent or the ActionListener, since Jython’s dynamic typing allows us to avoid mentioning these classes in our code. Secondly, there is no need to implement or subclass ActionListener. Instead, any user defined function is straightaway provided to the JButton constructor as a value of actionPerformed bean property. button = JButton('Click here!', actionPerformed = clickhere) The clickhere() function is defined as a regular Jython function, which handles the click event on the button. def change_text(event): print clicked!' Here is the Jython equivalent code. from javax.swing import JFrame, JButton frame = JFrame("Hello") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(300,200) def clickhere(event): print "clicked" btn = JButton("Add", actionPerformed = clickhere) frame.add(btn) frame.setVisible(True) The Output of Java and Jython code is identical. When the button is clicked, it will print the ‘clicked’ message on the console. In the following Jython code, two JTextField objects are provided on the JFrame window to enter marks in ‘phy’ and ‘maths’. The JButton object executes the add() function when clicked. btn = JButton("Add", actionPerformed = add) The add() function reads the contents of two text fields by the getText() method and parses them to integers, so that, addition can be performed. The result is then put in the third text field by the setText() method. def add(event): print "add" ttl = int(txt1.getText())+int(txt2.getText()) txt3.setText(str(ttl)) The complete code is given below − from javax.swing import JFrame, JLabel, JButton, JTextField from java.awt import Dimension frame = JFrame("Hello") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(300,200) frame.setLayout(None) def add(event): print "add" ttl = int(txt1.getText())+int(txt2.getText()) txt3.setText(str(ttl)) lbl1 = JLabel("Phy") lbl1.setBounds(60,20,40,20) txt1 = JTextField(10) txt1.setBounds(120,20,60,20) lbl2 = JLabel("Maths") lbl2.setBounds(60,50,40,20) txt2 = JTextField(10) txt2.setBounds(120, 50, 60,20) btn = JButton("Add", actionPerformed = add) btn.setBounds(60,80,60,20) lbl3 = JLabel("Total") lbl3.setBounds(60,110,40,20) txt3 = JTextField(10) txt3.setBounds(120, 110, 60,20) frame.add(lbl1) frame.add(txt1) frame.add(lbl2) frame.add(txt2) frame.add(btn) frame.add(lbl3) frame.add(txt3) frame.setVisible(True) When the above code is executed from the command prompt, the following window appears. Enter marks for ‘Phy’, Maths’, and click on the ‘Add’ button. The result will be displayed accordingly. The JRadioButton class is defined in the javax.swing package. It creates a selectable toggle button with on or off states. If multiple radio buttons are added in a ButtonGroup, their selection is mutually exclusive. In the following example, two objects of the JRadioButton class and two JLabels are added to a Jpanel container in a vertical BoxLayout. In the constructor of the JRadioButton objects, the OnCheck() function is set as the value of the actionPerformed property. This function is executed when the radio button is clicked to change its state. rb1 = JRadioButton("Male", True,actionPerformed = OnCheck) rb2 = JRadioButton("Female", actionPerformed = OnCheck) Note that the default state of Radio Button is false (not selected). The button rb1 is created with its starting state as True (selected). The two radio buttons are added to a radio ButtonGroup to make them mutually exclusive, so that if one is selected, other is deselected automatically. grp = ButtonGroup() grp.add(rb1) grp.add(rb2) These two radio buttons along with two labels are added to a panel object in the vertical layout with a separator area of 25 pixels in heights between rb2 and lbl2. panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS)) panel.add(Box.createVerticalGlue()) panel.add(lbl) panel.add(rb1) panel.add(rb2) panel.add(Box.createRigidArea(Dimension(0,25))) panel.add(lbl1) This panel is added to a top-level JFrame object, whose visible property is set to ‘True’ in the end. frame = JFrame("JRadioButton Example") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(250,200) frame.setVisible(True) The complete code of radio.py is given below: from javax.swing import JFrame, JPanel, JLabel, BoxLayout, Box from java.awt import Dimension from javax.swing import JRadioButton,ButtonGroup frame = JFrame("JRadioButton Example") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(250,200) panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS)) frame.add(panel) def OnCheck(event): lbl1.text = "" if rb1.isSelected(): lbl1.text = lbl1.text+"Gender selection : Male" else: lbl1.text = lbl1.text+"Gender selection : Female " lbl = JLabel("Select Gender") rb1 = JRadioButton("Male", True,actionPerformed = OnCheck) rb2 = JRadioButton("Female", actionPerformed = OnCheck) grp = ButtonGroup() grp.add(rb1) grp.add(rb2) lbl1 = JLabel("Gender Selection :") panel.add(Box.createVerticalGlue()) panel.add(lbl) panel.add(rb1) panel.add(rb2) panel.add(Box.createRigidArea(Dimension(0,25))) panel.add(lbl1) frame.setVisible(True) Run the above Jython script and change the radio button selection. The selection will appear in the label at the bottom. Like the JRadioButton, JCheckBox object is also a selectable button with a rectangular checkable box besides its caption. This is generally used to provide user opportunity to select multiple options from the list of items. In the following example, two check boxes and a label from swing package are added to a JPanel in vertical BoxLayout. The label at bottom displays the instantaneous selection state of two check boxes. Both checkboxes are declared with the constructor having the actionPerformed property set to the OnCheck() function. box1 = JCheckBox("Check1", actionPerformed = OnCheck) box2 = JCheckBox("Check2", actionPerformed = OnCheck) The OnCheck() function verifies selection state of each check box and displays corresponding message on the label at the bottom. def OnCheck(event): lbl1.text = "" if box1.isSelected(): lbl1.text = lbl1.text + "box1 selected " else: lbl1.text = lbl1.text + "box1 not selected " if box2.isSelected(): lbl1.text = lbl1.text + "box2 selected" else: lbl1.text = lbl1.text + "box2 not selected" These boxes and a JLabel object are added to a JPanel with a spaceholder of 50 pixels in height added between them. panel = JPanel() panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS)) panel.add(Box.createVerticalGlue()) panel.add(box1) panel.add(box2) panel.add(Box.createRigidArea(Dimension(0,50))) panel.add(lbl1) The panel itself is added to a top-level JFrame window, whose visible property is set to true in the end. frame = JFrame("JCheckBox Example") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(250,150) frame.add(panel) frame.setVisible(True) Run the above code and experiment with the selection of check boxes. The instantaneous state of both check boxes is displayed at the bottom. The JList control in the swing package provides the user with a scrollable list of items to choose. The JComboBox provides a drop down list of items. In Java, the selection event is processed by implementing the valueChanged() method in the ListSelectionListener. In Jython, an event handler is assigned to the valueChanged property of the JList object. In the following example, a JList object and a label are added to a JFrame in the BorderLayout. The JList is populated with a collection of items in a tuple. Its valueChanged property is set to listSelect() function. lang = ("C", "C++", "Java", "Python", "Perl", "C#", "VB", "PHP", "Javascript", "Ruby") lst = JList(lang, valueChanged = listSelect) The event handler function obtains the index of the selected item and fetches the corresponding item from the JList object to be displayed on the label at the bottom. def listSelect(event): index = lst.selectedIndex lbl1.text = "Hello" + lang[index] The JList and JLabel object are added to the JFrame using BorderLayout. The entire code is given below − from javax.swing import JFrame, JPanel, JLabel, JList from java.awt import BorderLayout frame = JFrame("JList Example") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(300,250) frame.setLayout(BorderLayout()) def listSelect(event): index = lst.selectedIndex lbl1.text = "Hello" + lang[index] lang = ("C", "C++", "Java", "Python", "Perl", "C#", "VB", "PHP", "Javascript", "Ruby") lst = JList(lang, valueChanged = listSelect) lbl1 = JLabel("box1 not selected box2 not selected") frame.add(lst, BorderLayout.NORTH) frame.add(lbl1, BorderLayout.SOUTH) frame.setVisible(True) The output of the following code is as follows. Most of the GUI based applications have a Menu bar at the top. It is found just below the title bar of the top-level window. The javax.swing package has elaborate facility to build an efficient menu system. It is constructed with the help of JMenuBar, JMenu and JMenuItem classes. In following example, a menu bar is provided in the top-level window. A File menu consisting of three menu item buttons is added to the menu bar. Let us now prepare a JFrame object with the layout set to BorderLayout. frame = JFrame("JMenuBar example") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,300) frame.setLayout(BorderLayout()) Now, a JMenuBar object is activated by the SetJMenuBar() method. bar = JMenuBar() frame.setJMenuBar(bar) Next, a JMenu object having ‘File’ caption is declared. Three JMenuItem buttons are added to the File menu. When any of the menu items are clicked, the ActionEvent handler OnClick() function is executed. It is defined with the actionPerformed property. file = JMenu("File") newfile = JMenuItem("New",actionPerformed = OnClick) openfile = JMenuItem("Open",actionPerformed = OnClick) savefile = JMenuItem("Save",actionPerformed = OnClick) file.add(newfile) file.add(openfile) file.add(savefile) bar.add(file) The OnClick() event handler retrieves the name of the JMenuItem button by the gwtActionCommand() function and displays it in the text box at the bottom of the window. def OnClick(event): txt.text = event.getActionCommand() The File menu object is added to menu bar. Finally, a JTextField control is added at the bottom of the JFrame object. txt = JTextField(10) frame.add(txt, BorderLayout.SOUTH) The entire code of menu.py is given below − from javax.swing import JFrame, JMenuBar, JMenu, JMenuItem, JTextField from java.awt import BorderLayout frame = JFrame("JMenuBar example") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,300) frame.setLayout(BorderLayout()) def OnClick(event): txt.text = event.getActionCommand() bar = JMenuBar() frame.setJMenuBar(bar) file = JMenu("File") newfile = JMenuItem("New",actionPerformed = OnClick) openfile = JMenuItem("Open",actionPerformed = OnClick) savefile = JMenuItem("Save",actionPerformed = OnClick) file.add(newfile) file.add(openfile) file.add(savefile) bar.add(file) txt = JTextField(10) frame.add(txt, BorderLayout.SOUTH) frame.setVisible(True) When the above script is executed using the Jython interpreter, a window with the File menu appears. Click on it and its three menu items will drop down. If any button is clicked, its name will be displayed in the text box control. A Dialog object is a window that appears on top of the base window with which the user interacts. In this chapter, we shall see the preconfigured dialogs defined in the swing library. They are MessageDialog, ConfirmDialog and InputDialog. They are available because of the static method of the JOptionPane class. In the following example, the File menu has three JMenu items corresponding to the above three dialogs; each executes the OnClick event handler. file = JMenu("File") msgbtn = JMenuItem("Message",actionPerformed = OnClick) conbtn = JMenuItem("Confirm",actionPerformed = OnClick) inputbtn = JMenuItem("Input",actionPerformed = OnClick) file.add(msgbtn) file.add(conbtn) file.add(inputbtn) The OnClick() handler function retrieves the caption of Menu Item button and invokes the respective showXXXDialog() method. def OnClick(event): str = event.getActionCommand() if str == 'Message': JOptionPane.showMessageDialog(frame,"this is a sample message dialog") if str == "Input": x = JOptionPane.showInputDialog(frame,"Enter your name") txt.setText(x) if str == "Confirm": s = JOptionPane.showConfirmDialog (frame, "Do you want to continue?") if s == JOptionPane.YES_OPTION: txt.setText("YES") if s == JOptionPane.NO_OPTION: txt.setText("NO") if s == JOptionPane.CANCEL_OPTION: txt.setText("CANCEL") If the message option from menu is chosen, a message pops up. If Input option is clicked, a dialog asking for the input pops up. The input text is then displayed in the text box in the JFrame window. If the Confirm option is selected, a dialog with three buttons, YES, NO and CANCEL comes up. The user’s choice is recorded in the text box. The entire code is given below − from javax.swing import JFrame, JMenuBar, JMenu, JMenuItem, JTextField from java.awt import BorderLayout from javax.swing import JOptionPane frame = JFrame("Dialog example") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,300) frame.setLayout(BorderLayout()) def OnClick(event): str = event.getActionCommand() if str == 'Message': JOptionPane.showMessageDialog(frame,"this is a sample message dialog") if str == "Input": x = JOptionPane.showInputDialog(frame,"Enter your name") txt.setText(x) if str == "Confirm": s = JOptionPane.showConfirmDialog (frame, "Do you want to continue?") if s == JOptionPane.YES_OPTION: txt.setText("YES") if s == JOptionPane.NO_OPTION: txt.setText("NO") if s == JOptionPane.CANCEL_OPTION: txt.setText("CANCEL") bar = JMenuBar() frame.setJMenuBar(bar) file = JMenu("File") msgbtn = JMenuItem("Message",actionPerformed = OnClick) conbtn = JMenuItem("Confirm",actionPerformed = OnClick) inputbtn = JMenuItem("Input",actionPerformed = OnClick) file.add(msgbtn) file.add(conbtn) file.add(inputbtn) bar.add(file) txt = JTextField(10) frame.add(txt, BorderLayout.SOUTH) frame.setVisible(True) When the above script is executed, the following window is displayed with three options in the menu − Print Add Notes Bookmark this page
[ { "code": null, "e": 2419, "s": 2081, "text": "Jython is the JVM implementation of the Python programming language. It is designed to run on the Java platform. A Jython program can import and use any Java class. Just as Java, Jython program compiles to bytecode. One of the main advantages is that a user interface designed in Python can use GUI elements of AWT, Swing or SWT Package." }, { "code": null, "e": 2832, "s": 2419, "text": "Jython, which started as JPython and was later renamed, follows closely the standard Python implementation called CPython as created by Guido Van Rossum. Jython was created in 1997 by Jim Hugunin. Jython 2.0 was released in 1999. Since then, Jython 2.x releases correspond to equivalent CPython releases. Jython 2.7.0 released in May 2015, corresponds to CPython 2.7. Development of Jython 3.x is under progress." }, { "code": null, "e": 2888, "s": 2832, "text": "Following are the differences between Python and Java −" }, { "code": null, "e": 3124, "s": 2888, "text": "Python is a dynamically typed language. Hence, the type declaration of variable is not needed. Java on the other hand is a statically typed language, which means that the type declaration of variable is mandatory and cannot be changed." }, { "code": null, "e": 3360, "s": 3124, "text": "Python is a dynamically typed language. Hence, the type declaration of variable is not needed. Java on the other hand is a statically typed language, which means that the type declaration of variable is mandatory and cannot be changed." }, { "code": null, "e": 3454, "s": 3360, "text": "Python has only unchecked exceptions, whereas Java has both checked and unchecked exceptions." }, { "code": null, "e": 3548, "s": 3454, "text": "Python has only unchecked exceptions, whereas Java has both checked and unchecked exceptions." }, { "code": null, "e": 3622, "s": 3548, "text": "Python uses indents for scoping, while Java uses matching curly brackets." }, { "code": null, "e": 3696, "s": 3622, "text": "Python uses indents for scoping, while Java uses matching curly brackets." }, { "code": null, "e": 3871, "s": 3696, "text": "Since Python is an interpreter-based language, it has no separate compilation steps. A Java program however needs to be compiled to bytecode and is in turn executed by a JVM." }, { "code": null, "e": 4046, "s": 3871, "text": "Since Python is an interpreter-based language, it has no separate compilation steps. A Java program however needs to be compiled to bytecode and is in turn executed by a JVM." }, { "code": null, "e": 4182, "s": 4046, "text": "Python supports multiple inheritance, but in Java, multiple inheritance is not possible. It however has implementation of an interface." }, { "code": null, "e": 4318, "s": 4182, "text": "Python supports multiple inheritance, but in Java, multiple inheritance is not possible. It however has implementation of an interface." }, { "code": null, "e": 4430, "s": 4318, "text": "Compared to Java, Python has a richer built-in data structures (lists, dicts, tuples, everything is an object)." }, { "code": null, "e": 4542, "s": 4430, "text": "Compared to Java, Python has a richer built-in data structures (lists, dicts, tuples, everything is an object)." }, { "code": null, "e": 4600, "s": 4542, "text": "Following are the differences between Python and Jython −" }, { "code": null, "e": 4762, "s": 4600, "text": "Reference implementation of Python, called CPython, is written in C language. Jython on the other hand is completely written in Java and is a JVM implementation." }, { "code": null, "e": 4924, "s": 4762, "text": "Reference implementation of Python, called CPython, is written in C language. Jython on the other hand is completely written in Java and is a JVM implementation." }, { "code": null, "e": 5041, "s": 4924, "text": "Standard Python is available on multiple platforms. Jython is available for any platform with a JVM installed on it." }, { "code": null, "e": 5158, "s": 5041, "text": "Standard Python is available on multiple platforms. Jython is available for any platform with a JVM installed on it." }, { "code": null, "e": 5252, "s": 5158, "text": "Standard Python code compiles to a .pyc file, while Jython program compiles to a .class file." }, { "code": null, "e": 5346, "s": 5252, "text": "Standard Python code compiles to a .pyc file, while Jython program compiles to a .class file." }, { "code": null, "e": 5437, "s": 5346, "text": "Python extensions can be written in C language. Extensions for Jython are written in Java." }, { "code": null, "e": 5528, "s": 5437, "text": "Python extensions can be written in C language. Extensions for Jython are written in Java." }, { "code": null, "e": 5651, "s": 5528, "text": "Jython is truly multi-threaded in nature. Python however uses the Global Interpreter Lock (GIL) mechanism for the purpose." }, { "code": null, "e": 5774, "s": 5651, "text": "Jython is truly multi-threaded in nature. Python however uses the Global Interpreter Lock (GIL) mechanism for the purpose." }, { "code": null, "e": 5841, "s": 5774, "text": "Both implementations have different garbage collection mechanisms." }, { "code": null, "e": 5908, "s": 5841, "text": "Both implementations have different garbage collection mechanisms." }, { "code": null, "e": 5987, "s": 5908, "text": "In the next chapter, we will learn how to import the Java libraries in Jython." }, { "code": null, "e": 6256, "s": 5987, "text": "Before installation of Jython 2.7, ensure that the system has JDK 7 or more installed. Jython is available in the form of an executable jar file. Download it from - http://www.jython.org/downloads.html and either double click on its icon or run the following command −" }, { "code": null, "e": 6294, "s": 6256, "text": "java -jar jython_installer-2.7.0.jar\n" }, { "code": null, "e": 6428, "s": 6294, "text": "An installation wizard will commence with which installation options have to be given. Here is the systematic installation procedure." }, { "code": null, "e": 6490, "s": 6428, "text": "The first step in the wizard asks you to select the language." }, { "code": null, "e": 6551, "s": 6490, "text": "The second step prompts you to accept the licence agreement." }, { "code": null, "e": 6654, "s": 6551, "text": "In the next step, choose the installation type. It is recommended to choose the Standard installation." }, { "code": null, "e": 6755, "s": 6654, "text": "The next screen asks your confirmation about your options and proceeds to complete the installation." }, { "code": null, "e": 6816, "s": 6755, "text": "The installation procedure might take some time to complete." }, { "code": null, "e": 7022, "s": 6816, "text": "After the installation is complete, invoke jython.exe from the bin directory inside the destination directory. Assuming that Jython is installed in C:\\jython27, execute the following from the command line." }, { "code": null, "e": 7046, "s": 7022, "text": "C:\\jython27\\bin\\jython\n" }, { "code": null, "e": 7154, "s": 7046, "text": "A Python prompt (>>>) will appear, in front of which any Python statement or Python script can be executed." }, { "code": null, "e": 7476, "s": 7154, "text": "One of the most important features of Jython is its ability to import Java classes in a Python program. We can import any java package or class in Jython, just as we do in a Java program. The following example shows how the java.util packages are imported in Python (Jython) script to declare an object of the Date class." }, { "code": null, "e": 7522, "s": 7476, "text": "from java.util import Date\nd = Date()\nprint d" }, { "code": null, "e": 7645, "s": 7522, "text": "Save and run the above code as UtilDate.py from the command line. Instance of the current date and time will be displayed." }, { "code": null, "e": 7710, "s": 7645, "text": "C:\\jython27\\bin>jython UtilDate.py\nSun Jul 09 00:05:43 IST 2017\n" }, { "code": null, "e": 7897, "s": 7710, "text": "The following packages from the Java library are more often imported in a Jython program mainly because standard Python library either does not have their equivalents or are not as good." }, { "code": null, "e": 7906, "s": 7897, "text": "Servlets" }, { "code": null, "e": 7910, "s": 7906, "text": "JMS" }, { "code": null, "e": 7915, "s": 7910, "text": "J2EE" }, { "code": null, "e": 7923, "s": 7915, "text": "Javadoc" }, { "code": null, "e": 7974, "s": 7923, "text": "Swing is considered superior to other GUI toolkits" }, { "code": null, "e": 8124, "s": 7974, "text": "Any Java package for that matter can be imported in a Jython script. Here, the following java program is stored and compiled in a package called foo." }, { "code": null, "e": 8322, "s": 8124, "text": "package foo;\npublic class HelloWorld {\n public void hello() {\n System.out.println(\"Hello World!\");\n }\n public void hello(String name) {\n System.out.printf(\"Hello %s!\", name);\n }\n}" }, { "code": null, "e": 8460, "s": 8322, "text": "This HelloWorld.class is imported in the following Jython Script. Methods in this class can be called from the Jython script importex.py." }, { "code": null, "e": 8540, "s": 8460, "text": "from foo import HelloWorld\nh = HelloWorld()\nh.hello()\nh.hello(\"TutorialsPoint\")" }, { "code": null, "e": 8621, "s": 8540, "text": "Save and execute the above script from the command line to get following output." }, { "code": null, "e": 8692, "s": 8621, "text": "C:\\jython27\\bin>jython importex.py\nHello World!\nHello TutorialsPoint!\n" }, { "code": null, "e": 9045, "s": 8692, "text": "Variables are named locations in computer’s memory. Each variable can hold one piece of data in it. Unlike Java, Python is a dynamically typed language. Hence while using Jython also; prior declaration of data type of variable is not done. Rather than the type of variable deciding which data can be stored in it, the data decides the type of variable." }, { "code": null, "e": 9313, "s": 9045, "text": "In the following example, a variable is assigned an integer value. Using the type() built-in function, we can verify that the type of variable is an integer. But, if the same variable is assigned a string, the type() function will string as the type of same variable." }, { "code": null, "e": 9391, "s": 9313, "text": "> x = 10\n>>> type(x)\n<class 'int'>\n\n>>> x = \"hello\"\n>>> type(x)\n<class 'str'>" }, { "code": null, "e": 9456, "s": 9391, "text": "This explains why Python is called a dynamically typed language." }, { "code": null, "e": 9526, "s": 9456, "text": "The following Python built-in data types can also be used in Jython −" }, { "code": null, "e": 9533, "s": 9526, "text": "Number" }, { "code": null, "e": 9540, "s": 9533, "text": "String" }, { "code": null, "e": 9545, "s": 9540, "text": "List" }, { "code": null, "e": 9551, "s": 9545, "text": "Tuple" }, { "code": null, "e": 9562, "s": 9551, "text": "Dictionary" }, { "code": null, "e": 9742, "s": 9562, "text": "Python recognizes numeric data as a number, which may be an integer, a real number with floating point or a complex number. String, List and Tuple data types are called sequences." }, { "code": null, "e": 10062, "s": 9742, "text": "In Python, any signed integer is said to be of type ‘int’. To express a long integer, letter ‘L’ is attached to it. A number with a decimal point separating the integer part from a fractional component is called ‘float’. The fractional part may contain an exponent expressed in the scientific notation using ‘E’ or ‘e’." }, { "code": null, "e": 10240, "s": 10062, "text": "A Complex number is also defined as numeric data type in Python. A complex number contains a real part (a floating-point number) and an imaginary part having ‘j’ attached to it." }, { "code": null, "e": 10436, "s": 10240, "text": "In order to express a number in the Octal or the Hexadecimal representation, 0O or 0X is prefixed to it. The following code block gives examples of different representations of numbers in Python." }, { "code": null, "e": 10597, "s": 10436, "text": "int -> 10, 100, -786, 80\nlong -> 51924361L, -0112L, 47329487234L\nfloat -> 15.2, -21.9, 32.3+e18, -3.25E+101\ncomplex -> 3.14j, 45.j, 3e+26J, 9.322e-36j\n" }, { "code": null, "e": 10839, "s": 10597, "text": "A string is any sequence of characters enclosed in single (e.g. ‘hello’), double (e.g. “hello”) or triple (e.g. ‘“hello’” o “““hello”””) quotation marks. Triple quotes are especially useful if content of the string spans over multiple lines." }, { "code": null, "e": 10994, "s": 10839, "text": "The Escape sequence characters can be included verbatim in triple quoted string. The following examples show different ways to declare a string in Python." }, { "code": null, "e": 11370, "s": 10994, "text": "str = ’hello how are you?’\nstr = ”Hello how are you?”\nstr = \"\"\"this is a long string that is made up of several lines and non-printable\ncharacters such as TAB ( \\t ) and they will show up that way when displayed. NEWLINEs\nwithin the string, whether explicitly given like this within the brackets [ \\n ], or just\na NEWLINE within the variable assignment will also show up.\n\"\"\"" }, { "code": null, "e": 11433, "s": 11370, "text": "The third string when printed, will give the following output." }, { "code": null, "e": 11739, "s": 11433, "text": "this is a long string that is made up of\nseveral lines and non-printable characters such as\nTAB ( \t ) and they will show up that way when displayed.\nNEWLINEs within the string, whether explicitly given like\nthis within the brackets [\n], or just a NEWLINE within\nthe variable assignment will also show up.\n" }, { "code": null, "e": 11951, "s": 11739, "text": "A List is a sequence data type. It is a collection of comma-separated items, not necessarily of the same type, stored in square brackets. Individual item from the List can be accessed using the zero based index." }, { "code": null, "e": 12018, "s": 11951, "text": "The following code block summarizes the usage of a List in Python." }, { "code": null, "e": 12158, "s": 12018, "text": "list1 = ['physics', 'chemistry', 1997, 2000];\nlist2 = [1, 2, 3, 4, 5, 6, 7 ];\nprint \"list1[0]: \", list1[0]\nprint \"list2[1:5]: \", list2[1:5]" }, { "code": null, "e": 12256, "s": 12158, "text": "The following table describes some of the most common Jython Expressions related to Jython Lists." }, { "code": null, "e": 12515, "s": 12256, "text": "A tuple is an immutable collection of comma-separated data items stored in parentheses. It is not possible to delete or modify an element in tuple, nor is it possible to add an element to the tuple collection. The following code block shows Tuple operations." }, { "code": null, "e": 12646, "s": 12515, "text": "tup1 = ('physics','chemistry‘,1997,2000);\ntup2 = (1, 2, 3, 4, 5, 6, 7 );\nprint \"tup1[0]: \", tup1[0]\nprint \"tup2[1:5]: \", tup2[1:5]" }, { "code": null, "e": 12942, "s": 12646, "text": "The Jython Dictionary is similar to Map class in Java Collection framework. It is a collection of key-value pairs. Pairs separated by comma are enclosed in curly brackets. A Dictionary object does not follow zero based index to retrieve element inside it as they are stored by hashing technique." }, { "code": null, "e": 13143, "s": 12942, "text": "The same key cannot appear more than once in a dictionary object. However, more than one key can have same associated values. Different functions available with Dictionary object are explained below −" }, { "code": null, "e": 13270, "s": 13143, "text": "dict = {'011':'New Delhi','022':'Mumbai','033':'Kolkata'}\nprint \"dict[‘011’]: \",dict['011']\nprint \"dict['Age']: \", dict['Age']" }, { "code": null, "e": 13366, "s": 13270, "text": "The following table describes some of the most common Jython Expressions related to Dictionary." }, { "code": null, "e": 13558, "s": 13366, "text": "In addition to Python’s built-in data types, Jython has the benefit of using Java collection classes by importing the java.util package. The following code describes the classes given below −" }, { "code": null, "e": 13591, "s": 13558, "text": "Java ArrayList object with add()" }, { "code": null, "e": 13600, "s": 13591, "text": "remove()" }, { "code": null, "e": 13648, "s": 13600, "text": "get() and set() methods of the ArrayList class." }, { "code": null, "e": 13983, "s": 13648, "text": "import java.util.ArrayList as ArrayList\narr = ArrayList()\narr.add(10)\narr.add(20)\nprint \"ArrayList:\",arr\narr.remove(10) #remove 10 from arraylist\narr.add(0,5) #add 5 at 0th index\nprint \"ArrayList:\",arr\nprint \"element at index 1:\",arr.get(1) #retrieve item at index 1\narr.set(0,100) #set item at 0th index to 100\nprint \"ArrayList:\",arr" }, { "code": null, "e": 14039, "s": 13983, "text": "The above Jython script produces the following output −" }, { "code": null, "e": 14157, "s": 14039, "text": "C:\\jython27\\bin>jython arrlist.py\nArrayList: [10, 20]\nArrayList: [5, 20]\nelement at index 1: 20\nArrayList: [100, 20]\n" }, { "code": null, "e": 14470, "s": 14157, "text": "Jython also implements the Jarray Object, which allows construction of a Java array in Python. In order to work with a jarray, simply define a sequence type in Jython and pass it to the jarrayobject along with the type of object contained within the sequence. All values within a jarray must be of the same type." }, { "code": null, "e": 14540, "s": 14470, "text": "The following table shows the character typecodes used with a jarray." }, { "code": null, "e": 14592, "s": 14540, "text": "The following example shows construction of jarray." }, { "code": null, "e": 14732, "s": 14592, "text": "my_seq = (1,2,3,4,5)\nfrom jarray import array\narr1 = array(my_seq,'i')\nprint arr1\nmyStr = \"Hello Jython\"\narr2 = array(myStr,'c')\nprint arr2" }, { "code": null, "e": 14954, "s": 14732, "text": "Here my_seq is defined as a tuple of integers. It is converted to Jarray arr1. The second example shows that Jarray arr2 is constructed from mySttr string sequence. The output of the above script jarray.py is as follows −" }, { "code": null, "e": 15010, "s": 14954, "text": "array('i', [1, 2, 3, 4, 5])\narray('c', 'Hello Jython')\n" }, { "code": null, "e": 15305, "s": 15010, "text": "Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed, if the condition is determined to be true, and optionally, other statements to be executed, if the condition is determined to be false." }, { "code": null, "e": 15439, "s": 15305, "text": "The following illustration shows the general form of a typical decision making structure found in most of the programming languages −" }, { "code": null, "e": 15800, "s": 15439, "text": "Jython does not use curly brackets to indicate blocks of statements to be executed when the condition is true or false (as is the case in Java). Instead, uniform indent (white space from left margin) is used to form block of statements. Such a uniformly indented block makes the conditional code to be executed when a condition given in ‘if’ statement is true." }, { "code": null, "e": 16119, "s": 15800, "text": "A similar block may be present after an optional ‘else’ statement. Jython also provides the elif statement using which successive conditions can be tested. Here, the else clause will appear last and will be executed only when all the preceding conditions fail. The general syntax of using if..elif..else is as follows." }, { "code": null, "e": 16242, "s": 16119, "text": "if expression1:\n statement(s)\nelif expression2:\n statement(s)\nelif expression3:\n statement(s)\nelse:\n statement(s)\n" }, { "code": null, "e": 16370, "s": 16242, "text": "In the following example, if ..elif ..else construct is used to calculate discount on different values of amount input by user." }, { "code": null, "e": 16588, "s": 16370, "text": "discount = 0\namount = input(\"enter Amount\")\nif amount>1000:\n discount = amount*0.10\nelif amount>500:\n discount = amount*0.05\nelse:\n discount = 0\nprint 'Discount = ',discount\nprint 'Net amount = ',amount-discount" }, { "code": null, "e": 16637, "s": 16588, "text": "The output of above code will be as shown below." }, { "code": null, "e": 16789, "s": 16637, "text": "enter Amount1500\nDiscount = 150.0\nNet amount = 1350.0\nenter Amount600\nDiscount = 30.0\nNet amount = 570.0\nenter Amount200\nDiscount = 0\nNet amount = 200\n" }, { "code": null, "e": 17113, "s": 16789, "text": "In general, statements in a program are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Statements that provide such repetition capability are called looping statements." }, { "code": null, "e": 17176, "s": 17113, "text": "In Jython, a loop can be formed by two statements, which are −" }, { "code": null, "e": 17200, "s": 17176, "text": "The while statement and" }, { "code": null, "e": 17224, "s": 17200, "text": "The while statement and" }, { "code": null, "e": 17242, "s": 17224, "text": "The for statement" }, { "code": null, "e": 17260, "s": 17242, "text": "The for statement" }, { "code": null, "e": 17468, "s": 17260, "text": "A while loop statement in Jython is similar to that in Java. It repeatedly executes a block of statements as long as a given condition is true. The following flowchart describes the behavior of a while loop." }, { "code": null, "e": 17526, "s": 17468, "text": "The general syntax of the while statement is given below." }, { "code": null, "e": 17561, "s": 17526, "text": "while expression:\n statement(s)\n" }, { "code": null, "e": 17689, "s": 17561, "text": "The following Jython code uses the while loop to repeatedly increment and print value of a variable until it is less than zero." }, { "code": null, "e": 17778, "s": 17689, "text": "count = 0\nwhile count<10:\n count = count+1\n print \"count = \",count\nprint \"Good Bye!\"" }, { "code": null, "e": 17819, "s": 17778, "text": "Output − The output would be as follows." }, { "code": null, "e": 17941, "s": 17819, "text": "count = 1\ncount = 2\ncount = 3\ncount = 4\ncount = 5\ncount = 6\ncount = 7\ncount = 8\ncount = 9\ncount = 10\nGood Bye!\n" }, { "code": null, "e": 18172, "s": 17941, "text": "The FOR loop in Jython is not a counted loop as in Java. Instead, it has the ability to traverse elements in a sequence data type such as string, list or tuple. The general syntax of the FOR statement in Jython is as shown below −" }, { "code": null, "e": 18221, "s": 18172, "text": "for iterating_var in sequence:\n statements(s)\n" }, { "code": null, "e": 18348, "s": 18221, "text": "We can display each character in a string, as well as each item in a List or Tuple by using the FOR statement as shown below −" }, { "code": null, "e": 18431, "s": 18348, "text": "#each letter in string\nfor letter in 'Python':\n print 'Current Letter :', letter" }, { "code": null, "e": 18472, "s": 18431, "text": "Output − The output would be as follows." }, { "code": null, "e": 18587, "s": 18472, "text": "Current Letter : P\nCurrent Letter : y\nCurrent Letter : t\nCurrent Letter : h\nCurrent Letter : o\nCurrent Letter : n\n" }, { "code": null, "e": 18632, "s": 18587, "text": "Let us consider another instance as follows." }, { "code": null, "e": 18766, "s": 18632, "text": "#each item in list\nlibs = [‘PyQt’, 'WxPython', 'Tkinter']\nfor lib in libs: # Second Example\n print 'Current library :', lib" }, { "code": null, "e": 18806, "s": 18766, "text": "Output − The output will be as follows." }, { "code": null, "e": 18883, "s": 18806, "text": "Current library : PyQt\nCurrent library : WxPython\nCurrent library : Tkinter\n" }, { "code": null, "e": 18921, "s": 18883, "text": "Here is another instance to consider." }, { "code": null, "e": 19056, "s": 18921, "text": "#each item in tuple\nlibs = (‘PyQt’, 'WxPython', 'Tkinter')\nfor lib in libs: # Second Example\n print 'Current library :', lib" }, { "code": null, "e": 19112, "s": 19056, "text": "Output − The output of the above program is as follows." }, { "code": null, "e": 19189, "s": 19112, "text": "Current library : PyQt\nCurrent library : WxPython\nCurrent library : Tkinter\n" }, { "code": null, "e": 19340, "s": 19189, "text": "In Jython, the for statement is also used to iterate over a list of numbers generated by range() function. The range() function takes following form −" }, { "code": null, "e": 19369, "s": 19340, "text": "range[([start],stop,[step])\n" }, { "code": null, "e": 19546, "s": 19369, "text": "The start and step parameters are 0 and 1 by default. The last number generated is stop step. The FOR statement traverses the list formed by the range() function. For example −" }, { "code": null, "e": 19580, "s": 19546, "text": "for num in range(5):\n print num" }, { "code": null, "e": 19615, "s": 19580, "text": "It produces the following output −" }, { "code": null, "e": 19626, "s": 19615, "text": "0\n1\n2\n3\n4\n" }, { "code": null, "e": 20012, "s": 19626, "text": "A complex programming logic is broken into one or more independent and reusable blocks of statements called as functions. Python’s standard library contains large numbers of built-in functions. One can also define their own function using the def keyword. User defined name of the function is followed by a block of statements that forms its body, which ends with the return statement." }, { "code": null, "e": 20145, "s": 20012, "text": "Once defined, it can be called from any environment any number of times. Let us consider the following code to make the point clear." }, { "code": null, "e": 20286, "s": 20145, "text": "#definition of function\ndefSayHello():\n \"optional documentation string\"\n print \"Hello World\"\n return\n\n#calling the function\nSayHello()" }, { "code": null, "e": 20600, "s": 20286, "text": "A function can be designed to receive one or more parameters / arguments from the calling environment. While calling such a parameterized function, you need to provide the same number of parameters with similar data types used in the function definition, otherwise Jython interpreter throws a TypeError exception." }, { "code": null, "e": 20867, "s": 20600, "text": "#defining function with two arguments\ndef area(l,b):\n area = l*b\n print \"area = \",area\n return\n\n#calling function\nlength = 10\nbreadth = 20\n#with two arguments. This is OK\narea(length, breadth)\n#only one argument provided. This will throw TypeError\narea(length)" }, { "code": null, "e": 20899, "s": 20867, "text": "The output will be as follows −" }, { "code": null, "e": 21056, "s": 20899, "text": "area = 200\nTraceback (most recent call last):\n File \"area.py\", line 11, in <module>\n area(length)\nTypeError: area() takes exactly 2 arguments (1 given)\n" }, { "code": null, "e": 21278, "s": 21056, "text": "After performing the steps defined in it, the called function returns to the calling environment. It can return the data, if an expression is mentioned in front of the return keyword inside the definition of the function." }, { "code": null, "e": 21536, "s": 21278, "text": "#defining function\ndef area(l,b):\n area = l*b\n print \"area = \",area\n return area\n\n#calling function\nlength = 10\nbreadth = 20\n#calling function and obtaining its reurned value\nresult = area(length, breadth)\nprint \"value returned by function : \", result" }, { "code": null, "e": 21625, "s": 21536, "text": "The following output is obtained if the above script is executed from the Jython prompt." }, { "code": null, "e": 21670, "s": 21625, "text": "area = 200\nvalue returned by function : 200\n" }, { "code": null, "e": 21986, "s": 21670, "text": "A module is a Jython script in which one or more related functions, classes or variables are defined. This allows a logical organization of the Jython code. The Program elements defined in a module can be used in another Jython script by importing either the module or the specific element (function/class) from it." }, { "code": null, "e": 22053, "s": 21986, "text": "In the following code (hello.py) a function SayHello() is defined." }, { "code": null, "e": 22128, "s": 22053, "text": "#definition of function\ndefSayHello(str):\n print \"Hello \", str\n return" }, { "code": null, "e": 22214, "s": 22128, "text": "To use the SayHello() function from another script, import the hello.py module in it." }, { "code": null, "e": 22261, "s": 22214, "text": "import hello\nhello.SayHello(\"TutorialsPoint\")\n" }, { "code": null, "e": 22395, "s": 22261, "text": "However, this will import all functions defined in the module. In order to import specific function from module use following syntax." }, { "code": null, "e": 22442, "s": 22395, "text": "from modname import name1[, name2[,... nameN]\n" }, { "code": null, "e": 22531, "s": 22442, "text": "For example, to import only the SayHello() function, change the above script as follows." }, { "code": null, "e": 22585, "s": 22531, "text": "from hello import SayHello\nSayHello(\"TutorialsPoint\")" }, { "code": null, "e": 22663, "s": 22585, "text": "There is no need to prefix the name of the module while calling the function." }, { "code": null, "e": 22847, "s": 22663, "text": "Any folder containing one or more Jython modules is recognized as a package. However, it must have a special file called __init__.py, which provides the index of functions to be used." }, { "code": null, "e": 22904, "s": 22847, "text": "Let us now understand, how to create and import package." }, { "code": null, "e": 22998, "s": 22904, "text": "Step 1 − Create a folder called package1, then create and save the following g modules in it." }, { "code": null, "e": 23086, "s": 22998, "text": "#fact.py\ndef factorial(n):\n f = 1\n for x in range(1,n+1):\n f = f*x\n return f" }, { "code": null, "e": 23131, "s": 23086, "text": "#sum.py\ndef add(x,y):\n s = x+y\n return s" }, { "code": null, "e": 23182, "s": 23131, "text": "#mult.py\ndef multiply(x,y):\n s = x*y\n return s" }, { "code": null, "e": 23279, "s": 23182, "text": "Step 2 − In the package1 folder create and save the __init__.py file with the following content." }, { "code": null, "e": 23365, "s": 23279, "text": "#__init__.py\nfrom fact import factorial\nfrom sum import add\nfrom mult import multiply" }, { "code": null, "e": 23449, "s": 23365, "text": "Step 3 − Create the following Jython script outside the package1 folder as test.py." }, { "code": null, "e": 23641, "s": 23449, "text": "# Import your Package.\nimport package1\n\nf = package1.factorial(5)\nprint \"factorial = \",f\ns = package1.add(10,20)\nprint \"addition = \",s\nm = package1.multiply(10,20)\nprint \"multiplication = \",m" }, { "code": null, "e": 23725, "s": 23641, "text": "Step 4 − Execute test.py from Jython prompt. The following output will be obtained." }, { "code": null, "e": 23777, "s": 23725, "text": "factorial = 120\naddition = 30\nmultiplication = 200\n" }, { "code": null, "e": 23997, "s": 23777, "text": "Download jython-standalone-2.7.0.jar - For embedding Jython in Java applications from their official downloads page: http://www.jython.org/downloads.html and include this jar file in Java CLASSPATH environment variable." }, { "code": null, "e": 24338, "s": 23997, "text": "This library contains the PythonInterpreter class. Using the object of this class, any Python script can be executed using the execfile() method. The PythonInterpreter enables you to make use of PyObjects directly. All objects known to the Jython runtime system are represented by an instance of the class PyObject or one of its subclasses." }, { "code": null, "e": 24445, "s": 24338, "text": "The PythonInterpreter class has some regularly used methods, which are explained in the table given below." }, { "code": null, "e": 24461, "s": 24445, "text": "setIn(PyObject)" }, { "code": null, "e": 24520, "s": 24461, "text": "Set the Python object to use for the standard input stream" }, { "code": null, "e": 24542, "s": 24520, "text": "setIn(java.io.Reader)" }, { "code": null, "e": 24600, "s": 24542, "text": "Set a java.io.Reader to use for the standard input stream" }, { "code": null, "e": 24627, "s": 24600, "text": "setIn(java.io.InputStream)" }, { "code": null, "e": 24690, "s": 24627, "text": "Set a java.io.InputStream to use for the standard input stream" }, { "code": null, "e": 24707, "s": 24690, "text": "setOut(PyObject)" }, { "code": null, "e": 24767, "s": 24707, "text": "Set the Python object to use for the standard output stream" }, { "code": null, "e": 24790, "s": 24767, "text": "setOut(java.io.Writer)" }, { "code": null, "e": 24851, "s": 24790, "text": "Set the java.io.Writer to use for the standard output stream" }, { "code": null, "e": 24880, "s": 24851, "text": "setOut(java,io.OutputStream)" }, { "code": null, "e": 24947, "s": 24880, "text": "Set the java.io.OutputStream to use for the standard output stream" }, { "code": null, "e": 24964, "s": 24947, "text": "setErr(PyObject)" }, { "code": null, "e": 25027, "s": 24964, "text": "Set a Python error object to use for the standard error stream" }, { "code": null, "e": 25049, "s": 25027, "text": "setErr(java.io.Writer" }, { "code": null, "e": 25107, "s": 25049, "text": "Set a java.io.Writer to use for the standard error stream" }, { "code": null, "e": 25136, "s": 25107, "text": "setErr(java.io.OutputStream)" }, { "code": null, "e": 25200, "s": 25136, "text": "Set a java.io.OutputStream to use for the standard error stream" }, { "code": null, "e": 25213, "s": 25200, "text": "eval(String)" }, { "code": null, "e": 25270, "s": 25213, "text": "Evaluate a string as Python source and return the result" }, { "code": null, "e": 25285, "s": 25270, "text": "eval(PyObject)" }, { "code": null, "e": 25337, "s": 25285, "text": "Evaluate a Python code object and return the result" }, { "code": null, "e": 25350, "s": 25337, "text": "exec(String)" }, { "code": null, "e": 25404, "s": 25350, "text": "Execute a Python source string in the local namespace" }, { "code": null, "e": 25419, "s": 25404, "text": "exec(PyObject)" }, { "code": null, "e": 25471, "s": 25419, "text": "Execute a Python code object in the local namespace" }, { "code": null, "e": 25497, "s": 25471, "text": "execfile(String filename)" }, { "code": null, "e": 25552, "s": 25497, "text": "Execute a file of Python source in the local namespace" }, { "code": null, "e": 25582, "s": 25552, "text": "execfile(java.io.InputStream)" }, { "code": null, "e": 25646, "s": 25582, "text": "Execute an input stream of Python source in the local namespace" }, { "code": null, "e": 25662, "s": 25646, "text": "compile(String)" }, { "code": null, "e": 25720, "s": 25662, "text": "Compile a Python source string as an expression or module" }, { "code": null, "e": 25746, "s": 25720, "text": "compile(script, filename)" }, { "code": null, "e": 25807, "s": 25746, "text": "Compile a script of Python source as an expression or module" }, { "code": null, "e": 25838, "s": 25807, "text": "set(String name, Object value)" }, { "code": null, "e": 25891, "s": 25838, "text": "Set a variable of Object type in the local namespace" }, { "code": null, "e": 25924, "s": 25891, "text": "set(String name, PyObject value)" }, { "code": null, "e": 25979, "s": 25924, "text": "Set a variable of PyObject type in the local namespace" }, { "code": null, "e": 25991, "s": 25979, "text": "get(String)" }, { "code": null, "e": 26042, "s": 25991, "text": "Get the value of a variable in the local namespace" }, { "code": null, "e": 26074, "s": 26042, "text": "get(String name, Classjavaclass" }, { "code": null, "e": 26193, "s": 26074, "text": "Get the value of a variable in the local namespace. The value will be returned as an instance of the given Java class." }, { "code": null, "e": 26422, "s": 26193, "text": "The following code block is a Java program having an embedded Jython script “hello.py”.usingexecfile() method of the PythonInterpreter object. It also shows how a Python variable can be set or read using set() and get() methods." }, { "code": null, "e": 26947, "s": 26422, "text": "import org.python.util.PythonInterpreter;\nimport org.python.core.*;\n\npublic class SimpleEmbedded {\n public static void main(String []args) throws PyException {\n PythonInterpreter interp = new PythonInterpreter();\n System.out.println(\"Hello, world from Java\");\n interp.execfile(\"hello.py\");\n interp.set(\"a\", new PyInteger(42));\n interp.exec(\"print a\");\n interp.exec(\"x = 2+2\");\n PyObject x = interp.get(\"x\");\n System.out.println(\"x: \"+x);\n System.out.println(\"Goodbye \");\n }\n}" }, { "code": null, "e": 27018, "s": 26947, "text": "Compile and run the above Java program to obtain the following output." }, { "code": null, "e": 27082, "s": 27018, "text": "Hello, world from Java\nhello world from Python\n42\nx: 4\nGoodbye\n" }, { "code": null, "e": 27319, "s": 27082, "text": "PyDev is an open source plugin for Eclipse IDE to enable development of projects in Python, Jython as well as IronPython. It is hosted at https://pydev.org. A step-by-step procedure to install PyDev plugin in Eclipse IDE is given below." }, { "code": null, "e": 27408, "s": 27319, "text": "Step 1 − Open Eclipse IDE and choose the Install New Software option from the Help menu." }, { "code": null, "e": 27674, "s": 27408, "text": "Step 2 − Enter http://pydev.org/updates in the textbox in front of work with label and click add. Choose all available entries in the list and click on Next. The Wizard will take a few minutes to complete the installation and it will prompt the IDE to be restarted." }, { "code": null, "e": 27788, "s": 27674, "text": "Step 3 − Now choose the preferences option from the Window menu. The Preferences dialog will open as shown below." }, { "code": null, "e": 27943, "s": 27788, "text": "Step 4 − Expand the Interpreters node and select Jython Interpreter in the left pane. On the right pane, click on new to give path to the jython.jar file." }, { "code": null, "e": 28001, "s": 27943, "text": "We are now ready to start a Jython project using Eclipse." }, { "code": null, "e": 28071, "s": 28001, "text": "To make a project in eclipse, we should follow the steps given below." }, { "code": null, "e": 28199, "s": 28071, "text": "Step 1 − Choose File ? New ? Project. Choose PyDev from the filter dialog. Give project name, project type and click on Finish." }, { "code": null, "e": 28310, "s": 28199, "text": "Step 2 − Hello project will now appear in the project explorer on the left. Right click to add hello.py in it." }, { "code": null, "e": 28396, "s": 28310, "text": "Step 3 − An empty hello.py will appear in the editor. Write the Jython code and save." }, { "code": null, "e": 28508, "s": 28396, "text": "Step 4 − Click on the Run button on the menu bar. The output will appear in the console window as shown below." }, { "code": null, "e": 28809, "s": 28508, "text": "Python and Jython support for NetBeans is available via the nbPython plugin. Download the plugin from following URL - http://plugins.netbeans.org/plugin/56795. Unzip the downloaded archive in some folder. For example - d:\\nbplugin. To install the NetBeans Plugin, let us follow the steps given below." }, { "code": null, "e": 29042, "s": 28809, "text": "Step 1 − Start the Netbeans IDE and then go to Tools/Plugin to open the Plugin Manager. Choose ‘Downloaded’ tab and browse to the folder in which the downloaded file has been unzipped. The NetBeans window will appear as shown below." }, { "code": null, "e": 29113, "s": 29042, "text": "Step 2 − The next step is to select all the .nbm files and click open." }, { "code": null, "e": 29151, "s": 29113, "text": "Step 3 − Click on the Install button." }, { "code": null, "e": 29212, "s": 29151, "text": "Step 4 − Accept the following license agreement to continue." }, { "code": null, "e": 29297, "s": 29212, "text": "Ignore the warning about untrusted source of plugins and restart the IDE to proceed." }, { "code": null, "e": 29439, "s": 29297, "text": "Once restarted, start a new project by choosing File/New. Python category will now be available in the categories list. Choose it to proceed." }, { "code": null, "e": 29649, "s": 29439, "text": "If the system has Python installed, its version/versions will be automatically detected and shown in the Python platform dropdown list. However, Jython will not be listed. Click on the Manage button to add it." }, { "code": null, "e": 29729, "s": 29649, "text": "Click on the ‘New’ button to add a platform name and path to Jython executable." }, { "code": null, "e": 29848, "s": 29729, "text": "Jython will now be available in the platform list. Select from the dropdown list as shown in the following screenshot." }, { "code": null, "e": 29928, "s": 29848, "text": "We can now fill in the project name, location and main file in the next window." }, { "code": null, "e": 30054, "s": 29928, "text": "The project structure will appear in the projects window of the NetBeans IDE and a template Python code in the editor window." }, { "code": null, "e": 30164, "s": 30054, "text": "Build and execute the Jython project to obtain the following result in the output window of the NetBeans IDE." }, { "code": null, "e": 30400, "s": 30164, "text": "A Java servlet is the most widely used web development technique. We can use Jython to write servlets and this adds many more advantages beyond what Java has to offer because now we can make use of the Python language features as well." }, { "code": null, "e": 30695, "s": 30400, "text": "We shall use the NetBeans IDE to develop a Java web application with a Jython servlet. Ensure that the nbPython plugin is installed in the NetBeans installation. Start a new project to build a web application by choosing the following path - File → New Project → Java web → New Web Application." }, { "code": null, "e": 31044, "s": 30695, "text": "Provide the Project name and location. The IDE will create the project folder structure. Add a Java servlet file (ServletTest.java) under the source packages node in the Projects window. This will add servlet-api.jar in the lib folder of the project. Also, let the IDE create the web.xml descriptor file. Add the following code in ServletTest.java." }, { "code": null, "e": 31802, "s": 31044, "text": "import java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\n\npublic class ServletTest extends HttpServlet {\n \n public void doGet (HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n doPost(request, response);\n }\n \n public void doPost (HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n response.setContentType (\"text/html\");\n PrintWriter toClient = response.getWriter();\n \n toClient.println (\n \"<html>\n <head>\n <title>Servlet Test</title>\" + \"\n </head>\n <body>\n <h1>Servlet Test</h1>\n </body>\n </html>\"\n );\n }\n}" }, { "code": null, "e": 31864, "s": 31802, "text": "The web.xml file created by NetBeans will be as shown below −" }, { "code": null, "e": 32148, "s": 31864, "text": "<web-app>\n <servlet>\n <servlet-name>ServletTest</servlet-name>\n <servlet-class>ServletTest</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>ServletTest</servlet-name>\n <url-pattern>/ServletTest</url-pattern>\n </servlet-mapping>\n</web-app>" }, { "code": null, "e": 32314, "s": 32148, "text": "Build and run the project to obtain the text Servlet Test appearing in <h1> tag in the browser window. Thus, we have added a regular Java servlet in the application." }, { "code": null, "e": 32537, "s": 32314, "text": "Now, we shall add the Jython Servlet. Jython servlets work by means of an intermediate Java servlet is also known as PyServlet. The PyServlet.class is present in the jython standalone.jar. Add it in the WEB-INF/lib folder." }, { "code": null, "e": 32712, "s": 32537, "text": "The next step is to configure the web.xml to invoke the PyServlet, whenever a request for any *.py file is raised. This should be done by adding the following xml code in it." }, { "code": null, "e": 32990, "s": 32712, "text": "<servlet>\n <servlet-name>PyServlet</servlet-name>\n <servlet-class>org.python.util.PyServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n</servlet>\n\n<servlet-mapping>\n <servlet-name>PyServlet</servlet-name>\n <url-pattern>*.py</url-pattern>\n</servlet-mapping>" }, { "code": null, "e": 33038, "s": 32990, "text": "The full web.xml code will look as shown below." }, { "code": null, "e": 33634, "s": 33038, "text": "<web-app>\n <servlet>\n <servlet-name>ServletTest</servlet-name>\n <servlet-class>ServletTest</servlet-class>\n </servlet>\n \n <servlet>\n <servlet-name>PyServlet</servlet-name>\n <servlet-class>org.python.util.PyServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>ServletTest</servlet-name>\n <url-pattern>/ServletTest</url-pattern>\n </servlet-mapping>\n \n <servlet-mapping>\n <servlet-name>PyServlet</servlet-name>\n <url-pattern>*.py</url-pattern>\n </servlet-mapping>\n</web-app>" }, { "code": null, "e": 33789, "s": 33634, "text": "Place the following Jython code in the WEB-INF folder inside the project folder as JythonServlet.py, which is equivalent to the previous ServletTest.java." }, { "code": null, "e": 34300, "s": 33789, "text": "from javax.servlet.http import HttpServlet\nclass JythonServlet1 (HttpServlet):\n def doGet(self,request,response):\n self.doPost (request,response)\n def doPost(self,request,response):\n toClient = response.getWriter()\n response.setContentType (\"text/html\")\n \n toClient.println (\n \"<html>\n <head>\n <title>Servlet Test</title>\" + \"\n </head>\n <body>\n <h1>Servlet Test</h1>\n </body>\n </html>\"\n )" }, { "code": null, "e": 34362, "s": 34300, "text": "Build the project and in the browser open the following URL −" }, { "code": null, "e": 34414, "s": 34362, "text": "http://localhost:8080/jythonwebapp/jythonservlet.py" }, { "code": null, "e": 34500, "s": 34414, "text": "The browser will show the Servlet Test in <h1> tag as in case of Java Servlet output." }, { "code": null, "e": 34731, "s": 34500, "text": "Jython uses the zxJDBC package that provides an easy-to-use Python wrapper around JDBC. zxJDBC bridges two standards: JDBC is the standard platform for database access in Java, and DBI is the standard database API for Python apps." }, { "code": null, "e": 34953, "s": 34731, "text": "ZxJDBC provides a DBI 2.0 standard compliant interface to JDBC. Over 200 drivers are available for JDBC and they all work with zxJDBC. High performance drivers are available for all major relational databases, including −" }, { "code": null, "e": 34957, "s": 34953, "text": "DB2" }, { "code": null, "e": 34963, "s": 34957, "text": "Derby" }, { "code": null, "e": 34969, "s": 34963, "text": "MySQL" }, { "code": null, "e": 34976, "s": 34969, "text": "Oracle" }, { "code": null, "e": 34987, "s": 34976, "text": "PostgreSQL" }, { "code": null, "e": 34994, "s": 34987, "text": "SQLite" }, { "code": null, "e": 35009, "s": 34994, "text": "SQL Server and" }, { "code": null, "e": 35017, "s": 35009, "text": "Sybase." }, { "code": null, "e": 35243, "s": 35017, "text": "The ZxJDBC package can be downloaded from https://sourceforge.net/projects/zxjdbc/ or http://www.ziclix.com/zxjdbc/. The downloaded archive contains the ZxJDBC.jar, which should be added to the CLASSPATH environment variable." }, { "code": null, "e": 35538, "s": 35243, "text": "We intend to establish database connectivity with MySQL database. For this purpose, the JDBC driver for MySQL is required. Download the MySQL J connector from the following link - https://dev.mysql.com/downloads/connector/j/ and include the mysql connector java-5.1.42-bin.jar in the CLASSPATH." }, { "code": null, "e": 35643, "s": 35538, "text": "Login to the MySQL server and create a student table in the test database with the following structure −" }, { "code": null, "e": 35668, "s": 35643, "text": "Add a few records in it." }, { "code": null, "e": 35720, "s": 35668, "text": "Create the following Jython script as dbconnect.py." }, { "code": null, "e": 35986, "s": 35720, "text": "url = \"jdbc:mysql://localhost/test\"\nuser = \"root\"\npassword = \"password\"\ndriver = \"com.mysql.jdbc.Driver\"\nmysqlConn = zxJDBC.connect(url, user, password, driver)\nmysqlConn = con.cursor()\nmysqlConn.execute(“select * from student)\nfor a in mysql.fetchall():\n print a" }, { "code": null, "e": 36096, "s": 35986, "text": "Execute the above script from the Jython prompt. Records in the student table will be listed as shown below −" }, { "code": null, "e": 36147, "s": 36096, "text": "(“Ravi”, 21, 78)\n(“Ashok”, 20, 65)\n(“Anil”,22,71)\n" }, { "code": null, "e": 36207, "s": 36147, "text": "This explains the procedure of establishing JDBC in Jython." }, { "code": null, "e": 36543, "s": 36207, "text": "One of the major features of Jython is its ability to use the Swing GUI library in JDK. The Standard Python distribution (often called as CPython) has the Tkinter GUI library shipped with it. Other GUI libraries like PyQt and WxPython are also available for use with it, but the swing library offers a platform independent GUI toolkit." }, { "code": null, "e": 36756, "s": 36543, "text": "Using the swing library in Jython is much easier compared to using it in Java. In Java the anonymous classes have to be used to create event binding. In Jython, we can simply pass a function for the same purpose." }, { "code": null, "e": 36948, "s": 36756, "text": "The basic top-level window is created by declaring an object of the JFrame class and set its visible property to true. For that, the Jframe class needs to be imported from the swing package." }, { "code": null, "e": 36979, "s": 36948, "text": "from javax.swing import JFrame" }, { "code": null, "e": 37137, "s": 36979, "text": "The JFrame class has multiple constructors with varying number of arguments. We shall use the one, which takes a string as argument and sets it as the title." }, { "code": null, "e": 37161, "s": 37137, "text": "frame = JFrame(“Hello”)" }, { "code": null, "e": 37289, "s": 37161, "text": "Set the frame’s size and location properties before setting its visible property to true. Store the following code as frame.py." }, { "code": null, "e": 37471, "s": 37289, "text": "from javax.swing import JFrame\n\nframe = JFrame(\"Hello\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(300,200)\nframe.setVisible(True)" }, { "code": null, "e": 37572, "s": 37471, "text": "Run the above script from the command prompt. It will display the following output showing a window." }, { "code": null, "e": 37881, "s": 37572, "text": "The swing GUI library is provided in the form of javax.swing package in Java. Its main container classes, JFrame and JDialog are respectively derived from Frame and Dialog classes, which are in the AWT library. Other GUI controls like JLabel, JButton, JTextField, etc., are derived from the JComponent class." }, { "code": null, "e": 37949, "s": 37881, "text": "The following illustration shows the Swing Package Class hierarchy." }, { "code": null, "e": 38031, "s": 37949, "text": "The following table summarizes different GUI control classes in a swing library −" }, { "code": null, "e": 38038, "s": 38031, "text": "JLabel" }, { "code": null, "e": 38102, "s": 38038, "text": "A JLabel object is a component for placing text in a container." }, { "code": null, "e": 38110, "s": 38102, "text": "JButton" }, { "code": null, "e": 38147, "s": 38110, "text": "This class creates a labeled button." }, { "code": null, "e": 38161, "s": 38147, "text": "JColorChooser" }, { "code": null, "e": 38264, "s": 38161, "text": "A JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color." }, { "code": null, "e": 38274, "s": 38264, "text": "JCheckBox" }, { "code": null, "e": 38368, "s": 38274, "text": "A JCheckBox is a graphical component that can be in either an on (true) or off (false) state." }, { "code": null, "e": 38381, "s": 38368, "text": "JRadioButton" }, { "code": null, "e": 38498, "s": 38381, "text": "The JRadioButton class is a graphical component that can be either in an on (true) or off (false) state. in a group." }, { "code": null, "e": 38504, "s": 38498, "text": "JList" }, { "code": null, "e": 38577, "s": 38504, "text": "A JList component presents the user with a scrolling list of text items." }, { "code": null, "e": 38587, "s": 38577, "text": "JComboBox" }, { "code": null, "e": 38656, "s": 38587, "text": "A JComboBox component presents the user with drop down list of items" }, { "code": null, "e": 38667, "s": 38656, "text": "JTextField" }, { "code": null, "e": 38761, "s": 38667, "text": "A JTextField object is a text component that allows for the editing of a single line of text." }, { "code": null, "e": 38776, "s": 38761, "text": "JPasswordField" }, { "code": null, "e": 38852, "s": 38776, "text": "A JPasswordField object is a text component specialized for password entry." }, { "code": null, "e": 38862, "s": 38852, "text": "JTextArea" }, { "code": null, "e": 38950, "s": 38862, "text": "A JTextArea object is a text component that allows editing of a multiple lines of text." }, { "code": null, "e": 38960, "s": 38950, "text": "ImageIcon" }, { "code": null, "e": 39053, "s": 38960, "text": "A ImageIcon control is an implementation of the Icon interface that paints Icons from Images" }, { "code": null, "e": 39064, "s": 39053, "text": "JScrollbar" }, { "code": null, "e": 39178, "s": 39064, "text": "A Scrollbar control represents a scroll bar component in order to enable the user to select from range of values." }, { "code": null, "e": 39190, "s": 39178, "text": "JOptionPane" }, { "code": null, "e": 39300, "s": 39190, "text": "JOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of something." }, { "code": null, "e": 39313, "s": 39300, "text": "JFileChooser" }, { "code": null, "e": 39402, "s": 39313, "text": "A JFileChooser control represents a dialog window from which the user can select a file." }, { "code": null, "e": 39415, "s": 39402, "text": "JProgressBar" }, { "code": null, "e": 39521, "s": 39415, "text": "As the task progresses towards completion, the progress bar displays the task's percentage of completion." }, { "code": null, "e": 39529, "s": 39521, "text": "JSlider" }, { "code": null, "e": 39625, "s": 39529, "text": "A JSlider lets the user graphically select a value by sliding a knob within a bounded interval." }, { "code": null, "e": 39634, "s": 39625, "text": "JSpinner" }, { "code": null, "e": 39754, "s": 39634, "text": "A JSpinner is a single line input field that lets the user select a number or an object value from an ordered sequence." }, { "code": null, "e": 39819, "s": 39754, "text": "We would be using some of these controls in subsequent examples." }, { "code": null, "e": 40092, "s": 39819, "text": "Layout managers in Java are classes those, which manage the placement of controls in the container objects like Frame, Dialog or Panel. Layout managers maintain the relative positioning of controls in a frame, even if the resolution changes or the frame itself is resized." }, { "code": null, "e": 40201, "s": 40092, "text": "These classes implement the Layout interface. The following Layout managers are defined in the AWT library −" }, { "code": null, "e": 40214, "s": 40201, "text": "BorderLayout" }, { "code": null, "e": 40225, "s": 40214, "text": "FlowLayout" }, { "code": null, "e": 40236, "s": 40225, "text": "GridLayout" }, { "code": null, "e": 40247, "s": 40236, "text": "CardLayout" }, { "code": null, "e": 40261, "s": 40247, "text": "GridBagLayout" }, { "code": null, "e": 40326, "s": 40261, "text": "The following Layout Managers are defined in the Swing library −" }, { "code": null, "e": 40336, "s": 40326, "text": "BoxLayout" }, { "code": null, "e": 40348, "s": 40336, "text": "GroupLayout" }, { "code": null, "e": 40365, "s": 40348, "text": "ScrollPaneLayout" }, { "code": null, "e": 40378, "s": 40365, "text": "SpringLayout" }, { "code": null, "e": 40471, "s": 40378, "text": "We shall use AWT layout managers as well as swing layout managers in the following examples." }, { "code": null, "e": 40487, "s": 40471, "text": "Absolute Layout" }, { "code": null, "e": 40499, "s": 40487, "text": "Flow Layout" }, { "code": null, "e": 40511, "s": 40499, "text": "Grid Layout" }, { "code": null, "e": 40525, "s": 40511, "text": "Border Layout" }, { "code": null, "e": 40536, "s": 40525, "text": "Box Layout" }, { "code": null, "e": 40549, "s": 40536, "text": "Group Layout" }, { "code": null, "e": 40593, "s": 40549, "text": "Let us now discuss each of these in detail." }, { "code": null, "e": 40775, "s": 40593, "text": "Before we explore all the above Layout managers, we must look at absolute positioning of the controls in a container. We have to set the layout method of the frame object to ‘None’." }, { "code": null, "e": 40797, "s": 40775, "text": "frame.setLayout(None)" }, { "code": null, "e": 40923, "s": 40797, "text": "Then place the control by calling the setBounds() method. It takes four arguments - x position, y position, width and height." }, { "code": null, "e": 41015, "s": 40923, "text": "For example - To place a button object at the absolute position and with the absolute size." }, { "code": null, "e": 41063, "s": 41015, "text": "btn = JButton(\"Add\")\nbtn.setBounds(60,80,60,20)" }, { "code": null, "e": 41314, "s": 41063, "text": "Similarly, all controls can be placed by properly allocating position and size. This layout is relatively easy to use, but fails to retain its appearance when the window either is resized, or if the program is executed when screen resolution changes." }, { "code": null, "e": 41541, "s": 41314, "text": "In the following Jython script, three Jlabel objects are used to display text “phy”, “maths” and “Total” respectively. In front of these three - JTextField objects are placed. A Button object is placed above the “Total” label." }, { "code": null, "e": 41610, "s": 41541, "text": "First of all the JFrame window is created with a layout set to none." }, { "code": null, "e": 41759, "s": 41610, "text": "frame = JFrame(\"Hello\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(300,200)\nframe.setLayout(None)" }, { "code": null, "e": 41875, "s": 41759, "text": "Then different controls are added according to their absolute position and size. The complete code is given below −" }, { "code": null, "e": 42579, "s": 41875, "text": "from javax.swing import JFrame, JLabel, JButton, JTextField\n\nframe = JFrame(\"Hello\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(300,200)\nframe.setLayout(None)\n\nlbl1 = JLabel(\"Phy\")\nlbl1.setBounds(60,20,40,20)\ntxt1 = JTextField(10)\ntxt1.setBounds(120,20,60,20)\nlbl2 = JLabel(\"Maths\")\nlbl2.setBounds(60,50,40,20)\ntxt2 = JTextField(10)\ntxt2.setBounds(120, 50, 60,20)\nbtn = JButton(\"Add\")\nbtn.setBounds(60,80,60,20)\nlbl3 = JLabel(\"Total\")\nlbl3.setBounds(60,110,40,20)\ntxt3 = JTextField(10)\ntxt3.setBounds(120, 110, 60,20)\n\nframe.add(lbl1)\nframe.add(txt1)\nframe.add(lbl2)\nframe.add(txt2)\nframe.add(btn)\nframe.add(lbl3)\nframe.add(txt3)\nframe.setVisible(True)" }, { "code": null, "e": 42624, "s": 42579, "text": "The output for the above code is as follows." }, { "code": null, "e": 42770, "s": 42624, "text": "The FlowLayout is the default layout manager for container classes. It arranges control from left to right and then from top to bottom direction." }, { "code": null, "e": 43013, "s": 42770, "text": "In following example, a Jlabel object, a JTextField object and a JButton object are to be displayed in a JFrame using FlowLayout manager. To start with, let us import the required classes from the javax.swing package and the java.awt package." }, { "code": null, "e": 43105, "s": 43013, "text": "from javax.swing import JFrame, JLabel, JButton, JTextField\nfrom java.awt import FlowLayout" }, { "code": null, "e": 43186, "s": 43105, "text": "Then create a JFrame object and set its Location as well as the size properties." }, { "code": null, "e": 43395, "s": 43186, "text": "frame = JFrame(\"Hello\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(200,200)\nSet the layout manager for the frame as FlowLayout.\nframe.setLayout(FlowLayout())" }, { "code": null, "e": 43459, "s": 43395, "text": "Now declare objects for JLabel, JTextfield and JButton classes." }, { "code": null, "e": 43542, "s": 43459, "text": "label = JLabel(\"Welcome to Jython Swing\")\ntxt = JTextField(30)\nbtn = JButton(\"ok\")" }, { "code": null, "e": 43631, "s": 43542, "text": "Finally add these controls in the frame by calling the add() method of the JFrame class." }, { "code": null, "e": 43678, "s": 43631, "text": "frame.add(label)\nframe.add(txt)\nframe.add(btn)" }, { "code": null, "e": 43796, "s": 43678, "text": "To display the frame, set its visible property to true. The complete Jython script and its output is as given below −" }, { "code": null, "e": 44202, "s": 43796, "text": "from javax.swing import JFrame, JLabel, JButton, JTextField\nfrom java.awt import FlowLayout\n\nframe = JFrame(\"Hello\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(200,200)\n\nframe.setLayout(FlowLayout())\n\nlabel = JLabel(\"Welcome to Jython Swing\")\ntxt = JTextField(30)\nbtn = JButton(\"ok\")\n\nframe.add(label)\nframe.add(txt)\nframe.add(btn)\nframe.setVisible(True)" }, { "code": null, "e": 44325, "s": 44202, "text": "The Gridlayout manager allows placement of controls in a rectangular grid. One control is placed in each cell of the grid." }, { "code": null, "e": 44491, "s": 44325, "text": "In following example, the GridLayout is applied to a JFrame object dividing it in to 4 rows and 4 columns. A JButton object is to be placed in each cell of the grid." }, { "code": null, "e": 44536, "s": 44491, "text": "Let us first import the required libraries −" }, { "code": null, "e": 44608, "s": 44536, "text": "from javax.swing import JFrame, JButton\nfrom java.awt import GridLayout" }, { "code": null, "e": 44643, "s": 44608, "text": "Then create the JFrame container −" }, { "code": null, "e": 44770, "s": 44643, "text": "frame = JFrame(\"Hello\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(400,400)" }, { "code": null, "e": 44832, "s": 44770, "text": "Now, apply GridLayout by specifying its dimensions as 4 by 4." }, { "code": null, "e": 44865, "s": 44832, "text": "frame.setLayout(GridLayout(4,4))" }, { "code": null, "e": 44981, "s": 44865, "text": "We should now use two FOR loops, each going from 1 to 4, so sixteen JButton objects are placed in subsequent cells." }, { "code": null, "e": 45112, "s": 44981, "text": "k = 0\nframe.setLayout(GridLayout(4,4))\nfor i in range(1,5):\n for j in range(1,5):\n k = k+1\n frame.add(JButton(str(k)))" }, { "code": null, "e": 45194, "s": 45112, "text": "Finally set visibility of frame to true. The complete Jython code is given below." }, { "code": null, "e": 45551, "s": 45194, "text": "from javax.swing import JFrame, JButton\nfrom java.awt import GridLayout\n\nframe = JFrame(\"Hello\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(400,400)\n\nframe.setLayout(GridLayout(4,4))\n\nk = 0\nfor i in range(1,5):\n for j in range(1,5):\n k = k+1\n frame.add(JButton(str(k)))\n\nframe.setVisible(True)" }, { "code": null, "e": 45596, "s": 45551, "text": "The output of the above code is as follows −" }, { "code": null, "e": 45782, "s": 45596, "text": "The BorderLayout manager divides the container in five geographical regions and places with one component in each region. These regions are represented by defined constants as follows −" }, { "code": null, "e": 45801, "s": 45782, "text": "BorderLayout.NORTH" }, { "code": null, "e": 45820, "s": 45801, "text": "BorderLayout.SOUTH" }, { "code": null, "e": 45838, "s": 45820, "text": "BorderLayout.EAST" }, { "code": null, "e": 45856, "s": 45838, "text": "BorderLayout.WEST" }, { "code": null, "e": 45876, "s": 45856, "text": "BorderLayout.CENTER" }, { "code": null, "e": 45916, "s": 45876, "text": "Let us consider the following example −" }, { "code": null, "e": 46117, "s": 45916, "text": "The BoxLayout class is defined in the javax.swing package. It is used to arrange components in the container either vertically or horizontally. The direction is determined by the following constants −" }, { "code": null, "e": 46124, "s": 46117, "text": "X_AXIS" }, { "code": null, "e": 46131, "s": 46124, "text": "Y_AXIS" }, { "code": null, "e": 46141, "s": 46131, "text": "LINE_AXIS" }, { "code": null, "e": 46151, "s": 46141, "text": "PAGE_AXIS" }, { "code": null, "e": 46456, "s": 46151, "text": "The integer constant specifies the axis along which the container's components should be laid out. When the container has the default component orientation, LINE_AXIS specifies that the components be laid out from left to right, and PAGE_AXIS specifies that the components be laid out from top to bottom." }, { "code": null, "e": 46708, "s": 46456, "text": "In the following example, panel (of JPanel class) is added in a JFrame object. Vertical BoxLayout is applied to it and two more panels, top and bottom, are added to it. These two internal panels have two buttons each added in the horizontal Boxlayout." }, { "code": null, "e": 46757, "s": 46708, "text": "Let us first create the top-level JFrame window." }, { "code": null, "e": 46877, "s": 46757, "text": "frame = JFrame()\nframe.setTitle(\"Buttons\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setSize(300, 150)" }, { "code": null, "e": 46963, "s": 46877, "text": "The JPanel object is declared having a vertical BoxLayout. Add it in top-level frame." }, { "code": null, "e": 47049, "s": 46963, "text": "panel = JPanel()\npanel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))\nframe.add(panel)" }, { "code": null, "e": 47227, "s": 47049, "text": "In this panel, two more panels top and bottom are added to it. Each of them have two JButton objects added to them horizontally with a space holder of 25 pixels separating them." }, { "code": null, "e": 47449, "s": 47227, "text": "###top panel\ntop = JPanel()\ntop.setLayout(BoxLayout(top, BoxLayout.X_AXIS))\nb1 = JButton(\"OK\")\nb2 = JButton(\"Close\")\ntop.add(Box.createVerticalGlue())\ntop.add(b1)\ntop.add(Box.createRigidArea(Dimension(25, 0)))\ntop.add(b2)" }, { "code": null, "e": 47493, "s": 47449, "text": "Similarly, the bottom panel is constructed." }, { "code": null, "e": 47740, "s": 47493, "text": "###bottom panel\nbottom = JPanel()\nbottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS))\nb3 = JButton(\"Open\")\nb4 = JButton(\"Save\")\nbottom.add(b3)\nbottom.add(Box.createRigidArea(Dimension(25, 0)))\nbottom.add(b4)\nbottom.add(Box.createVerticalGlue())" }, { "code": null, "e": 47938, "s": 47740, "text": "Note that the createRigidArea() function is used to create a space of 25 pixels between two buttons. Also the createVerticalGlue() function occupies the leading or the trailing space in the layout." }, { "code": null, "e": 48071, "s": 47938, "text": "To start with, add the top and bottom panels and set the visibility property of the frame to true. The complete code is as follows −" }, { "code": null, "e": 48899, "s": 48071, "text": "from java.awt import Dimension\nfrom javax.swing import JButton, JFrame,JPanel,BoxLayout,Box\n\nframe = JFrame()\nframe.setTitle(\"Buttons\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setSize(300, 150)\n\npanel = JPanel()\npanel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))\nframe.add(panel)\n\n###top panel\ntop = JPanel()\ntop.setLayout(BoxLayout(top, BoxLayout.X_AXIS))\nb1 = JButton(\"OK\")\nb2 = JButton(\"Close\")\ntop.add(Box.createVerticalGlue())\ntop.add(b1)\ntop.add(Box.createRigidArea(Dimension(25, 0)))\ntop.add(b2)\n\n###bottom panel\nbottom = JPanel()\nbottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS))\nb3 = JButton(\"Open\")\nb4 = JButton(\"Save\")\nbottom.add(b3)\nbottom.add(Box.createRigidArea(Dimension(25, 0)))\nbottom.add(b4)\nbottom.add(Box.createVerticalGlue())\n\npanel.add(bottom)\npanel.add(top)\nframe.setVisible(True)" }, { "code": null, "e": 48950, "s": 48899, "text": "The above code will generate the following output." }, { "code": null, "e": 49134, "s": 48950, "text": "The GroupLayout manager groups the components in a hierarchical manner. The grouping is done by two classes, SequentialGroup and ParallelGroup, both implement Group interface in Java." }, { "code": null, "e": 49334, "s": 49134, "text": "The layout procedure is divided in two steps. In one-step, components are placed along with the horizontal axis, and in second along vertical axis. Each component must be defined twice in the layout." }, { "code": null, "e": 49676, "s": 49334, "text": "There are two types of arrangements, sequential and parallel. In both, we can arrange components sequentially or in parallel. In horizontal arrangement, row is called sequential group and column is called parallel group. On the other hand, in parallel arrangement, row of element is a parallel group and a column, which is called sequential." }, { "code": null, "e": 49869, "s": 49676, "text": "In following example, five buttons are arranged in such a way that three each appear in row and column. To start with, Add a Jpanel object in a JFrame window and set its layout as Grouplayout." }, { "code": null, "e": 50011, "s": 49869, "text": "frame = JFrame()\npanel = JPanel()\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nlayout = GroupLayout(panel)\npanel.setLayout(layout)" }, { "code": null, "e": 50048, "s": 50011, "text": "Then construct the JButton objects −" }, { "code": null, "e": 50163, "s": 50048, "text": "buttonD = JButton(\"D\")\nbuttonR = JButton(\"R\")\nbuttonY = JButton(\"Y\")\nbuttonO = JButton(\"O\")\nbuttonT = JButton(\"T\")" }, { "code": null, "e": 50356, "s": 50163, "text": "Next, we create a SequentialGroup named LeftToRight to which buttonD and buttonY are added. In between them, a ParallelGroup ColumnMiddle (with other three buttons added vertically) is placed." }, { "code": null, "e": 50653, "s": 50356, "text": "leftToRight = layout.createSequentialGroup()\nleftToRight.addComponent(buttonD)\ncolumnMiddle = layout.createParallelGroup()\ncolumnMiddle.addComponent(buttonR)\ncolumnMiddle.addComponent(buttonO)\ncolumnMiddle.addComponent(buttonT)\nleftToRight.addGroup(columnMiddle)\nleftToRight.addComponent(buttonY)" }, { "code": null, "e": 50805, "s": 50653, "text": "Now comes the definition of vertical SequentialGroup called TopToBottom. Add a ParallelGroup row of three buttons and then rest two buttons vertically." }, { "code": null, "e": 51072, "s": 50805, "text": "topToBottom = layout.createSequentialGroup()\nrowTop = layout.createParallelGroup()\nrowTop.addComponent(buttonD)\nrowTop.addComponent(buttonR)\nrowTop.addComponent(buttonY)\ntopToBottom.addGroup(rowTop)\ntopToBottom.addComponent(buttonO)\ntopToBottom.addComponent(buttonT)" }, { "code": null, "e": 51206, "s": 51072, "text": "Finally, set LeftToRight group horizontally and TopToBottom group vertically to the layout object. The complete code is given below −" }, { "code": null, "e": 52218, "s": 51206, "text": "from javax.swing import JButton, JFrame,JPanel,GroupLayout\n\nframe = JFrame()\npanel = JPanel()\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nlayout = GroupLayout(panel)\npanel.setLayout(layout)\n\nbuttonD = JButton(\"D\")\nbuttonR = JButton(\"R\")\nbuttonY = JButton(\"Y\")\nbuttonO = JButton(\"O\")\nbuttonT = JButton(\"T\")\n\nleftToRight = layout.createSequentialGroup()\nleftToRight.addComponent(buttonD)\ncolumnMiddle = layout.createParallelGroup()\ncolumnMiddle.addComponent(buttonR)\ncolumnMiddle.addComponent(buttonO)\ncolumnMiddle.addComponent(buttonT)\nleftToRight.addGroup(columnMiddle)\nleftToRight.addComponent(buttonY)\n\ntopToBottom = layout.createSequentialGroup()\nrowTop = layout.createParallelGroup()\nrowTop.addComponent(buttonD)\nrowTop.addComponent(buttonR)\nrowTop.addComponent(buttonY)\ntopToBottom.addGroup(rowTop)\ntopToBottom.addComponent(buttonO)\ntopToBottom.addComponent(buttonT)\n\nlayout.setHorizontalGroup(leftToRight)\nlayout.setVerticalGroup(topToBottom)\n\nframe.add(panel)\nframe.pack()\nframe.setVisible(True)" }, { "code": null, "e": 52263, "s": 52218, "text": "The output of the above code is as follows −" }, { "code": null, "e": 52692, "s": 52263, "text": "Event handling in Java swing requires that the control (like JButton or JList etc.) should be registered with the respective event listener. The event listener interface or corresponding Adapter class needs to be either implemented or subclassed with its event handling method overridden. In Jython, the event handling is very simple. We can pass any function as property of event handling function corresponding to the control." }, { "code": null, "e": 52747, "s": 52692, "text": "Let us first see how a click event is handled in Java." }, { "code": null, "e": 52882, "s": 52747, "text": "To begin with, we have to import the java.awt.event package. Next, the class extending JFrame must implement ActionListener interface." }, { "code": null, "e": 52945, "s": 52882, "text": "public class btnclick extends JFrame implements ActionListener" }, { "code": null, "e": 53101, "s": 52945, "text": "Then, we have to declare the JButton object, add it to the ContentPane of frame and then register it with ActionListener by the addActionListener() method." }, { "code": null, "e": 53201, "s": 53101, "text": "JButton b1 = new JButton(\"Click here\");\n getContentPane().add(b1);\n b1.addActionListener(this);" }, { "code": null, "e": 53313, "s": 53201, "text": "Now, the actionPerformed() method of the ActionListener interface must be overridden to handle the ActionEvent." }, { "code": null, "e": 53345, "s": 53313, "text": "Following is entire Java code −" }, { "code": null, "e": 53882, "s": 53345, "text": "import java.awt.event.*;\nimport javax.swing.*;\npublic class btnclick extends JFrame implements ActionListener {\n btnclick() {\n JButton b1 = new JButton(\"Click here\");\n getContentPane().add(b1);\n b1.addActionListener(this);\n }\n \n public void actionPerformed(ActionEvent e) {\n System.out.println(\"Clicked\");\n }\n \n public static void main(String args[]) {\n btnclick b = new btnclick();\n b.setSize(300,200);\n b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n b.setVisible(true);\n }\n}" }, { "code": null, "e": 53946, "s": 53882, "text": "Now, we will write the Jython code equivalent to the same code." }, { "code": null, "e": 54112, "s": 53946, "text": "To start with, we do not need to import the ActionEvent or the ActionListener, since Jython’s dynamic typing allows us to avoid mentioning these classes in our code." }, { "code": null, "e": 54312, "s": 54112, "text": "Secondly, there is no need to implement or subclass ActionListener. Instead, any user defined function is straightaway provided to the JButton constructor as a value of actionPerformed bean property." }, { "code": null, "e": 54373, "s": 54312, "text": "button = JButton('Click here!', actionPerformed = clickhere)" }, { "code": null, "e": 54484, "s": 54373, "text": "The clickhere() function is defined as a regular Jython function, which handles the click event on the button." }, { "code": null, "e": 54524, "s": 54484, "text": "def change_text(event):\nprint clicked!'" }, { "code": null, "e": 54560, "s": 54524, "text": "Here is the Jython equivalent code." }, { "code": null, "e": 54860, "s": 54560, "text": "from javax.swing import JFrame, JButton\n\nframe = JFrame(\"Hello\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(300,200)\n\ndef clickhere(event):\n print \"clicked\"\n\nbtn = JButton(\"Add\", actionPerformed = clickhere)\nframe.add(btn)\n\nframe.setVisible(True)" }, { "code": null, "e": 54989, "s": 54860, "text": "The Output of Java and Jython code is identical. When the button is clicked, it will print the ‘clicked’ message on the console." }, { "code": null, "e": 55174, "s": 54989, "text": "In the following Jython code, two JTextField objects are provided on the JFrame window to enter marks in ‘phy’ and ‘maths’. The JButton object executes the add() function when clicked." }, { "code": null, "e": 55218, "s": 55174, "text": "btn = JButton(\"Add\", actionPerformed = add)" }, { "code": null, "e": 55436, "s": 55218, "text": "The add() function reads the contents of two text fields by the getText() method and parses them to integers, so that, addition can be performed. The result is then put in the third text field by the setText() method." }, { "code": null, "e": 55542, "s": 55436, "text": "def add(event):\n print \"add\"\n ttl = int(txt1.getText())+int(txt2.getText())\n txt3.setText(str(ttl))" }, { "code": null, "e": 55577, "s": 55542, "text": "The complete code is given below −" }, { "code": null, "e": 56442, "s": 55577, "text": "from javax.swing import JFrame, JLabel, JButton, JTextField\nfrom java.awt import Dimension\n\nframe = JFrame(\"Hello\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(300,200)\nframe.setLayout(None)\n\ndef add(event):\n print \"add\"\n ttl = int(txt1.getText())+int(txt2.getText())\n txt3.setText(str(ttl))\n\nlbl1 = JLabel(\"Phy\")\nlbl1.setBounds(60,20,40,20)\ntxt1 = JTextField(10)\ntxt1.setBounds(120,20,60,20)\nlbl2 = JLabel(\"Maths\")\nlbl2.setBounds(60,50,40,20)\ntxt2 = JTextField(10)\ntxt2.setBounds(120, 50, 60,20)\nbtn = JButton(\"Add\", actionPerformed = add)\nbtn.setBounds(60,80,60,20)\nlbl3 = JLabel(\"Total\")\nlbl3.setBounds(60,110,40,20)\ntxt3 = JTextField(10)\ntxt3.setBounds(120, 110, 60,20)\n\nframe.add(lbl1)\nframe.add(txt1)\nframe.add(lbl2)\nframe.add(txt2)\nframe.add(btn)\nframe.add(lbl3)\nframe.add(txt3)\nframe.setVisible(True)" }, { "code": null, "e": 56633, "s": 56442, "text": "When the above code is executed from the command prompt, the following window appears. Enter marks for ‘Phy’, Maths’, and click on the ‘Add’ button. The result will be displayed accordingly." }, { "code": null, "e": 56849, "s": 56633, "text": "The JRadioButton class is defined in the javax.swing package. It creates a selectable toggle button with on or off states. If multiple radio buttons are added in a ButtonGroup, their selection is mutually exclusive." }, { "code": null, "e": 57190, "s": 56849, "text": "In the following example, two objects of the JRadioButton class and two JLabels are added to a Jpanel container in a vertical BoxLayout. In the constructor of the JRadioButton objects, the OnCheck() function is set as the value of the actionPerformed property. This function is executed when the radio button is clicked to change its state." }, { "code": null, "e": 57306, "s": 57190, "text": "rb1 = JRadioButton(\"Male\", True,actionPerformed = OnCheck)\nrb2 = JRadioButton(\"Female\", actionPerformed = OnCheck)\n" }, { "code": null, "e": 57445, "s": 57306, "text": "Note that the default state of Radio Button is false (not selected). The button rb1 is created with its starting state as True (selected)." }, { "code": null, "e": 57596, "s": 57445, "text": "The two radio buttons are added to a radio ButtonGroup to make them mutually exclusive, so that if one is selected, other is deselected automatically." }, { "code": null, "e": 57642, "s": 57596, "text": "grp = ButtonGroup()\ngrp.add(rb1)\ngrp.add(rb2)" }, { "code": null, "e": 57807, "s": 57642, "text": "These two radio buttons along with two labels are added to a panel object in the vertical layout with a separator area of 25 pixels in heights between rb2 and lbl2." }, { "code": null, "e": 58022, "s": 57807, "text": "panel = JPanel()\npanel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))\n\npanel.add(Box.createVerticalGlue())\npanel.add(lbl)\npanel.add(rb1)\npanel.add(rb2)\npanel.add(Box.createRigidArea(Dimension(0,25)))\npanel.add(lbl1)" }, { "code": null, "e": 58124, "s": 58022, "text": "This panel is added to a top-level JFrame object, whose visible property is set to ‘True’ in the end." }, { "code": null, "e": 59295, "s": 58124, "text": "frame = JFrame(\"JRadioButton Example\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(250,200)\nframe.setVisible(True)\nThe complete code of radio.py is given below:\nfrom javax.swing import JFrame, JPanel, JLabel, BoxLayout, Box\n\nfrom java.awt import Dimension\nfrom javax.swing import JRadioButton,ButtonGroup\nframe = JFrame(\"JRadioButton Example\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(250,200)\npanel = JPanel()\npanel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))\nframe.add(panel)\n\ndef OnCheck(event):\n lbl1.text = \"\"\n if rb1.isSelected():\n lbl1.text = lbl1.text+\"Gender selection : Male\"\n else:\n lbl1.text = lbl1.text+\"Gender selection : Female \"\n lbl = JLabel(\"Select Gender\")\n\nrb1 = JRadioButton(\"Male\", True,actionPerformed = OnCheck)\nrb2 = JRadioButton(\"Female\", actionPerformed = OnCheck)\ngrp = ButtonGroup()\ngrp.add(rb1)\ngrp.add(rb2)\n\nlbl1 = JLabel(\"Gender Selection :\")\n\npanel.add(Box.createVerticalGlue())\npanel.add(lbl)\npanel.add(rb1)\npanel.add(rb2)\npanel.add(Box.createRigidArea(Dimension(0,25)))\npanel.add(lbl1)\n\nframe.setVisible(True)" }, { "code": null, "e": 59416, "s": 59295, "text": "Run the above Jython script and change the radio button selection. The selection will appear in the label at the bottom." }, { "code": null, "e": 59640, "s": 59416, "text": "Like the JRadioButton, JCheckBox object is also a selectable button with a rectangular checkable box besides its caption. This is generally used to provide user opportunity to select multiple options from the list of items." }, { "code": null, "e": 59841, "s": 59640, "text": "In the following example, two check boxes and a label from swing package are added to a JPanel in vertical BoxLayout. The label at bottom displays the instantaneous selection state of two check boxes." }, { "code": null, "e": 59958, "s": 59841, "text": "Both checkboxes are declared with the constructor having the actionPerformed property set to the OnCheck() function." }, { "code": null, "e": 60066, "s": 59958, "text": "box1 = JCheckBox(\"Check1\", actionPerformed = OnCheck)\nbox2 = JCheckBox(\"Check2\", actionPerformed = OnCheck)" }, { "code": null, "e": 60195, "s": 60066, "text": "The OnCheck() function verifies selection state of each check box and displays corresponding message on the label at the bottom." }, { "code": null, "e": 60495, "s": 60195, "text": "def OnCheck(event):\n lbl1.text = \"\"\n if box1.isSelected():\n lbl1.text = lbl1.text + \"box1 selected \"\n else:\n lbl1.text = lbl1.text + \"box1 not selected \"\n if box2.isSelected():\n lbl1.text = lbl1.text + \"box2 selected\"\n else:\n lbl1.text = lbl1.text + \"box2 not selected\"" }, { "code": null, "e": 60611, "s": 60495, "text": "These boxes and a JLabel object are added to a JPanel with a spaceholder of 50 pixels in height added between them." }, { "code": null, "e": 60812, "s": 60611, "text": "panel = JPanel()\npanel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))\npanel.add(Box.createVerticalGlue())\npanel.add(box1)\npanel.add(box2)\npanel.add(Box.createRigidArea(Dimension(0,50)))\npanel.add(lbl1)" }, { "code": null, "e": 60918, "s": 60812, "text": "The panel itself is added to a top-level JFrame window, whose visible property is set to true in the end." }, { "code": null, "e": 61098, "s": 60918, "text": "frame = JFrame(\"JCheckBox Example\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(250,150)\nframe.add(panel)\n\nframe.setVisible(True)" }, { "code": null, "e": 61239, "s": 61098, "text": "Run the above code and experiment with the selection of check boxes. The instantaneous state of both check boxes is displayed at the bottom." }, { "code": null, "e": 61594, "s": 61239, "text": "The JList control in the swing package provides the user with a scrollable list of items to choose. The JComboBox provides a drop down list of items. In Java, the selection event is processed by implementing the valueChanged() method in the ListSelectionListener. In Jython, an event handler is assigned to the valueChanged property of the JList object." }, { "code": null, "e": 61811, "s": 61594, "text": "In the following example, a JList object and a label are added to a JFrame in the BorderLayout. The JList is populated with a collection of items in a tuple. Its valueChanged property is set to listSelect() function." }, { "code": null, "e": 61943, "s": 61811, "text": "lang = (\"C\", \"C++\", \"Java\", \"Python\", \"Perl\", \"C#\", \"VB\", \"PHP\", \"Javascript\", \"Ruby\")\nlst = JList(lang, valueChanged = listSelect)" }, { "code": null, "e": 62110, "s": 61943, "text": "The event handler function obtains the index of the selected item and fetches the corresponding item from the JList object to be displayed on the label at the bottom." }, { "code": null, "e": 62199, "s": 62110, "text": "def listSelect(event):\n index = lst.selectedIndex\n lbl1.text = \"Hello\" + lang[index]" }, { "code": null, "e": 62271, "s": 62199, "text": "The JList and JLabel object are added to the JFrame using BorderLayout." }, { "code": null, "e": 62304, "s": 62271, "text": "The entire code is given below −" }, { "code": null, "e": 62932, "s": 62304, "text": "from javax.swing import JFrame, JPanel, JLabel, JList\nfrom java.awt import BorderLayout\n\nframe = JFrame(\"JList Example\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(300,250)\n\nframe.setLayout(BorderLayout())\n\ndef listSelect(event):\n index = lst.selectedIndex\n lbl1.text = \"Hello\" + lang[index]\n\nlang = (\"C\", \"C++\", \"Java\", \"Python\", \"Perl\", \"C#\", \"VB\", \"PHP\", \"Javascript\", \"Ruby\")\nlst = JList(lang, valueChanged = listSelect)\nlbl1 = JLabel(\"box1 not selected box2 not selected\")\nframe.add(lst, BorderLayout.NORTH)\nframe.add(lbl1, BorderLayout.SOUTH)\n\nframe.setVisible(True)" }, { "code": null, "e": 62980, "s": 62932, "text": "The output of the following code is as follows." }, { "code": null, "e": 63261, "s": 62980, "text": "Most of the GUI based applications have a Menu bar at the top. It is found just below the title bar of the top-level window. The javax.swing package has elaborate facility to build an efficient menu system. It is constructed with the help of JMenuBar, JMenu and JMenuItem classes." }, { "code": null, "e": 63479, "s": 63261, "text": "In following example, a menu bar is provided in the top-level window. A File menu consisting of three menu item buttons is added to the menu bar. Let us now prepare a JFrame object with the layout set to BorderLayout." }, { "code": null, "e": 63649, "s": 63479, "text": "frame = JFrame(\"JMenuBar example\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(400,300)\nframe.setLayout(BorderLayout())" }, { "code": null, "e": 63714, "s": 63649, "text": "Now, a JMenuBar object is activated by the SetJMenuBar() method." }, { "code": null, "e": 63754, "s": 63714, "text": "bar = JMenuBar()\nframe.setJMenuBar(bar)" }, { "code": null, "e": 64007, "s": 63754, "text": "Next, a JMenu object having ‘File’ caption is declared. Three JMenuItem buttons are added to the File menu. When any of the menu items are clicked, the ActionEvent handler OnClick() function is executed. It is defined with the actionPerformed property." }, { "code": null, "e": 64261, "s": 64007, "text": "file = JMenu(\"File\")\nnewfile = JMenuItem(\"New\",actionPerformed = OnClick)\nopenfile = JMenuItem(\"Open\",actionPerformed = OnClick)\nsavefile = JMenuItem(\"Save\",actionPerformed = OnClick)\nfile.add(newfile)\nfile.add(openfile)\nfile.add(savefile)\nbar.add(file)" }, { "code": null, "e": 64428, "s": 64261, "text": "The OnClick() event handler retrieves the name of the JMenuItem button by the gwtActionCommand() function and displays it in the text box at the bottom of the window." }, { "code": null, "e": 64487, "s": 64428, "text": "def OnClick(event):\n txt.text = event.getActionCommand()" }, { "code": null, "e": 64605, "s": 64487, "text": "The File menu object is added to menu bar. Finally, a JTextField control is added at the bottom of the JFrame object." }, { "code": null, "e": 64661, "s": 64605, "text": "txt = JTextField(10)\nframe.add(txt, BorderLayout.SOUTH)" }, { "code": null, "e": 64705, "s": 64661, "text": "The entire code of menu.py is given below −" }, { "code": null, "e": 65418, "s": 64705, "text": "from javax.swing import JFrame, JMenuBar, JMenu, JMenuItem, JTextField\nfrom java.awt import BorderLayout\n\nframe = JFrame(\"JMenuBar example\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(400,300)\nframe.setLayout(BorderLayout())\n\ndef OnClick(event):\n txt.text = event.getActionCommand()\n\nbar = JMenuBar()\nframe.setJMenuBar(bar)\n\nfile = JMenu(\"File\")\nnewfile = JMenuItem(\"New\",actionPerformed = OnClick)\nopenfile = JMenuItem(\"Open\",actionPerformed = OnClick)\nsavefile = JMenuItem(\"Save\",actionPerformed = OnClick)\nfile.add(newfile)\nfile.add(openfile)\nfile.add(savefile)\nbar.add(file)\n\ntxt = JTextField(10)\nframe.add(txt, BorderLayout.SOUTH)\n\nframe.setVisible(True)" }, { "code": null, "e": 65650, "s": 65418, "text": "When the above script is executed using the Jython interpreter, a window with the File menu appears. Click on it and its three menu items will drop down. If any button is clicked, its name will be displayed in the text box control." }, { "code": null, "e": 65963, "s": 65650, "text": "A Dialog object is a window that appears on top of the base window with which the user interacts. In this chapter, we shall see the preconfigured dialogs defined in the swing library. They are MessageDialog, ConfirmDialog and InputDialog. They are available because of the static method of the JOptionPane class." }, { "code": null, "e": 66108, "s": 65963, "text": "In the following example, the File menu has three JMenu items corresponding to the above three dialogs; each executes the OnClick event handler." }, { "code": null, "e": 66350, "s": 66108, "text": "file = JMenu(\"File\")\nmsgbtn = JMenuItem(\"Message\",actionPerformed = OnClick)\nconbtn = JMenuItem(\"Confirm\",actionPerformed = OnClick)\ninputbtn = JMenuItem(\"Input\",actionPerformed = OnClick)\nfile.add(msgbtn)\nfile.add(conbtn)\nfile.add(inputbtn)" }, { "code": null, "e": 66474, "s": 66350, "text": "The OnClick() handler function retrieves the caption of Menu Item button and invokes the respective showXXXDialog() method." }, { "code": null, "e": 67037, "s": 66474, "text": "def OnClick(event):\n str = event.getActionCommand()\n if str == 'Message':\n JOptionPane.showMessageDialog(frame,\"this is a sample message dialog\")\n if str == \"Input\":\n x = JOptionPane.showInputDialog(frame,\"Enter your name\")\n txt.setText(x)\n if str == \"Confirm\":\n s = JOptionPane.showConfirmDialog (frame, \"Do you want to continue?\")\n if s == JOptionPane.YES_OPTION:\n txt.setText(\"YES\")\n if s == JOptionPane.NO_OPTION:\n txt.setText(\"NO\")\n if s == JOptionPane.CANCEL_OPTION:\n txt.setText(\"CANCEL\")" }, { "code": null, "e": 67377, "s": 67037, "text": "If the message option from menu is chosen, a message pops up. If Input option is clicked, a dialog asking for the input pops up. The input text is then displayed in the text box in the JFrame window. If the Confirm option is selected, a dialog with three buttons, YES, NO and CANCEL comes up. The user’s choice is recorded in the text box." }, { "code": null, "e": 67410, "s": 67377, "text": "The entire code is given below −" }, { "code": null, "e": 68660, "s": 67410, "text": "from javax.swing import JFrame, JMenuBar, JMenu, JMenuItem, JTextField\nfrom java.awt import BorderLayout\nfrom javax.swing import JOptionPane\nframe = JFrame(\"Dialog example\")\nframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\nframe.setLocation(100,100)\nframe.setSize(400,300)\nframe.setLayout(BorderLayout())\n\ndef OnClick(event):\n str = event.getActionCommand()\n if str == 'Message':\n JOptionPane.showMessageDialog(frame,\"this is a sample message dialog\")\n if str == \"Input\":\n x = JOptionPane.showInputDialog(frame,\"Enter your name\")\n txt.setText(x)\n if str == \"Confirm\":\n s = JOptionPane.showConfirmDialog (frame, \"Do you want to continue?\")\n if s == JOptionPane.YES_OPTION:\n txt.setText(\"YES\")\n if s == JOptionPane.NO_OPTION:\n txt.setText(\"NO\")\n if s == JOptionPane.CANCEL_OPTION:\n txt.setText(\"CANCEL\")\n\nbar = JMenuBar()\nframe.setJMenuBar(bar)\n\nfile = JMenu(\"File\")\nmsgbtn = JMenuItem(\"Message\",actionPerformed = OnClick)\nconbtn = JMenuItem(\"Confirm\",actionPerformed = OnClick)\ninputbtn = JMenuItem(\"Input\",actionPerformed = OnClick)\nfile.add(msgbtn)\nfile.add(conbtn)\nfile.add(inputbtn)\nbar.add(file)\ntxt = JTextField(10)\nframe.add(txt, BorderLayout.SOUTH)\nframe.setVisible(True)" }, { "code": null, "e": 68762, "s": 68660, "text": "When the above script is executed, the following window is displayed with three options in the menu −" }, { "code": null, "e": 68769, "s": 68762, "text": " Print" }, { "code": null, "e": 68780, "s": 68769, "text": " Add Notes" } ]
MySQL query to skip the duplicate and select only one from the duplicated values
The syntax is as follows to skip the duplicate value and select only one from the duplicated values − select min(yourColumnName1),yourColumnName2 from yourTableName group by yourColumnName2; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table doNotSelectDuplicateValuesDemo -> ( -> User_Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> User_Name varchar(20) -> ); Query OK, 0 rows affected (0.78 sec) Now you can insert some records in the table using insert command. The query is as follows − mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('John'); Query OK, 1 row affected (0.15 sec) mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Carol'); Query OK, 1 row affected (0.09 sec) mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Carol'); Query OK, 1 row affected (0.17 sec) mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Carol'); Query OK, 1 row affected (0.08 sec) mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Sam'); Query OK, 1 row affected (0.28 sec) mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Mike'); Query OK, 1 row affected (0.19 sec) mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Bob'); Query OK, 1 row affected (0.16 sec) mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('David'); Query OK, 1 row affected (0.21 sec) mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Maxwell'); Query OK, 1 row affected (0.13 sec) mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Bob'); Query OK, 1 row affected (0.11 sec) mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Ramit'); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from doNotSelectDuplicateValuesDemo; Here is the output − +---------+-----------+ | User_Id | User_Name | +---------+-----------+ | 1 | John | | 2 | Carol | | 3 | Carol | | 4 | Carol | | 5 | Sam | | 6 | Mike | | 7 | Bob | | 8 | David | | 9 | Maxwell | | 10 | Bob | | 11 | Ramit | +---------+-----------+ 11 rows in set (0.00 sec) Here is the query to skip the duplicate value and select only one from the duplicated values − mysql> select min(User_Id),User_Name from doNotSelectDuplicateValuesDemo group by User_Name; Here is the output − +--------------+-----------+ | min(User_Id) | User_Name | +--------------+-----------+ | 1 | John | | 2 | Carol | | 5 | Sam | | 6 | Mike | | 7 | Bob | | 8 | David | | 9 | Maxwell | | 11 | Ramit | +--------------+-----------+ 8 rows in set (0.07 sec)
[ { "code": null, "e": 1164, "s": 1062, "text": "The syntax is as follows to skip the duplicate value and select only one from the duplicated values −" }, { "code": null, "e": 1253, "s": 1164, "text": "select min(yourColumnName1),yourColumnName2 from yourTableName group by\nyourColumnName2;" }, { "code": null, "e": 1352, "s": 1253, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1540, "s": 1352, "text": "mysql> create table doNotSelectDuplicateValuesDemo\n -> (\n -> User_Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> User_Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.78 sec)" }, { "code": null, "e": 1633, "s": 1540, "text": "Now you can insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2881, "s": 1633, "text": "mysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('John');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Carol');\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Carol');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Carol');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Sam');\nQuery OK, 1 row affected (0.28 sec)\nmysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Mike');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Bob');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('David');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Maxwell');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Bob');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into doNotSelectDuplicateValuesDemo(User_Name) values('Ramit');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2966, "s": 2881, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 3018, "s": 2966, "text": "mysql> select *from doNotSelectDuplicateValuesDemo;" }, { "code": null, "e": 3039, "s": 3018, "text": "Here is the output −" }, { "code": null, "e": 3425, "s": 3039, "text": "+---------+-----------+\n| User_Id | User_Name |\n+---------+-----------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Carol |\n| 4 | Carol |\n| 5 | Sam |\n| 6 | Mike |\n| 7 | Bob |\n| 8 | David |\n| 9 | Maxwell |\n| 10 | Bob |\n| 11 | Ramit |\n+---------+-----------+\n11 rows in set (0.00 sec)" }, { "code": null, "e": 3520, "s": 3425, "text": "Here is the query to skip the duplicate value and select only one from the duplicated values −" }, { "code": null, "e": 3613, "s": 3520, "text": "mysql> select min(User_Id),User_Name from doNotSelectDuplicateValuesDemo group by\nUser_Name;" }, { "code": null, "e": 3634, "s": 3613, "text": "Here is the output −" }, { "code": null, "e": 4007, "s": 3634, "text": "+--------------+-----------+\n| min(User_Id) | User_Name |\n+--------------+-----------+\n| 1 | John |\n| 2 | Carol |\n| 5 | Sam |\n| 6 | Mike |\n| 7 | Bob |\n| 8 | David |\n| 9 | Maxwell |\n| 11 | Ramit |\n+--------------+-----------+\n8 rows in set (0.07 sec)" } ]
How to delete lines from a Python tkinter canvas?
The Canvas widget has many use-cases in GUI application development. We can use a Canvas widget to draw shapes, creating graphics, images, and many other things. To draw a line in Canvas, we can use create_line(x,y,x1,y1, **options) method. In Tkinter, we can draw two types of lines − simple and dashed. If you want your application to delete the created lines, then you can use the delete() method. Let us have a look at the example where we will delete the line defined in the Canvas widget. # Import the required libraries from tkinter import * # Create an instance of tkinter frame or window win=Tk() # Set the size of the tkinter window win.geometry("700x350") # Define a function to delete the shape def on_click(): canvas.delete(line) # Create a canvas widget canvas=Canvas(win, width=500, height=300) canvas.pack() # Add a line in canvas widget line=canvas.create_line(100,200,200,35, fill="red", width=10) # Create a button to delete the button Button(win, text="Delete Shape", command=on_click).pack() win.mainloop() If we run the above code, it will display a window with a button and a shape in the canvas. Now, click the "Delete Shape" button to delete the displayed line from the canvas.
[ { "code": null, "e": 1367, "s": 1062, "text": "The Canvas widget has many use-cases in GUI application development. We can use a Canvas widget to draw shapes, creating graphics, images, and many other things. To draw a line in Canvas, we can use create_line(x,y,x1,y1, **options) method. In Tkinter, we can draw two types of lines − simple and dashed." }, { "code": null, "e": 1463, "s": 1367, "text": "If you want your application to delete the created lines, then you can use the delete() method." }, { "code": null, "e": 1557, "s": 1463, "text": "Let us have a look at the example where we will delete the line defined in the Canvas widget." }, { "code": null, "e": 2100, "s": 1557, "text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Define a function to delete the shape\ndef on_click():\n canvas.delete(line)\n\n# Create a canvas widget\ncanvas=Canvas(win, width=500, height=300)\ncanvas.pack()\n\n# Add a line in canvas widget\nline=canvas.create_line(100,200,200,35, fill=\"red\", width=10)\n\n# Create a button to delete the button\nButton(win, text=\"Delete Shape\", command=on_click).pack()\n\nwin.mainloop()" }, { "code": null, "e": 2192, "s": 2100, "text": "If we run the above code, it will display a window with a button and a shape in the canvas." }, { "code": null, "e": 2275, "s": 2192, "text": "Now, click the \"Delete Shape\" button to delete the displayed line from the canvas." } ]
The Ubiquitous Binary Search | Set 1
14 Jun, 2022 We all aware of binary search algorithm. Binary search is easiest difficult algorithm to get it right. I present some interesting problems that I collected on binary search. There were some requests on binary search. I request you to honor the code, “I sincerely attempt to solve the problem and ensure there are no corner cases”. After reading each problem minimize the browser and try solving it. Problem Statement: Given a sorted array of N distinct elements. Find a key in the array using least number of comparisons. (Do you think binary search is optimal to search a key in sorted array?) Without much theory, here is typical binary search algorithm. C Java C# Javascript // Returns location of key, or -1 if not foundint BinarySearch(int A[], int l, int r, int key){ int m; while( l <= r ) { m = l + (r-l)/2; if( A[m] == key ) // first comparison return m; if( A[m] < key ) // second comparison l = m + 1; else r = m - 1; } return -1;} // Java code to implement the approachimport java.util.*; class GFG { // Returns location of key, or -1 if not foundstatic int BinarySearch(int A[], int l, int r, int key){ int m; while( l < r ) { m = l + (r-l)/2; if( A[m] == key ) // first comparison return m; if( A[m] < key ) // second comparison l = m + 1; else r = m - 1; } return -1;}} // This code is contributed by sanjoy_62. // C# program to implement// the above approachusing System; class GFG{ // Returns location of key, or -1 if not foundstatic int BinarySearch(int[] A, int l, int r, int key){ int m; while( l < r ) { m = l + (r-l)/2; if( A[m] == key ) // first comparison return m; if( A[m] < key ) // second comparison l = m + 1; else r = m - 1; } return -1;}} // This code is contributed by code_hunt. <script>// Javascript code to implement the approach // Returns location of key, or -1 if not foundfunction BinarySearch(A, l, r, key) { let m; while (l < r) { m = l + (r - l) / 2; if (A[m] == key) // first comparison return m; if (A[m] < key) // second comparison l = m + 1; else r = m - 1; } return -1;} // This code is contributed by gfgking</script> Theoretically we need log N + 1 comparisons in worst case. If we observe, we are using two comparisons per iteration except during final successful match, if any. In practice, comparison would be costly operation, it won’t be just primitive type comparison. It is more economical to minimize comparisons as that of theoretical limit. See below figure on initialize of indices in the next implementation. The following implementation uses fewer number of comparisons. C // Invariant: A[l] <= key and A[r] > key// Boundary: |r - l| = 1// Input: A[l .... r-1]int BinarySearch(int A[], int l, int r, int key){ int m; while( r - l > 1 ) { m = l + (r-l)/2; if( A[m] <= key ) l = m; else r = m; } if( A[l] == key ) return l; if( A[r] == key ) return r; else return -1;} In the while loop we are depending only on one comparison. The search space converges to place l and r point two different consecutive elements. We need one more comparison to trace search status. You can see sample test case http://ideone.com/76bad0. (C++11 code) Problem Statement: Given an array of N distinct integers, find floor value of input ‘key’. Say, A = {-1, 2, 3, 5, 6, 8, 9, 10} and key = 7, we should return 6 as outcome. We can use the above optimized implementation to find floor value of key. We keep moving the left pointer to right most as long as the invariant holds. Eventually left pointer points an element less than or equal to key (by definition floor value). The following are possible corner cases, —> If all elements in the array are smaller than key, left pointer moves till last element. —> If all elements in the array are greater than key, it is an error condition. —> If all elements in the array equal and <= key, it is worst case input to our implementation. Here is implementation, C // largest value <= key// Invariant: A[l] <= key and A[r] > key// Boundary: |r - l| = 1// Input: A[l .... r-1]// Precondition: A[l] <= key <= A[r]int Floor(int A[], int l, int r, int key){ int m; while( r - l > 1 ) { m = l + (r - l)/2; if( A[m] <= key ) l = m; else r = m; } return A[l];} // Initial callint Floor(int A[], int size, int key){ // Add error checking if key < A[0] if( key < A[0] ) return -1; // Observe boundaries return Floor(A, 0, size, key);} You can see some test cases http://ideone.com/z0Kx4a. Problem Statement: Given a sorted array with possible duplicate elements. Find number of occurrences of input ‘key’ in log N time. The idea here is finding left and right most occurrences of key in the array using binary search. We can modify floor function to trace right most occurrence and left most occurrence. Here is implementation, C // Input: Indices Range [l ... r)// Invariant: A[l] <= key and A[r] > keyint GetRightPosition(int A[], int l, int r, int key){ int m; while( r - l > 1 ) { m = l + (r - l)/2; if( A[m] <= key ) l = m; else r = m; } return l;} // Input: Indices Range (l ... r]// Invariant: A[r] >= key and A[l] > keyint GetLeftPosition(int A[], int l, int r, int key){ int m; while( r - l > 1 ) { m = l + (r - l)/2; if( A[m] >= key ) r = m; else l = m; } return r;} int CountOccurances(int A[], int size, int key){ // Observe boundary conditions int left = GetLeftPosition(A, -1, size-1, key); int right = GetRightPosition(A, 0, size, key); // What if the element doesn't exists in the array? // The checks helps to trace that element exists return (A[left] == key && key == A[right])? (right - left + 1) : 0;} Sample code http://ideone.com/zn6R6a. Problem Statement: Given a sorted array of distinct elements, and the array is rotated at an unknown position. Find minimum element in the array. We can see pictorial representation of sample input array in the below figure. We converge the search space till l and r points single element. If the middle location falls in the first pulse, the condition A[m] < A[r] doesn’t satisfy, we converge our search space to A[m+1 ... r]. If the middle location falls in the second pulse, the condition A[m] < A[r] satisfied, we converge our search space to A[1 ... m]. At every iteration we check for search space size, if it is 1, we are done. Given below is implementation of algorithm. Can you come up with different implementation? C int BinarySearchIndexOfMinimumRotatedArray(int A[], int l, int r){ // extreme condition, size zero or size two int m; // Precondition: A[l] > A[r] if( A[l] <= A[r] ) return l; while( l <= r ) { // Termination condition (l will eventually falls on r, and r always // point minimum possible value) if( l == r ) return l; m = l + (r-l)/2; // 'm' can fall in first pulse, // second pulse or exactly in the middle if( A[m] < A[r] ) // min can't be in the range // (m < i <= r), we can exclude A[m+1 ... r] r = m; else // min must be in the range (m < i <= r), // we must search in A[m+1 ... r] l = m+1; } return -1;} int BinarySearchIndexOfMinimumRotatedArray(int A[], int size){ return BinarySearchIndexOfMinimumRotatedArray(A, 0, size-1);} See sample test cases http://ideone.com/KbwDrk. Exercises: 1. A function called signum(x, y) is defined as, signum(x, y) = -1 if x < y = 0 if x = y = 1 if x > y Did you come across any instruction set in which a comparison behaves like signum function? Can it make the first implementation of binary search optimal? 2. Implement ceil function replica of floor function. 3. Discuss with your friends “Is binary search optimal (results in the least number of comparisons)? Why not ternary search or interpolation search on a sorted array? When do you prefer ternary or interpolation search over binary search?” 4. Draw a tree representation of binary search (believe me, it helps you a lot to understand much internals of binary search). Stay tuned, I will cover few more interesting problems using binary search in upcoming articles. I welcome your comments. – – – by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Nitin Jain 7 Aryan_Sapra_280 AjayN adityac9254 sanjoy_62 code_hunt gfgking Binary Search Searching Searching Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons K'th Smallest/Largest Element in Unsorted Array | Set 1 Search an element in a sorted and rotated array Find the Missing Number Search, insert and delete in an unsorted array Program to find largest element in an array k largest(or smallest) elements in an array Two Pointers Technique Given an array of size n and a number k, find all elements that appear more than n/k times Search, insert and delete in a sorted array
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Jun, 2022" }, { "code": null, "e": 712, "s": 54, "text": "We all aware of binary search algorithm. Binary search is easiest difficult algorithm to get it right. I present some interesting problems that I collected on binary search. There were some requests on binary search. I request you to honor the code, “I sincerely attempt to solve the problem and ensure there are no corner cases”. After reading each problem minimize the browser and try solving it. Problem Statement: Given a sorted array of N distinct elements. Find a key in the array using least number of comparisons. (Do you think binary search is optimal to search a key in sorted array?) Without much theory, here is typical binary search algorithm. " }, { "code": null, "e": 714, "s": 712, "text": "C" }, { "code": null, "e": 719, "s": 714, "text": "Java" }, { "code": null, "e": 722, "s": 719, "text": "C#" }, { "code": null, "e": 733, "s": 722, "text": "Javascript" }, { "code": "// Returns location of key, or -1 if not foundint BinarySearch(int A[], int l, int r, int key){ int m; while( l <= r ) { m = l + (r-l)/2; if( A[m] == key ) // first comparison return m; if( A[m] < key ) // second comparison l = m + 1; else r = m - 1; } return -1;}", "e": 1082, "s": 733, "text": null }, { "code": "// Java code to implement the approachimport java.util.*; class GFG { // Returns location of key, or -1 if not foundstatic int BinarySearch(int A[], int l, int r, int key){ int m; while( l < r ) { m = l + (r-l)/2; if( A[m] == key ) // first comparison return m; if( A[m] < key ) // second comparison l = m + 1; else r = m - 1; } return -1;}} // This code is contributed by sanjoy_62.", "e": 1553, "s": 1082, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Returns location of key, or -1 if not foundstatic int BinarySearch(int[] A, int l, int r, int key){ int m; while( l < r ) { m = l + (r-l)/2; if( A[m] == key ) // first comparison return m; if( A[m] < key ) // second comparison l = m + 1; else r = m - 1; } return -1;}} // This code is contributed by code_hunt.", "e": 2026, "s": 1553, "text": null }, { "code": "<script>// Javascript code to implement the approach // Returns location of key, or -1 if not foundfunction BinarySearch(A, l, r, key) { let m; while (l < r) { m = l + (r - l) / 2; if (A[m] == key) // first comparison return m; if (A[m] < key) // second comparison l = m + 1; else r = m - 1; } return -1;} // This code is contributed by gfgking</script>", "e": 2423, "s": 2026, "text": null }, { "code": null, "e": 2892, "s": 2423, "text": "Theoretically we need log N + 1 comparisons in worst case. If we observe, we are using two comparisons per iteration except during final successful match, if any. In practice, comparison would be costly operation, it won’t be just primitive type comparison. It is more economical to minimize comparisons as that of theoretical limit. See below figure on initialize of indices in the next implementation. The following implementation uses fewer number of comparisons. " }, { "code": null, "e": 2894, "s": 2892, "text": "C" }, { "code": "// Invariant: A[l] <= key and A[r] > key// Boundary: |r - l| = 1// Input: A[l .... r-1]int BinarySearch(int A[], int l, int r, int key){ int m; while( r - l > 1 ) { m = l + (r-l)/2; if( A[m] <= key ) l = m; else r = m; } if( A[l] == key ) return l; if( A[r] == key ) return r; else return -1;}", "e": 3279, "s": 2894, "text": null }, { "code": null, "e": 4298, "s": 3279, "text": "In the while loop we are depending only on one comparison. The search space converges to place l and r point two different consecutive elements. We need one more comparison to trace search status. You can see sample test case http://ideone.com/76bad0. (C++11 code) Problem Statement: Given an array of N distinct integers, find floor value of input ‘key’. Say, A = {-1, 2, 3, 5, 6, 8, 9, 10} and key = 7, we should return 6 as outcome. We can use the above optimized implementation to find floor value of key. We keep moving the left pointer to right most as long as the invariant holds. Eventually left pointer points an element less than or equal to key (by definition floor value). The following are possible corner cases, —> If all elements in the array are smaller than key, left pointer moves till last element. —> If all elements in the array are greater than key, it is an error condition. —> If all elements in the array equal and <= key, it is worst case input to our implementation. Here is implementation, " }, { "code": null, "e": 4300, "s": 4298, "text": "C" }, { "code": "// largest value <= key// Invariant: A[l] <= key and A[r] > key// Boundary: |r - l| = 1// Input: A[l .... r-1]// Precondition: A[l] <= key <= A[r]int Floor(int A[], int l, int r, int key){ int m; while( r - l > 1 ) { m = l + (r - l)/2; if( A[m] <= key ) l = m; else r = m; } return A[l];} // Initial callint Floor(int A[], int size, int key){ // Add error checking if key < A[0] if( key < A[0] ) return -1; // Observe boundaries return Floor(A, 0, size, key);}", "e": 4847, "s": 4300, "text": null }, { "code": null, "e": 5241, "s": 4847, "text": "You can see some test cases http://ideone.com/z0Kx4a. Problem Statement: Given a sorted array with possible duplicate elements. Find number of occurrences of input ‘key’ in log N time. The idea here is finding left and right most occurrences of key in the array using binary search. We can modify floor function to trace right most occurrence and left most occurrence. Here is implementation, " }, { "code": null, "e": 5243, "s": 5241, "text": "C" }, { "code": "// Input: Indices Range [l ... r)// Invariant: A[l] <= key and A[r] > keyint GetRightPosition(int A[], int l, int r, int key){ int m; while( r - l > 1 ) { m = l + (r - l)/2; if( A[m] <= key ) l = m; else r = m; } return l;} // Input: Indices Range (l ... r]// Invariant: A[r] >= key and A[l] > keyint GetLeftPosition(int A[], int l, int r, int key){ int m; while( r - l > 1 ) { m = l + (r - l)/2; if( A[m] >= key ) r = m; else l = m; } return r;} int CountOccurances(int A[], int size, int key){ // Observe boundary conditions int left = GetLeftPosition(A, -1, size-1, key); int right = GetRightPosition(A, 0, size, key); // What if the element doesn't exists in the array? // The checks helps to trace that element exists return (A[left] == key && key == A[right])? (right - left + 1) : 0;}", "e": 6195, "s": 5243, "text": null }, { "code": null, "e": 6962, "s": 6195, "text": "Sample code http://ideone.com/zn6R6a. Problem Statement: Given a sorted array of distinct elements, and the array is rotated at an unknown position. Find minimum element in the array. We can see pictorial representation of sample input array in the below figure. We converge the search space till l and r points single element. If the middle location falls in the first pulse, the condition A[m] < A[r] doesn’t satisfy, we converge our search space to A[m+1 ... r]. If the middle location falls in the second pulse, the condition A[m] < A[r] satisfied, we converge our search space to A[1 ... m]. At every iteration we check for search space size, if it is 1, we are done. Given below is implementation of algorithm. Can you come up with different implementation? " }, { "code": null, "e": 6964, "s": 6962, "text": "C" }, { "code": "int BinarySearchIndexOfMinimumRotatedArray(int A[], int l, int r){ // extreme condition, size zero or size two int m; // Precondition: A[l] > A[r] if( A[l] <= A[r] ) return l; while( l <= r ) { // Termination condition (l will eventually falls on r, and r always // point minimum possible value) if( l == r ) return l; m = l + (r-l)/2; // 'm' can fall in first pulse, // second pulse or exactly in the middle if( A[m] < A[r] ) // min can't be in the range // (m < i <= r), we can exclude A[m+1 ... r] r = m; else // min must be in the range (m < i <= r), // we must search in A[m+1 ... r] l = m+1; } return -1;} int BinarySearchIndexOfMinimumRotatedArray(int A[], int size){ return BinarySearchIndexOfMinimumRotatedArray(A, 0, size-1);}", "e": 7888, "s": 6964, "text": null }, { "code": null, "e": 7996, "s": 7888, "text": "See sample test cases http://ideone.com/KbwDrk. Exercises: 1. A function called signum(x, y) is defined as," }, { "code": null, "e": 8077, "s": 7996, "text": "signum(x, y) = -1 if x < y\n = 0 if x = y\n = 1 if x > y" }, { "code": null, "e": 8652, "s": 8077, "text": "Did you come across any instruction set in which a comparison behaves like signum function? Can it make the first implementation of binary search optimal? 2. Implement ceil function replica of floor function. 3. Discuss with your friends “Is binary search optimal (results in the least number of comparisons)? Why not ternary search or interpolation search on a sorted array? When do you prefer ternary or interpolation search over binary search?” 4. Draw a tree representation of binary search (believe me, it helps you a lot to understand much internals of binary search)." }, { "code": null, "e": 8915, "s": 8652, "text": "Stay tuned, I will cover few more interesting problems using binary search in upcoming articles. I welcome your comments. – – – by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 8928, "s": 8915, "text": "Nitin Jain 7" }, { "code": null, "e": 8944, "s": 8928, "text": "Aryan_Sapra_280" }, { "code": null, "e": 8950, "s": 8944, "text": "AjayN" }, { "code": null, "e": 8962, "s": 8950, "text": "adityac9254" }, { "code": null, "e": 8972, "s": 8962, "text": "sanjoy_62" }, { "code": null, "e": 8982, "s": 8972, "text": "code_hunt" }, { "code": null, "e": 8990, "s": 8982, "text": "gfgking" }, { "code": null, "e": 9004, "s": 8990, "text": "Binary Search" }, { "code": null, "e": 9014, "s": 9004, "text": "Searching" }, { "code": null, "e": 9024, "s": 9014, "text": "Searching" }, { "code": null, "e": 9038, "s": 9024, "text": "Binary Search" }, { "code": null, "e": 9136, "s": 9038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9204, "s": 9136, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 9260, "s": 9204, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 9308, "s": 9260, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 9332, "s": 9308, "text": "Find the Missing Number" }, { "code": null, "e": 9379, "s": 9332, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 9423, "s": 9379, "text": "Program to find largest element in an array" }, { "code": null, "e": 9467, "s": 9423, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 9490, "s": 9467, "text": "Two Pointers Technique" }, { "code": null, "e": 9581, "s": 9490, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" } ]
Data Visualization in R
26 Apr, 2022 Data visualization is the technique used to deliver insights in data using visual cues such as graphs, charts, maps, and many others. This is useful as it helps in intuitive and easy understanding of the large quantities of data and thereby make better decisions regarding it. The popular data visualization tools that are available are Tableau, Plotly, R, Google Charts, Infogram, and Kibana. The various data visualization platforms have different capabilities, functionality, and use cases. They also require a different skill set. This article discusses the use of R for data visualization. R is a language that is designed for statistical computing, graphical data analysis, and scientific research. It is usually preferred for data visualization as it offers flexibility and minimum required coding through its packages. Some of the various types of visualizations offered by R are: There are two types of bar plots- horizontal and vertical which represent data points as horizontal or vertical bars of certain lengths proportional to the value of the data item. They are generally used for continuous and categorical variable plotting. By setting the horiz parameter to true and false, we can get horizontal and vertical bar plots respectively. Example 1: R # Horizontal Bar Plot for # Ozone concentration in airbarplot(airquality$Ozone, main = 'Ozone Concenteration in air', xlab = 'ozone levels', horiz = TRUE) Output: Example 2: R # Vertical Bar Plot for # Ozone concentration in airbarplot(airquality$Ozone, main = 'Ozone Concenteration in air', xlab = 'ozone levels', col ='blue', horiz = FALSE) Output: Bar plots are used for the following scenarios: To perform a comparative study between the various data categories in the data set. To analyze the change of a variable over time in months or years. A histogram is like a bar chart as it uses bars of varying height to represent data distribution. However, in a histogram values are grouped into consecutive intervals called bins. In a Histogram, continuous values are grouped and displayed in these bins whose size can be varied. Example: R # Histogram for Maximum Daily Temperaturedata(airquality) hist(airquality$Temp, main ="La Guardia Airport's\Maximum Temperature(Daily)", xlab ="Temperature(Fahrenheit)", xlim = c(50, 125), col ="yellow", freq = TRUE) Output: For a histogram, the parameter xlim can be used to specify the interval within which all values are to be displayed. Another parameter freq when set to TRUE denotes the frequency of the various values in the histogram and when set to FALSE, the probability densities are represented on the y-axis such that they are of the histogram adds up to one. Histograms are used in the following scenarios: To verify an equal and symmetric distribution of the data. To identify deviations from expected values. The statistical summary of the given data is presented graphically using a boxplot. A boxplot depicts information like the minimum and maximum data point, the median value, first and third quartile, and interquartile range. Example: R # Box plot for average wind speeddata(airquality) boxplot(airquality$Wind, main = "Average wind speed\at La Guardia Airport", xlab = "Miles per hour", ylab = "Wind", col = "orange", border = "brown", horizontal = TRUE, notch = TRUE) Output: Multiple box plots can also be generated at once through the following code: Example: R # Multiple Box plots, each representing# an Air Quality Parameterboxplot(airquality[, 0:4], main ='Box Plots for Air Quality Parameters') Output: Box Plots are used for: To give a comprehensive statistical description of the data through a visual cue. To identify the outlier points that do not lie in the inter-quartile range of data. A scatter plot is composed of many points on a Cartesian plane. Each point denotes the value taken by two parameters and helps us easily identify the relationship between them. Example: R # Scatter plot for Ozone Concentration per monthdata(airquality) plot(airquality$Ozone, airquality$Month, main ="Scatterplot Example", xlab ="Ozone Concentration in parts per billion", ylab =" Month of observation ", pch = 19) Output: Scatter Plots are used in the following scenarios: To show whether an association exists between bivariate data. To measure the strength and direction of such a relationship. Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix. heatmap() function is used to plot heatmap. Syntax: heatmap(data) Parameters: data: It represent matrix data, such as values of rows and columns Return: This function draws a heatmap. R # Set seed for reproducibility# set.seed(110) # Create example datadata <- matrix(rnorm(50, 0, 5), nrow = 5, ncol = 5) # Column namescolnames(data) <- paste0("col", 1:5)rownames(data) <- paste0("row", 1:5) # Draw a heatmapheatmap(data) Output: Here we are using maps package to visualize and display geographical maps using an R programming language. install.packages("maps") Link of the dataset: worldcities.csv R # Read dataset and convert it into# Dataframedata <- read.csv("worldcities.csv")df <- data.frame(data) # Load the required librarieslibrary(maps)map(database = "world") # marking points on mappoints(x = df$lat[1:500], y = df$lng[1:500], col = "Red") Output: Here we will use preps() function, This function is used to create 3D surfaces in perspective view. This function will draw perspective plots of a surface over the x–y plane. Syntax: persp(x, y, z) Parameter: This function accepts different parameters i.e. x, y and z where x and y are vectors defining the location along x- and y-axis. z-axis will be the height of the surface in the matrix z. Return Value: persp() returns the viewing transformation matrix for projecting 3D coordinates (x, y, z) into the 2D plane using homogeneous 4D coordinates (x, y, z, t). R # Adding Titles and Labeling Axes to Plotcone <- function(x, y){sqrt(x ^ 2 + y ^ 2)} # prepare variables.x <- y <- seq(-1, 1, length = 30)z <- outer(x, y, cone) # plot the 3D surface# Adding Titles and Labeling Axes to Plotpersp(x, y, z,main="Perspective Plot of a Cone",zlab = "Height",theta = 30, phi = 15,col = "orange", shade = 0.4) Output: R has the following advantages over other tools for data visualization: R offers a broad collection of visualization libraries along with extensive online guidance on their usage. R also offers data visualization in the form of 3D models and multipanel charts. Through R, we can easily customize our data visualization by changing axes, fonts, legends, annotations, and labels. R also has the following disadvantages: R is only preferred for data visualization when done on an individual standalone server. Data visualization using R is slow for large amounts of data as compared to other counterparts. Presenting analytical conclusions of the data to the non-analysts departments of your company. Health monitoring devices use data visualization to track any anomaly in blood pressure, cholesterol and others. To discover repeating patterns and trends in consumer and marketing data. Meteorologists use data visualization for assessing prevalent weather changes throughout the world. Real-time maps and geo-positioning systems use visualization for traffic monitoring and estimating travel time. kumar_satyam sweetyty data-science Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) How to Split Column Into Multiple Columns in R DataFrame? Adding elements in a vector in R programming - append() method Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Apr, 2022" }, { "code": null, "e": 305, "s": 28, "text": "Data visualization is the technique used to deliver insights in data using visual cues such as graphs, charts, maps, and many others. This is useful as it helps in intuitive and easy understanding of the large quantities of data and thereby make better decisions regarding it." }, { "code": null, "e": 623, "s": 305, "text": "The popular data visualization tools that are available are Tableau, Plotly, R, Google Charts, Infogram, and Kibana. The various data visualization platforms have different capabilities, functionality, and use cases. They also require a different skill set. This article discusses the use of R for data visualization." }, { "code": null, "e": 855, "s": 623, "text": "R is a language that is designed for statistical computing, graphical data analysis, and scientific research. It is usually preferred for data visualization as it offers flexibility and minimum required coding through its packages." }, { "code": null, "e": 917, "s": 855, "text": "Some of the various types of visualizations offered by R are:" }, { "code": null, "e": 1281, "s": 917, "text": "There are two types of bar plots- horizontal and vertical which represent data points as horizontal or vertical bars of certain lengths proportional to the value of the data item. They are generally used for continuous and categorical variable plotting. By setting the horiz parameter to true and false, we can get horizontal and vertical bar plots respectively. " }, { "code": null, "e": 1293, "s": 1281, "text": "Example 1: " }, { "code": null, "e": 1295, "s": 1293, "text": "R" }, { "code": "# Horizontal Bar Plot for # Ozone concentration in airbarplot(airquality$Ozone, main = 'Ozone Concenteration in air', xlab = 'ozone levels', horiz = TRUE)", "e": 1464, "s": 1295, "text": null }, { "code": null, "e": 1472, "s": 1464, "text": "Output:" }, { "code": null, "e": 1484, "s": 1472, "text": "Example 2: " }, { "code": null, "e": 1486, "s": 1484, "text": "R" }, { "code": "# Vertical Bar Plot for # Ozone concentration in airbarplot(airquality$Ozone, main = 'Ozone Concenteration in air', xlab = 'ozone levels', col ='blue', horiz = FALSE)", "e": 1661, "s": 1486, "text": null }, { "code": null, "e": 1669, "s": 1661, "text": "Output:" }, { "code": null, "e": 1717, "s": 1669, "text": "Bar plots are used for the following scenarios:" }, { "code": null, "e": 1801, "s": 1717, "text": "To perform a comparative study between the various data categories in the data set." }, { "code": null, "e": 1867, "s": 1801, "text": "To analyze the change of a variable over time in months or years." }, { "code": null, "e": 2148, "s": 1867, "text": "A histogram is like a bar chart as it uses bars of varying height to represent data distribution. However, in a histogram values are grouped into consecutive intervals called bins. In a Histogram, continuous values are grouped and displayed in these bins whose size can be varied." }, { "code": null, "e": 2158, "s": 2148, "text": "Example: " }, { "code": null, "e": 2160, "s": 2158, "text": "R" }, { "code": "# Histogram for Maximum Daily Temperaturedata(airquality) hist(airquality$Temp, main =\"La Guardia Airport's\\Maximum Temperature(Daily)\", xlab =\"Temperature(Fahrenheit)\", xlim = c(50, 125), col =\"yellow\", freq = TRUE)", "e": 2387, "s": 2160, "text": null }, { "code": null, "e": 2395, "s": 2387, "text": "Output:" }, { "code": null, "e": 2745, "s": 2395, "text": "For a histogram, the parameter xlim can be used to specify the interval within which all values are to be displayed. Another parameter freq when set to TRUE denotes the frequency of the various values in the histogram and when set to FALSE, the probability densities are represented on the y-axis such that they are of the histogram adds up to one. " }, { "code": null, "e": 2794, "s": 2745, "text": "Histograms are used in the following scenarios: " }, { "code": null, "e": 2853, "s": 2794, "text": "To verify an equal and symmetric distribution of the data." }, { "code": null, "e": 2898, "s": 2853, "text": "To identify deviations from expected values." }, { "code": null, "e": 3122, "s": 2898, "text": "The statistical summary of the given data is presented graphically using a boxplot. A boxplot depicts information like the minimum and maximum data point, the median value, first and third quartile, and interquartile range." }, { "code": null, "e": 3132, "s": 3122, "text": "Example: " }, { "code": null, "e": 3134, "s": 3132, "text": "R" }, { "code": "# Box plot for average wind speeddata(airquality) boxplot(airquality$Wind, main = \"Average wind speed\\at La Guardia Airport\", xlab = \"Miles per hour\", ylab = \"Wind\", col = \"orange\", border = \"brown\", horizontal = TRUE, notch = TRUE)", "e": 3389, "s": 3134, "text": null }, { "code": null, "e": 3397, "s": 3389, "text": "Output:" }, { "code": null, "e": 3474, "s": 3397, "text": "Multiple box plots can also be generated at once through the following code:" }, { "code": null, "e": 3484, "s": 3474, "text": "Example: " }, { "code": null, "e": 3486, "s": 3484, "text": "R" }, { "code": "# Multiple Box plots, each representing# an Air Quality Parameterboxplot(airquality[, 0:4], main ='Box Plots for Air Quality Parameters')", "e": 3632, "s": 3486, "text": null }, { "code": null, "e": 3640, "s": 3632, "text": "Output:" }, { "code": null, "e": 3665, "s": 3640, "text": "Box Plots are used for: " }, { "code": null, "e": 3747, "s": 3665, "text": "To give a comprehensive statistical description of the data through a visual cue." }, { "code": null, "e": 3831, "s": 3747, "text": "To identify the outlier points that do not lie in the inter-quartile range of data." }, { "code": null, "e": 4008, "s": 3831, "text": "A scatter plot is composed of many points on a Cartesian plane. Each point denotes the value taken by two parameters and helps us easily identify the relationship between them." }, { "code": null, "e": 4018, "s": 4008, "text": "Example: " }, { "code": null, "e": 4020, "s": 4018, "text": "R" }, { "code": "# Scatter plot for Ozone Concentration per monthdata(airquality) plot(airquality$Ozone, airquality$Month, main =\"Scatterplot Example\", xlab =\"Ozone Concentration in parts per billion\", ylab =\" Month of observation \", pch = 19)", "e": 4258, "s": 4020, "text": null }, { "code": null, "e": 4266, "s": 4258, "text": "Output:" }, { "code": null, "e": 4318, "s": 4266, "text": "Scatter Plots are used in the following scenarios: " }, { "code": null, "e": 4380, "s": 4318, "text": "To show whether an association exists between bivariate data." }, { "code": null, "e": 4442, "s": 4380, "text": "To measure the strength and direction of such a relationship." }, { "code": null, "e": 4594, "s": 4442, "text": "Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix. heatmap() function is used to plot heatmap." }, { "code": null, "e": 4616, "s": 4594, "text": "Syntax: heatmap(data)" }, { "code": null, "e": 4695, "s": 4616, "text": "Parameters: data: It represent matrix data, such as values of rows and columns" }, { "code": null, "e": 4734, "s": 4695, "text": "Return: This function draws a heatmap." }, { "code": null, "e": 4736, "s": 4734, "text": "R" }, { "code": "# Set seed for reproducibility# set.seed(110) # Create example datadata <- matrix(rnorm(50, 0, 5), nrow = 5, ncol = 5) # Column namescolnames(data) <- paste0(\"col\", 1:5)rownames(data) <- paste0(\"row\", 1:5) # Draw a heatmapheatmap(data) ", "e": 4983, "s": 4736, "text": null }, { "code": null, "e": 4991, "s": 4983, "text": "Output:" }, { "code": null, "e": 5098, "s": 4991, "text": "Here we are using maps package to visualize and display geographical maps using an R programming language." }, { "code": null, "e": 5123, "s": 5098, "text": "install.packages(\"maps\")" }, { "code": null, "e": 5160, "s": 5123, "text": "Link of the dataset: worldcities.csv" }, { "code": null, "e": 5162, "s": 5160, "text": "R" }, { "code": "# Read dataset and convert it into# Dataframedata <- read.csv(\"worldcities.csv\")df <- data.frame(data) # Load the required librarieslibrary(maps)map(database = \"world\") # marking points on mappoints(x = df$lat[1:500], y = df$lng[1:500], col = \"Red\")", "e": 5416, "s": 5162, "text": null }, { "code": null, "e": 5424, "s": 5416, "text": "Output:" }, { "code": null, "e": 5599, "s": 5424, "text": "Here we will use preps() function, This function is used to create 3D surfaces in perspective view. This function will draw perspective plots of a surface over the x–y plane." }, { "code": null, "e": 5622, "s": 5599, "text": "Syntax: persp(x, y, z)" }, { "code": null, "e": 5819, "s": 5622, "text": "Parameter: This function accepts different parameters i.e. x, y and z where x and y are vectors defining the location along x- and y-axis. z-axis will be the height of the surface in the matrix z." }, { "code": null, "e": 5988, "s": 5819, "text": "Return Value: persp() returns the viewing transformation matrix for projecting 3D coordinates (x, y, z) into the 2D plane using homogeneous 4D coordinates (x, y, z, t)." }, { "code": null, "e": 5990, "s": 5988, "text": "R" }, { "code": "# Adding Titles and Labeling Axes to Plotcone <- function(x, y){sqrt(x ^ 2 + y ^ 2)} # prepare variables.x <- y <- seq(-1, 1, length = 30)z <- outer(x, y, cone) # plot the 3D surface# Adding Titles and Labeling Axes to Plotpersp(x, y, z,main=\"Perspective Plot of a Cone\",zlab = \"Height\",theta = 30, phi = 15,col = \"orange\", shade = 0.4)", "e": 6333, "s": 5990, "text": null }, { "code": null, "e": 6341, "s": 6333, "text": "Output:" }, { "code": null, "e": 6414, "s": 6341, "text": "R has the following advantages over other tools for data visualization: " }, { "code": null, "e": 6522, "s": 6414, "text": "R offers a broad collection of visualization libraries along with extensive online guidance on their usage." }, { "code": null, "e": 6603, "s": 6522, "text": "R also offers data visualization in the form of 3D models and multipanel charts." }, { "code": null, "e": 6720, "s": 6603, "text": "Through R, we can easily customize our data visualization by changing axes, fonts, legends, annotations, and labels." }, { "code": null, "e": 6761, "s": 6720, "text": "R also has the following disadvantages: " }, { "code": null, "e": 6850, "s": 6761, "text": "R is only preferred for data visualization when done on an individual standalone server." }, { "code": null, "e": 6946, "s": 6850, "text": "Data visualization using R is slow for large amounts of data as compared to other counterparts." }, { "code": null, "e": 7041, "s": 6946, "text": "Presenting analytical conclusions of the data to the non-analysts departments of your company." }, { "code": null, "e": 7154, "s": 7041, "text": "Health monitoring devices use data visualization to track any anomaly in blood pressure, cholesterol and others." }, { "code": null, "e": 7228, "s": 7154, "text": "To discover repeating patterns and trends in consumer and marketing data." }, { "code": null, "e": 7328, "s": 7228, "text": "Meteorologists use data visualization for assessing prevalent weather changes throughout the world." }, { "code": null, "e": 7440, "s": 7328, "text": "Real-time maps and geo-positioning systems use visualization for traffic monitoring and estimating travel time." }, { "code": null, "e": 7453, "s": 7440, "text": "kumar_satyam" }, { "code": null, "e": 7462, "s": 7453, "text": "sweetyty" }, { "code": null, "e": 7475, "s": 7462, "text": "data-science" }, { "code": null, "e": 7482, "s": 7475, "text": "Picked" }, { "code": null, "e": 7493, "s": 7482, "text": "R Language" }, { "code": null, "e": 7591, "s": 7493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7636, "s": 7591, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 7688, "s": 7636, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 7746, "s": 7688, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 7798, "s": 7746, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 7830, "s": 7798, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 7888, "s": 7830, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 7951, "s": 7888, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 7986, "s": 7951, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 8030, "s": 7986, "text": "How to change Row Names of DataFrame in R ?" } ]
Python OpenCV – waitKey() Function
17 Oct, 2021 waitkey() function of Python OpenCV allows users to display a window for given milliseconds or until any key is pressed. It takes time in milliseconds as a parameter and waits for the given time to destroy the window, if 0 is passed in the argument it waits till any key is pressed. Using waitKey() method we show the image for 5 seconds before it automatically closes. The code will be as follows: Python # importing cv2 moduleimport cv2 # read the imageimg = cv2.imread("gfg_logo.png") # showing the imagecv2.imshow('gfg', img) # waiting using waitKey methodcv2.waitKey(5000) Output: Now we can see one example of passing 0 as the parameter. This time instead of automatically closing the window would wait till any key is pressed. The code will be: Python # importing cv2 moduleimport cv2 # read the imageimg = cv2.imread("gfg_logo.png") # showing the imagecv2.imshow('gfg', img) # waiting using waitKey methodcv2.waitKey(0) Output: Picked Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Oct, 2021" }, { "code": null, "e": 312, "s": 28, "text": "waitkey() function of Python OpenCV allows users to display a window for given milliseconds or until any key is pressed. It takes time in milliseconds as a parameter and waits for the given time to destroy the window, if 0 is passed in the argument it waits till any key is pressed. " }, { "code": null, "e": 428, "s": 312, "text": "Using waitKey() method we show the image for 5 seconds before it automatically closes. The code will be as follows:" }, { "code": null, "e": 435, "s": 428, "text": "Python" }, { "code": "# importing cv2 moduleimport cv2 # read the imageimg = cv2.imread(\"gfg_logo.png\") # showing the imagecv2.imshow('gfg', img) # waiting using waitKey methodcv2.waitKey(5000)", "e": 610, "s": 435, "text": null }, { "code": null, "e": 618, "s": 610, "text": "Output:" }, { "code": null, "e": 784, "s": 618, "text": "Now we can see one example of passing 0 as the parameter. This time instead of automatically closing the window would wait till any key is pressed. The code will be:" }, { "code": null, "e": 791, "s": 784, "text": "Python" }, { "code": "# importing cv2 moduleimport cv2 # read the imageimg = cv2.imread(\"gfg_logo.png\") # showing the imagecv2.imshow('gfg', img) # waiting using waitKey methodcv2.waitKey(0)", "e": 963, "s": 791, "text": null }, { "code": null, "e": 971, "s": 963, "text": "Output:" }, { "code": null, "e": 978, "s": 971, "text": "Picked" }, { "code": null, "e": 992, "s": 978, "text": "Python-OpenCV" }, { "code": null, "e": 999, "s": 992, "text": "Python" } ]
Print Fibonacci Series in reverse order using Recursion
01 Dec, 2021 Given an integer N, the task is to print the first N terms of the Fibonacci series in reverse order using Recursion. Examples: Input: N = 5Output: 3 2 1 1 0Explanation: First five terms are – 0 1 1 2 3. Input: N = 10Output: 34 21 13 8 5 3 2 1 1 0 Approach: The idea is to use recursion in a way that keeps calling the same function again till N is greater than 0 and keeps on adding the terms and after that starts printing the terms. Follow the steps below to solve the problem: Define a function fibo(int N, int a, int b) whereN is the number of terms anda and b are the initial terms with values 0 and 1. N is the number of terms and a and b are the initial terms with values 0 and 1. If N is greater than 0, then call the function again with values N-1, b, a+b. After the function call, print a as the answer. Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print the fibonacci// series in reverse order.void fibo(int n, int a, int b){ if (n > 0) { // Function call fibo(n - 1, b, a + b); // Print the result cout << a << " "; }} // Driver Codeint main(){ int N = 10; fibo(N, 0, 1); return 0;} // Java program for the above approachimport java.util.*;public class GFG{// Function to print the fibonacci// series in reverse order.static void fibo(int n, int a, int b){ if (n > 0) { // Function call fibo(n - 1, b, a + b); // Print the result System.out.print(a + " "); }} // Driver Codepublic static void main(String args[]){ int N = 10; fibo(N, 0, 1);}}// This code is contributed by Samim Hossain Mondal. # Python program for the above approach # Function to print the fibonacci# series in reverse order.def fibo(n, a, b): if (n > 0): # Function call fibo(n - 1, b, a + b) # Print the result print(a, end=" ") # Driver Codeif __name__ == "__main__": N = 10 fibo(N, 0, 1) # This code is contributed by Samim Hossain Mondal. // C# program for the above approachusing System;class GFG{// Function to print the fibonacci// series in reverse order.static void fibo(int n, int a, int b){ if (n > 0) { // Function call fibo(n - 1, b, a + b); // Print the result Console.Write(a + " "); }} // Driver Codepublic static void Main(){ int N = 10; fibo(N, 0, 1);}}// This code is contributed by Samim Hossain Mondal. <script>// Javascript program for the above approach // Function to print the fibonacci// series in reverse order.function fibo(n, a, b){ if (n > 0) { // Function call fibo(n - 1, b, a + b); // Print the result document.write(a + " "); }} // Driver Codelet N = 10;fibo(N, 0, 1); // This code is contributed by Samim Hossain Mondal.</script> 34 21 13 8 5 3 2 1 1 0 Time Complexity: O(N)Auxiliary Space: O(N) samim2000 Fibonacci Reverse Mathematical Pattern Searching Recursion Mathematical Recursion Fibonacci Pattern Searching Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Dec, 2021" }, { "code": null, "e": 145, "s": 28, "text": "Given an integer N, the task is to print the first N terms of the Fibonacci series in reverse order using Recursion." }, { "code": null, "e": 155, "s": 145, "text": "Examples:" }, { "code": null, "e": 232, "s": 155, "text": "Input: N = 5Output: 3 2 1 1 0Explanation: First five terms are – 0 1 1 2 3. " }, { "code": null, "e": 276, "s": 232, "text": "Input: N = 10Output: 34 21 13 8 5 3 2 1 1 0" }, { "code": null, "e": 465, "s": 276, "text": "Approach: The idea is to use recursion in a way that keeps calling the same function again till N is greater than 0 and keeps on adding the terms and after that starts printing the terms. " }, { "code": null, "e": 510, "s": 465, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 638, "s": 510, "text": "Define a function fibo(int N, int a, int b) whereN is the number of terms anda and b are the initial terms with values 0 and 1." }, { "code": null, "e": 667, "s": 638, "text": "N is the number of terms and" }, { "code": null, "e": 718, "s": 667, "text": "a and b are the initial terms with values 0 and 1." }, { "code": null, "e": 796, "s": 718, "text": "If N is greater than 0, then call the function again with values N-1, b, a+b." }, { "code": null, "e": 844, "s": 796, "text": "After the function call, print a as the answer." }, { "code": null, "e": 895, "s": 844, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 899, "s": 895, "text": "C++" }, { "code": null, "e": 904, "s": 899, "text": "Java" }, { "code": null, "e": 912, "s": 904, "text": "Python3" }, { "code": null, "e": 915, "s": 912, "text": "C#" }, { "code": null, "e": 926, "s": 915, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print the fibonacci// series in reverse order.void fibo(int n, int a, int b){ if (n > 0) { // Function call fibo(n - 1, b, a + b); // Print the result cout << a << \" \"; }} // Driver Codeint main(){ int N = 10; fibo(N, 0, 1); return 0;}", "e": 1304, "s": 926, "text": null }, { "code": "// Java program for the above approachimport java.util.*;public class GFG{// Function to print the fibonacci// series in reverse order.static void fibo(int n, int a, int b){ if (n > 0) { // Function call fibo(n - 1, b, a + b); // Print the result System.out.print(a + \" \"); }} // Driver Codepublic static void main(String args[]){ int N = 10; fibo(N, 0, 1);}}// This code is contributed by Samim Hossain Mondal.", "e": 1758, "s": 1304, "text": null }, { "code": "# Python program for the above approach # Function to print the fibonacci# series in reverse order.def fibo(n, a, b): if (n > 0): # Function call fibo(n - 1, b, a + b) # Print the result print(a, end=\" \") # Driver Codeif __name__ == \"__main__\": N = 10 fibo(N, 0, 1) # This code is contributed by Samim Hossain Mondal.", "e": 2122, "s": 1758, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{// Function to print the fibonacci// series in reverse order.static void fibo(int n, int a, int b){ if (n > 0) { // Function call fibo(n - 1, b, a + b); // Print the result Console.Write(a + \" \"); }} // Driver Codepublic static void Main(){ int N = 10; fibo(N, 0, 1);}}// This code is contributed by Samim Hossain Mondal.", "e": 2545, "s": 2122, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to print the fibonacci// series in reverse order.function fibo(n, a, b){ if (n > 0) { // Function call fibo(n - 1, b, a + b); // Print the result document.write(a + \" \"); }} // Driver Codelet N = 10;fibo(N, 0, 1); // This code is contributed by Samim Hossain Mondal.</script>", "e": 2922, "s": 2545, "text": null }, { "code": null, "e": 2949, "s": 2925, "text": "34 21 13 8 5 3 2 1 1 0 " }, { "code": null, "e": 2994, "s": 2951, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 3006, "s": 2996, "text": "samim2000" }, { "code": null, "e": 3016, "s": 3006, "text": "Fibonacci" }, { "code": null, "e": 3024, "s": 3016, "text": "Reverse" }, { "code": null, "e": 3037, "s": 3024, "text": "Mathematical" }, { "code": null, "e": 3055, "s": 3037, "text": "Pattern Searching" }, { "code": null, "e": 3065, "s": 3055, "text": "Recursion" }, { "code": null, "e": 3078, "s": 3065, "text": "Mathematical" }, { "code": null, "e": 3088, "s": 3078, "text": "Recursion" }, { "code": null, "e": 3098, "s": 3088, "text": "Fibonacci" }, { "code": null, "e": 3116, "s": 3098, "text": "Pattern Searching" }, { "code": null, "e": 3124, "s": 3116, "text": "Reverse" } ]
Maximum length possible by cutting N given woods into at least K pieces
23 Jun, 2022 Given an array wood[] of size N, representing the length of N pieces of wood and an integer K, at least K pieces of the same length need to be cut from the given wooden pieces. The task is to find the maximum possible length of these K wooden pieces that can be obtained. Examples: Input: wood[] = {5, 9, 7}, K = 3 Output: 5 Explanation: Cut arr[0] = 5 = 5 Cut arr[1] = 9 = 5 + 4 Cut arr[2] = 7 = 5 + 2 Therefore, the maximum length that can be obtained by cutting the woods into 3 pieces is 5. Input: wood[] = {5, 9, 7}, K = 4 Output: 4 Explanation: Cut arr[0] = 5 = 4 + 1 Cut arr[1] = 9 = 2 * 4 + 1 Cut arr[2] = 7 = 4 + 3 Therefore, the maximum length that can be obtained by cutting the woods into 4 pieces is 4. Approach: The problem can be solved using a Binary search. Follow the steps below to solve the problem: Find the maximum element from the array wood[] and store it in a variable, say Max. The value of L must lie in the range [1, Max]. Therefore, apply binary search over the range [1, Max]. Initialize two variables say, left = 1 and right = Max to store the range in which the value of L lies. Check if it is possible to cut the woods into K pieces with length of each piece equal to (left + right) / 2 or not. If found to be true, then update left = (left + right) / 2. Otherwise, update right = (left + right) / 2 . Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to check if it is possible to cut// woods into K pieces of length lenbool isValid(int wood[], int N, int len, int K){ // Stores count of pieces // having length equal to K int count = 0; // Traverse wood[] array for (int i = 0; i < N; i++) { // Update count count += wood[i] / len; } return count >= K;} // Function to find the maximum value of Lint findMaxLen(int wood[], int N, int K){ // Stores minimum possible value of L int left = 1; // Stores maximum possible value of L int right = *max_element(wood, wood + N); // Apply binary search over // the range [left, right] while (left <= right) { // Stores mid value of // left and right int mid = left + (right - left) / 2; // If it is possible to cut woods // into K pieces having length // of each piece equal to mid if (isValid(wood, N, mid, K)) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return right;} // Driver Codeint main(){ int wood[] = { 5, 9, 7 }; int N = sizeof(wood) / sizeof(wood[0]); int K = 4; cout << findMaxLen(wood, N, K);} // Java program to implement// the above approachimport java.util.*; class GFG{ // Function to check if it is possible// to cut woods into K pieces of// length lenstatic boolean isValid(int wood[], int N, int len, int K){ // Stores count of pieces // having length equal to K int count = 0; // Traverse wood[] array for(int i = 0; i < N; i++) { // Update count count += wood[i] / len; } return count >= K;} // Function to find the maximum value of Lstatic int findMaxLen(int wood[], int N, int K){ // Stores minimum possible value of L int left = 1; // Stores maximum possible value of L int right = Arrays.stream(wood).max().getAsInt(); // Apply binary search over // the range [left, right] while (left <= right) { // Stores mid value of // left and right int mid = left + (right - left) / 2; // If it is possible to cut woods // into K pieces having length // of each piece equal to mid if (isValid(wood, N, mid, K)) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return right;} // Driver Codepublic static void main(String[] args){ int wood[] = { 5, 9, 7 }; int N = wood.length; int K = 4; System.out.print(findMaxLen(wood, N, K));}} // This code is contributed by Princi Singh # Python3 program to implement# the above approach # Function to check if it is possible to# cut woods into K pieces of length lendef isValid(wood, N, len, K): # Stores count of pieces # having length equal to K count = 0 # Traverse wood[] array for i in range(N): # Update count count += wood[i] // len return (count >= K) # Function to find the maximum value of Ldef findMaxLen(wood, N, K): # Stores minimum possible value of L left = 1 # Stores maximum possible value of L right = max(wood) # Apply binary search over # the range [left, right] while (left <= right): # Stores mid value of # left and right mid = left + (right - left) // 2 # If it is possible to cut woods # into K pieces having length # of each piece equal to mid if (isValid(wood, N, mid, K)): # Update left left = mid + 1 else: # Update right right = mid - 1 return right # Driver Codeif __name__ == '__main__': wood = [ 5, 9, 7 ] N = len(wood) K = 4 print(findMaxLen(wood, N, K)) # This code is contributed by mohit kumar 29 // C# program to implement// the above approachusing System;using System.Linq;class GFG{ // Function to check if it is possible// to cut woods into K pieces of// length lenstatic bool isValid(int []wood, int N, int len, int K){ // Stores count of pieces // having length equal to K int count = 0; // Traverse wood[] array for(int i = 0; i < N; i++) { // Update count count += wood[i] / len; } return count >= K;} // Function to find the maximum// value of Lstatic int findMaxLen(int []wood, int N, int K){ // Stores minimum possible // value of L int left = 1; // Stores maximum possible // value of L int right = wood.Max(); // Apply binary search over // the range [left, right] while (left <= right) { // Stores mid value of // left and right int mid = left + (right - left) / 2; // If it is possible to cut woods // into K pieces having length // of each piece equal to mid if (isValid(wood, N, mid, K)) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return right;} // Driver Codepublic static void Main(String[] args){ int []wood = {5, 9, 7}; int N = wood.Length; int K = 4; Console.Write(findMaxLen(wood, N, K));}} // This code is contributed by shikhasingrajput <script> // Javascript program to implement// the above approach // Function to check if it is possible // to cut woods into K pieces of // length len function isValid(wood , N , len , K) { // Stores count of pieces // having length equal to K var count = 0; // Traverse wood array for (i = 0; i < N; i++) { // Update count count += parseInt(wood[i] / len); } return count >= K; } // Function to find the maximum value of L function findMaxLen(wood , N , K) { // Stores minimum possible value of L var left = 1; // Stores maximum possible value of L var right = Math.max.apply(Math,wood); // Apply binary search over // the range [left, right] while (left <= right) { // Stores mid value of // left and right var mid = left + (right - left) / 2; // If it is possible to cut woods // into K pieces having length // of each piece equal to mid if (isValid(wood, N, mid, K)) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return right; } // Driver Code var wood = [ 5, 9, 7 ]; var N = wood.length; var K = 4; document.write(findMaxLen(wood, N, K)); // This code is contributed by todaysgaurav </script> 4 Time Complexity: O(N * Log2M), where M is the maximum element of the given arrayAuxiliary Space: O(1) mohit kumar 29 princi singh shikhasingrajput todaysgaurav kanaujiyavimleshkumar sagar0719kumar jainlovely450 Arrays Binary Search Facebook Google interview-preparation Arrays Divide and Conquer Searching Google Facebook Arrays Searching Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 324, "s": 52, "text": "Given an array wood[] of size N, representing the length of N pieces of wood and an integer K, at least K pieces of the same length need to be cut from the given wooden pieces. The task is to find the maximum possible length of these K wooden pieces that can be obtained." }, { "code": null, "e": 334, "s": 324, "text": "Examples:" }, { "code": null, "e": 547, "s": 334, "text": "Input: wood[] = {5, 9, 7}, K = 3 Output: 5 Explanation: Cut arr[0] = 5 = 5 Cut arr[1] = 9 = 5 + 4 Cut arr[2] = 7 = 5 + 2 Therefore, the maximum length that can be obtained by cutting the woods into 3 pieces is 5." }, { "code": null, "e": 768, "s": 547, "text": "Input: wood[] = {5, 9, 7}, K = 4 Output: 4 Explanation: Cut arr[0] = 5 = 4 + 1 Cut arr[1] = 9 = 2 * 4 + 1 Cut arr[2] = 7 = 4 + 3 Therefore, the maximum length that can be obtained by cutting the woods into 4 pieces is 4." }, { "code": null, "e": 872, "s": 768, "text": "Approach: The problem can be solved using a Binary search. Follow the steps below to solve the problem:" }, { "code": null, "e": 956, "s": 872, "text": "Find the maximum element from the array wood[] and store it in a variable, say Max." }, { "code": null, "e": 1059, "s": 956, "text": "The value of L must lie in the range [1, Max]. Therefore, apply binary search over the range [1, Max]." }, { "code": null, "e": 1163, "s": 1059, "text": "Initialize two variables say, left = 1 and right = Max to store the range in which the value of L lies." }, { "code": null, "e": 1340, "s": 1163, "text": "Check if it is possible to cut the woods into K pieces with length of each piece equal to (left + right) / 2 or not. If found to be true, then update left = (left + right) / 2." }, { "code": null, "e": 1387, "s": 1340, "text": "Otherwise, update right = (left + right) / 2 ." }, { "code": null, "e": 1438, "s": 1387, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1442, "s": 1438, "text": "C++" }, { "code": null, "e": 1447, "s": 1442, "text": "Java" }, { "code": null, "e": 1455, "s": 1447, "text": "Python3" }, { "code": null, "e": 1458, "s": 1455, "text": "C#" }, { "code": null, "e": 1469, "s": 1458, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to check if it is possible to cut// woods into K pieces of length lenbool isValid(int wood[], int N, int len, int K){ // Stores count of pieces // having length equal to K int count = 0; // Traverse wood[] array for (int i = 0; i < N; i++) { // Update count count += wood[i] / len; } return count >= K;} // Function to find the maximum value of Lint findMaxLen(int wood[], int N, int K){ // Stores minimum possible value of L int left = 1; // Stores maximum possible value of L int right = *max_element(wood, wood + N); // Apply binary search over // the range [left, right] while (left <= right) { // Stores mid value of // left and right int mid = left + (right - left) / 2; // If it is possible to cut woods // into K pieces having length // of each piece equal to mid if (isValid(wood, N, mid, K)) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return right;} // Driver Codeint main(){ int wood[] = { 5, 9, 7 }; int N = sizeof(wood) / sizeof(wood[0]); int K = 4; cout << findMaxLen(wood, N, K);}", "e": 2852, "s": 1469, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to check if it is possible// to cut woods into K pieces of// length lenstatic boolean isValid(int wood[], int N, int len, int K){ // Stores count of pieces // having length equal to K int count = 0; // Traverse wood[] array for(int i = 0; i < N; i++) { // Update count count += wood[i] / len; } return count >= K;} // Function to find the maximum value of Lstatic int findMaxLen(int wood[], int N, int K){ // Stores minimum possible value of L int left = 1; // Stores maximum possible value of L int right = Arrays.stream(wood).max().getAsInt(); // Apply binary search over // the range [left, right] while (left <= right) { // Stores mid value of // left and right int mid = left + (right - left) / 2; // If it is possible to cut woods // into K pieces having length // of each piece equal to mid if (isValid(wood, N, mid, K)) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return right;} // Driver Codepublic static void main(String[] args){ int wood[] = { 5, 9, 7 }; int N = wood.length; int K = 4; System.out.print(findMaxLen(wood, N, K));}} // This code is contributed by Princi Singh", "e": 4380, "s": 2852, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to check if it is possible to# cut woods into K pieces of length lendef isValid(wood, N, len, K): # Stores count of pieces # having length equal to K count = 0 # Traverse wood[] array for i in range(N): # Update count count += wood[i] // len return (count >= K) # Function to find the maximum value of Ldef findMaxLen(wood, N, K): # Stores minimum possible value of L left = 1 # Stores maximum possible value of L right = max(wood) # Apply binary search over # the range [left, right] while (left <= right): # Stores mid value of # left and right mid = left + (right - left) // 2 # If it is possible to cut woods # into K pieces having length # of each piece equal to mid if (isValid(wood, N, mid, K)): # Update left left = mid + 1 else: # Update right right = mid - 1 return right # Driver Codeif __name__ == '__main__': wood = [ 5, 9, 7 ] N = len(wood) K = 4 print(findMaxLen(wood, N, K)) # This code is contributed by mohit kumar 29", "e": 5604, "s": 4380, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Linq;class GFG{ // Function to check if it is possible// to cut woods into K pieces of// length lenstatic bool isValid(int []wood, int N, int len, int K){ // Stores count of pieces // having length equal to K int count = 0; // Traverse wood[] array for(int i = 0; i < N; i++) { // Update count count += wood[i] / len; } return count >= K;} // Function to find the maximum// value of Lstatic int findMaxLen(int []wood, int N, int K){ // Stores minimum possible // value of L int left = 1; // Stores maximum possible // value of L int right = wood.Max(); // Apply binary search over // the range [left, right] while (left <= right) { // Stores mid value of // left and right int mid = left + (right - left) / 2; // If it is possible to cut woods // into K pieces having length // of each piece equal to mid if (isValid(wood, N, mid, K)) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return right;} // Driver Codepublic static void Main(String[] args){ int []wood = {5, 9, 7}; int N = wood.Length; int K = 4; Console.Write(findMaxLen(wood, N, K));}} // This code is contributed by shikhasingrajput", "e": 6995, "s": 5604, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to check if it is possible // to cut woods into K pieces of // length len function isValid(wood , N , len , K) { // Stores count of pieces // having length equal to K var count = 0; // Traverse wood array for (i = 0; i < N; i++) { // Update count count += parseInt(wood[i] / len); } return count >= K; } // Function to find the maximum value of L function findMaxLen(wood , N , K) { // Stores minimum possible value of L var left = 1; // Stores maximum possible value of L var right = Math.max.apply(Math,wood); // Apply binary search over // the range [left, right] while (left <= right) { // Stores mid value of // left and right var mid = left + (right - left) / 2; // If it is possible to cut woods // into K pieces having length // of each piece equal to mid if (isValid(wood, N, mid, K)) { // Update left left = mid + 1; } else { // Update right right = mid - 1; } } return right; } // Driver Code var wood = [ 5, 9, 7 ]; var N = wood.length; var K = 4; document.write(findMaxLen(wood, N, K)); // This code is contributed by todaysgaurav </script>", "e": 8493, "s": 6995, "text": null }, { "code": null, "e": 8495, "s": 8493, "text": "4" }, { "code": null, "e": 8599, "s": 8497, "text": "Time Complexity: O(N * Log2M), where M is the maximum element of the given arrayAuxiliary Space: O(1)" }, { "code": null, "e": 8614, "s": 8599, "text": "mohit kumar 29" }, { "code": null, "e": 8627, "s": 8614, "text": "princi singh" }, { "code": null, "e": 8644, "s": 8627, "text": "shikhasingrajput" }, { "code": null, "e": 8657, "s": 8644, "text": "todaysgaurav" }, { "code": null, "e": 8679, "s": 8657, "text": "kanaujiyavimleshkumar" }, { "code": null, "e": 8694, "s": 8679, "text": "sagar0719kumar" }, { "code": null, "e": 8708, "s": 8694, "text": "jainlovely450" }, { "code": null, "e": 8715, "s": 8708, "text": "Arrays" }, { "code": null, "e": 8729, "s": 8715, "text": "Binary Search" }, { "code": null, "e": 8738, "s": 8729, "text": "Facebook" }, { "code": null, "e": 8745, "s": 8738, "text": "Google" }, { "code": null, "e": 8767, "s": 8745, "text": "interview-preparation" }, { "code": null, "e": 8774, "s": 8767, "text": "Arrays" }, { "code": null, "e": 8793, "s": 8774, "text": "Divide and Conquer" }, { "code": null, "e": 8803, "s": 8793, "text": "Searching" }, { "code": null, "e": 8810, "s": 8803, "text": "Google" }, { "code": null, "e": 8819, "s": 8810, "text": "Facebook" }, { "code": null, "e": 8826, "s": 8819, "text": "Arrays" }, { "code": null, "e": 8836, "s": 8826, "text": "Searching" }, { "code": null, "e": 8855, "s": 8836, "text": "Divide and Conquer" }, { "code": null, "e": 8869, "s": 8855, "text": "Binary Search" } ]
Python Program to print all permutations of a given string
13 Jan, 2022 A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Source: Mathword(http://mathworld.wolfram.com/Permutation.html) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB Here is a solution that is used as a basis in backtracking. Python3 # Python program to print all permutations# with duplicates alloweddef toString(List): return ''.join(List) # Function to print permutations# of string# This function takes three parameters:# 1. String# 2. Starting index of the string# 3. Ending index of the string.def permute(a, l, r): if l == r: print (toString(a)) else: for i in range(l, r + 1): a[l], a[i] = a[i], a[l] permute(a, l + 1, r) # backtrack a[l], a[i] = a[i], a[l] # Driver codestring = "ABC"n = len(string)a = list(string)permute(a, 0, n-1)# This code is contributed by Bhavya Jain Output: ABC ACB BAC BCA CBA CAB Algorithm Paradigm: Backtracking Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a permutation. Auxiliary Space: O(r – l) Note: The above solution prints duplicate permutations if there are repeating characters in the input string. Please see the below link for a solution that prints only distinct permutations even if there are duplicates in input.Print all distinct permutations of a given string with duplicates. Permutations of a given string using STL Another approach: Python3 # Python program to implement# the above approachdef permute(s, answer): if (len(s) == 0): print(answer, end = " ") return for i in range(len(s)): ch = s[i] left_substr = s[0:i] right_substr = s[i + 1:] rest = left_substr + right_substr permute(rest, answer + ch) # Driver Codeanswer = ""s = input("Enter the string : ")print("All possible strings are : ")permute(s, answer)# This code is contributed by Harshit Srivastava Output: Enter the string : abc All possible strings are : abc acb bac bca cab cba Time Complexity: O(n*n!) The time complexity is the same as the above approach, i.e. there are n! permutations and it requires O(n) time to print a permutation. Auxiliary Space: O(|s|) viditvarshney amartyaghoshgfg Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert string dictionary to dictionary Python program to add two numbers Python Program for Binary Search (Recursive and Iterative) Python Program for factorial of a number Python program to find second largest number in a list Iterate over characters of a string in Python Python program to interchange first and last elements in a list Python | Convert set into a list Appending to list in Python dictionary Python | Convert a list into a tuple
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jan, 2022" }, { "code": null, "e": 262, "s": 54, "text": "A permutation also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. " }, { "code": null, "e": 326, "s": 262, "text": "Source: Mathword(http://mathworld.wolfram.com/Permutation.html)" }, { "code": null, "e": 392, "s": 326, "text": "Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB" }, { "code": null, "e": 452, "s": 392, "text": "Here is a solution that is used as a basis in backtracking." }, { "code": null, "e": 460, "s": 452, "text": "Python3" }, { "code": "# Python program to print all permutations# with duplicates alloweddef toString(List): return ''.join(List) # Function to print permutations# of string# This function takes three parameters:# 1. String# 2. Starting index of the string# 3. Ending index of the string.def permute(a, l, r): if l == r: print (toString(a)) else: for i in range(l, r + 1): a[l], a[i] = a[i], a[l] permute(a, l + 1, r) # backtrack a[l], a[i] = a[i], a[l] # Driver codestring = \"ABC\"n = len(string)a = list(string)permute(a, 0, n-1)# This code is contributed by Bhavya Jain", "e": 1078, "s": 460, "text": null }, { "code": null, "e": 1087, "s": 1078, "text": "Output: " }, { "code": null, "e": 1111, "s": 1087, "text": "ABC\nACB\nBAC\nBCA\nCBA\nCAB" }, { "code": null, "e": 1145, "s": 1111, "text": "Algorithm Paradigm: Backtracking " }, { "code": null, "e": 1256, "s": 1145, "text": "Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a permutation." }, { "code": null, "e": 1282, "s": 1256, "text": "Auxiliary Space: O(r – l)" }, { "code": null, "e": 1618, "s": 1282, "text": "Note: The above solution prints duplicate permutations if there are repeating characters in the input string. Please see the below link for a solution that prints only distinct permutations even if there are duplicates in input.Print all distinct permutations of a given string with duplicates. Permutations of a given string using STL" }, { "code": null, "e": 1636, "s": 1618, "text": "Another approach:" }, { "code": null, "e": 1644, "s": 1636, "text": "Python3" }, { "code": "# Python program to implement# the above approachdef permute(s, answer): if (len(s) == 0): print(answer, end = \" \") return for i in range(len(s)): ch = s[i] left_substr = s[0:i] right_substr = s[i + 1:] rest = left_substr + right_substr permute(rest, answer + ch) # Driver Codeanswer = \"\"s = input(\"Enter the string : \")print(\"All possible strings are : \")permute(s, answer)# This code is contributed by Harshit Srivastava", "e": 2128, "s": 1644, "text": null }, { "code": null, "e": 2136, "s": 2128, "text": "Output:" }, { "code": null, "e": 2215, "s": 2136, "text": "Enter the string : abc\nAll possible strings are : abc acb bac bca cab cba" }, { "code": null, "e": 2376, "s": 2215, "text": "Time Complexity: O(n*n!) The time complexity is the same as the above approach, i.e. there are n! permutations and it requires O(n) time to print a permutation." }, { "code": null, "e": 2400, "s": 2376, "text": "Auxiliary Space: O(|s|)" }, { "code": null, "e": 2414, "s": 2400, "text": "viditvarshney" }, { "code": null, "e": 2430, "s": 2414, "text": "amartyaghoshgfg" }, { "code": null, "e": 2446, "s": 2430, "text": "Python Programs" }, { "code": null, "e": 2544, "s": 2446, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2593, "s": 2544, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 2627, "s": 2593, "text": "Python program to add two numbers" }, { "code": null, "e": 2686, "s": 2627, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 2727, "s": 2686, "text": "Python Program for factorial of a number" }, { "code": null, "e": 2782, "s": 2727, "text": "Python program to find second largest number in a list" }, { "code": null, "e": 2828, "s": 2782, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 2892, "s": 2828, "text": "Python program to interchange first and last elements in a list" }, { "code": null, "e": 2925, "s": 2892, "text": "Python | Convert set into a list" }, { "code": null, "e": 2964, "s": 2925, "text": "Appending to list in Python dictionary" } ]
List View Search list on typing with filter like keyword search using jQuery?
Let’s the following is our input type, wherein the user will search − <input type="text" class="txtInput" id="searchTheKey" placeholder="Enter the keywords to search....."> Now, use hide() and show() to display only relevant search and hide rest. For example, on typing “Ja”, related keywords like “Java” and “JavaScript” should be visible because it begins with “Ja”. Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <label> Enter the keyword.. <input type="text" class="txtInput" id="searchTheKey" placeholder="Enter the keywords to search....."> </label> <ul id="matchKey"> <li id="subjectName">JavaScript</li> <li id="teacherName"><a href="#">John Smith</a></li> <li id="subjectName">Java</li> <li id="teacherName"><a href="#">David Miller</a</li> <li id="subjectName">MongoDB</li> <li id="teacherName"><a href="#">Carol Taylor</a></li> </ul> <script> $("#searchTheKey").on('keyup', function(){ var value = $(this).val().toLowerCase(); $("#matchKey li").each(function () { if ($(this).text().toLowerCase().search(value) > -1) { $(this).show(); $(this).prev('.subjectName').last().show(); } else { $(this).hide(); } }); }) </script> </body> </html> To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor. This will produce the following output − Now, I am entering the only Java and getting the search result. The screenshot is as follows − Look at the above snapshot, remaining list of items are hiding.
[ { "code": null, "e": 1257, "s": 1187, "text": "Let’s the following is our input type, wherein the user will search −" }, { "code": null, "e": 1360, "s": 1257, "text": "<input type=\"text\" class=\"txtInput\" id=\"searchTheKey\" placeholder=\"Enter the keywords to search.....\">" }, { "code": null, "e": 1556, "s": 1360, "text": "Now, use hide() and show() to display only relevant search and hide rest. For example, on\ntyping “Ja”, related keywords like “Java” and “JavaScript” should be visible because it begins\nwith “Ja”." }, { "code": null, "e": 1567, "s": 1556, "text": " Live Demo" }, { "code": null, "e": 2781, "s": 1567, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<label>\nEnter the keyword..\n<input type=\"text\" class=\"txtInput\" id=\"searchTheKey\" placeholder=\"Enter the keywords to search.....\">\n</label>\n<ul id=\"matchKey\">\n<li id=\"subjectName\">JavaScript</li>\n<li id=\"teacherName\"><a href=\"#\">John Smith</a></li>\n<li id=\"subjectName\">Java</li>\n<li id=\"teacherName\"><a href=\"#\">David Miller</a</li>\n<li id=\"subjectName\">MongoDB</li>\n<li id=\"teacherName\"><a href=\"#\">Carol Taylor</a></li>\n</ul>\n<script>\n $(\"#searchTheKey\").on('keyup', function(){\n var value = $(this).val().toLowerCase();\n $(\"#matchKey li\").each(function () {\n if ($(this).text().toLowerCase().search(value) > -1) {\n $(this).show();\n $(this).prev('.subjectName').last().show();\n } else {\n $(this).hide();\n }\n });\n })\n</script>\n</body>\n</html>" }, { "code": null, "e": 2943, "s": 2781, "text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor." }, { "code": null, "e": 2984, "s": 2943, "text": "This will produce the following output −" }, { "code": null, "e": 3079, "s": 2984, "text": "Now, I am entering the only Java and getting the search result. The screenshot is as follows −" }, { "code": null, "e": 3143, "s": 3079, "text": "Look at the above snapshot, remaining list of items are hiding." } ]
How to darken an Image using CSS ?
30 Jul, 2021 Method 1: Using the filter property: The filter property is used to apply various graphical effects to an element. The brightness() function can be used as a value to apply a linear multiplier to make it appear darker or lighter than the original. To make an image darker, any value below 100% could be used to darken the image by that percentage. Syntax: filter: brightness(50%) Example: <!DOCTYPE html><html> <head> <title> How to Darken an Image using CSS? </title> <style> .darkened-image { filter: brightness(50%); background-image: url('https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png'); height: 94px; width: 120px; } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to Darken an Image with CSS? </b> <p> The image below is the normal image: </p> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png"> <p> The image below is the darkened image: </p> <div class="darkened-image"></div></body> </html> Output: Method 2: Using the background-image property with a linear gradient: The background-image property in CSS supports the use of multiple backgrounds that are layered on top of each other. Using the linear-gradient property, a black colored background is used as the front layer and the image to be darkened is used as the back layer. The order of the background-image property specifies the front layer to be specified first before defining the layers at the back.The opacity of the black gradient can be changed to control the amount of darkening. This can be used accordingly to darken the image as required. Syntax: background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("url_of_image")) Example: Using an opacity of 0.5 of the background gradient to darken the image. <!DOCTYPE html><html> <head> <title> How to Darken an Image with CSS? </title> <style> .darkened-image { background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png'); height: 94px; width: 120px; } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b> How to Darken an Image with CSS? </b> <p> The image below is the normal image: </p> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png"> <p> The image below is the darkened image: </p> <div class="darkened-image"></div></body> </html> Output: 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. CSS-Misc Picked CSS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jul, 2021" }, { "code": null, "e": 376, "s": 28, "text": "Method 1: Using the filter property: The filter property is used to apply various graphical effects to an element. The brightness() function can be used as a value to apply a linear multiplier to make it appear darker or lighter than the original. To make an image darker, any value below 100% could be used to darken the image by that percentage." }, { "code": null, "e": 384, "s": 376, "text": "Syntax:" }, { "code": null, "e": 408, "s": 384, "text": "filter: brightness(50%)" }, { "code": null, "e": 417, "s": 408, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to Darken an Image using CSS? </title> <style> .darkened-image { filter: brightness(50%); background-image: url('https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png'); height: 94px; width: 120px; } </style></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to Darken an Image with CSS? </b> <p> The image below is the normal image: </p> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png\"> <p> The image below is the darkened image: </p> <div class=\"darkened-image\"></div></body> </html>", "e": 1231, "s": 417, "text": null }, { "code": null, "e": 1239, "s": 1231, "text": "Output:" }, { "code": null, "e": 1849, "s": 1239, "text": "Method 2: Using the background-image property with a linear gradient: The background-image property in CSS supports the use of multiple backgrounds that are layered on top of each other. Using the linear-gradient property, a black colored background is used as the front layer and the image to be darkened is used as the back layer. The order of the background-image property specifies the front layer to be specified first before defining the layers at the back.The opacity of the black gradient can be changed to control the amount of darkening. This can be used accordingly to darken the image as required." }, { "code": null, "e": 1857, "s": 1849, "text": "Syntax:" }, { "code": null, "e": 1976, "s": 1857, "text": "background-image: linear-gradient(rgba(0, 0, 0, 0.5),\n rgba(0, 0, 0, 0.5)), url(\"url_of_image\"))" }, { "code": null, "e": 2057, "s": 1976, "text": "Example: Using an opacity of 0.5 of the background gradient to darken the image." }, { "code": "<!DOCTYPE html><html> <head> <title> How to Darken an Image with CSS? </title> <style> .darkened-image { background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png'); height: 94px; width: 120px; } </style></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b> How to Darken an Image with CSS? </b> <p> The image below is the normal image: </p> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png\"> <p> The image below is the darkened image: </p> <div class=\"darkened-image\"></div></body> </html>", "e": 2905, "s": 2057, "text": null }, { "code": null, "e": 2913, "s": 2905, "text": "Output:" }, { "code": null, "e": 3099, "s": 2913, "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": 3108, "s": 3099, "text": "CSS-Misc" }, { "code": null, "e": 3115, "s": 3108, "text": "Picked" }, { "code": null, "e": 3119, "s": 3115, "text": "CSS" }, { "code": null, "e": 3136, "s": 3119, "text": "Web Technologies" }, { "code": null, "e": 3163, "s": 3136, "text": "Web technologies Questions" } ]
How to extract the last row from list of a data frame in R?
Suppose we have two frames each having 5 columns that are stored in a list in R and we want to extract the last row from each data frame then we can use the lapply function. For example, if we have a list called LIST that contains the data frames described above then we can extract the last row from each data frame using the command lapply(LIST,tail,1). Consider the below list of data frames − Live Demo > x1<-rpois(20,5) > x2<-rpois(20,5) > df1<-data.frame(x1,x2) > y1<-rnorm(20) > y2<-rnorm(20) > df2<-data.frame(y1,y2) > z1<-runif(20,2,5) > z2<-runif(20,2,5) > df3<-data.frame(z1,z2) > List<-list(df1,df2,df3) > List [[1]] x1 x2 1 6 5 2 6 5 3 1 6 4 3 7 5 3 2 6 1 5 7 2 4 8 4 9 9 3 7 10 6 4 11 3 3 12 7 6 13 5 4 14 6 3 15 3 7 16 6 3 17 6 4 18 6 2 19 2 5 20 4 2 [[2]] y1 y2 1 -0.122804668 -1.6121924 2 0.368791187 -0.1544747 3 0.609177511 -0.1826137 4 -1.203014907 0.2230573 5 0.635002355 -1.8070089 6 1.859925346 -0.7883239 7 -0.031825058 -0.3458682 8 -2.096244574 0.9227411 9 -1.580421379 1.2784456 10 1.110385489 -0.2452274 11 0.336772170 -0.8106806 12 -0.957564919 0.3096939 13 -0.686361808 -0.9769511 14 -1.828680903 -1.3923749 15 -1.455614755 0.6422880 16 1.300948577 1.3421038 17 -0.002059289 0.3392104 18 0.577102561 0.8994493 19 -0.908456903 0.5898572 20 1.085195168 0.5538230 [[3]] z1 z2 1 2.890933 4.918197 2 3.810215 3.869794 3 4.229115 2.709872 4 2.418676 4.464096 5 3.854820 4.876632 6 4.585025 4.080327 7 2.982565 3.604979 8 3.060728 4.523820 9 3.173745 2.203814 10 2.814365 2.806997 11 3.115635 3.032836 12 3.464063 3.498520 13 4.565387 2.021247 14 3.150363 3.273335 15 3.371670 4.497002 16 3.291873 4.102787 17 2.930217 3.962004 18 4.222483 4.428542 19 4.078323 3.199733 20 2.430997 4.328706 Extracting the last row of data frames in List − > lapply(List,tail,1) [[1]] x1 x2 20 4 2 [[2]] y1 y2 20 1.085195 0.553823 [[3]] z1 z2 20 2.430997 4.328706
[ { "code": null, "e": 1543, "s": 1187, "text": "Suppose we have two frames each having 5 columns that are stored in a list in R and we want to extract the last row from each data frame then we can use the lapply function. For example, if we have a list called LIST that contains the data frames described above then we can extract the last row from each data frame using the command lapply(LIST,tail,1)." }, { "code": null, "e": 1584, "s": 1543, "text": "Consider the below list of data frames −" }, { "code": null, "e": 1594, "s": 1584, "text": "Live Demo" }, { "code": null, "e": 1810, "s": 1594, "text": "> x1<-rpois(20,5)\n> x2<-rpois(20,5)\n> df1<-data.frame(x1,x2)\n> y1<-rnorm(20)\n> y2<-rnorm(20)\n> df2<-data.frame(y1,y2)\n> z1<-runif(20,2,5)\n> z2<-runif(20,2,5)\n> df3<-data.frame(z1,z2)\n> List<-list(df1,df2,df3)\n> List" }, { "code": null, "e": 3029, "s": 1810, "text": "[[1]]\n x1 x2\n1 6 5\n2 6 5\n3 1 6\n4 3 7\n5 3 2\n6 1 5\n7 2 4\n8 4 9\n9 3 7\n10 6 4\n11 3 3\n12 7 6\n13 5 4\n14 6 3\n15 3 7\n16 6 3\n17 6 4\n18 6 2\n19 2 5\n20 4 2\n \n[[2]]\n y1 y2\n1 -0.122804668 -1.6121924\n2 0.368791187 -0.1544747\n3 0.609177511 -0.1826137\n4 -1.203014907 0.2230573\n5 0.635002355 -1.8070089\n6 1.859925346 -0.7883239\n7 -0.031825058 -0.3458682\n8 -2.096244574 0.9227411\n9 -1.580421379 1.2784456\n10 1.110385489 -0.2452274\n11 0.336772170 -0.8106806\n12 -0.957564919 0.3096939\n13 -0.686361808 -0.9769511\n14 -1.828680903 -1.3923749\n15 -1.455614755 0.6422880\n16 1.300948577 1.3421038\n17 -0.002059289 0.3392104\n18 0.577102561 0.8994493\n19 -0.908456903 0.5898572\n20 1.085195168 0.5538230\n \n[[3]]\n z1 z2\n1 2.890933 4.918197\n2 3.810215 3.869794\n3 4.229115 2.709872\n4 2.418676 4.464096\n5 3.854820 4.876632\n6 4.585025 4.080327\n7 2.982565 3.604979\n8 3.060728 4.523820\n9 3.173745 2.203814\n10 2.814365 2.806997\n11 3.115635 3.032836\n12 3.464063 3.498520\n13 4.565387 2.021247\n14 3.150363 3.273335\n15 3.371670 4.497002\n16 3.291873 4.102787\n17 2.930217 3.962004\n18 4.222483 4.428542\n19 4.078323 3.199733\n20 2.430997 4.328706" }, { "code": null, "e": 3078, "s": 3029, "text": "Extracting the last row of data frames in List −" }, { "code": null, "e": 3100, "s": 3078, "text": "> lapply(List,tail,1)" }, { "code": null, "e": 3224, "s": 3100, "text": "[[1]]\n x1 x2\n20 4 2\n \n[[2]]\n y1 y2\n20 1.085195 0.553823\n \n[[3]]\n z1 z2\n20 2.430997 4.328706" } ]
Program for N-th term of Geometric Progression series
25 Feb, 2021 Given first term (a), common ratio (r) and a integer N of the Geometric Progression series, the task is to find Nth term of the series.Examples : Input : a = 2 r = 2, N = 4 Output : The 4th term of the series is : 16 Input : a = 2 r = 3, N = 5 Output : The 5th term of the series is : 162 Approach: We know the Geometric Progression series is like = 2, 4, 8, 16, 32 .... ... In this series 2 is the stating term of the series . Common ratio = 4 / 2 = 2 (ratio common in the series). so we can write the series as :t1 = a1 t2 = a1 * r(2-1) t3 = a1 * r(3-1) t4 = a1 * r(4-1) . . . . tN = a1 * r(N-1) To find the Nth term in the Geometric Progression series we use the simple formula . TN = a1 * r(N-1) C++ Java Python3 C# PHP Javascript // CPP Program to find nth term of// geometric progression#include <bits/stdc++.h> using namespace std; int Nth_of_GP(int a, int r, int N){ // using formula to find // the Nth term // TN = a1 * r(N-1) return( a * (int)(pow(r, N - 1)) ); } // Driver codeint main(){ // starting number int a = 2; // Common ratio int r = 3; // N th term to be find int N = 5; // Display the output cout << "The "<< N <<"th term of the series is : " << Nth_of_GP(a, r, N); return 0;} // java program to find nth term// of geometric progressionimport java.io.*;import java.lang.*; class GFG{ public static int Nth_of_GP(int a, int r, int N) { // using formula to find the Nth // term TN = a1 * r(N-1) return ( a * (int)(Math.pow(r, N - 1)) ); } // Driver code public static void main(String[] args) { // starting number int a = 2; // Common ratio int r = 3; // N th term to be find int N = 5; // Display the output System.out.print("The "+ N + "th term of the" + " series is : " + Nth_of_GP(a, r, N)); }} # Python3 Program to find nth# term of geometric progressionimport math def Nth_of_GP(a, r, N): # Using formula to find the Nth # term TN = a1 * r(N-1) return( a * (int)(math.pow(r, N - 1)) ) # Driver codea = 2 # Starting numberr = 3 # Common ratioN = 5 # N th term to be find print("The", N, "th term of the series is :", Nth_of_GP(a, r, N)) # This code is contributed by Smitha Dinesh Semwal // C# program to find nth term// of geometric progressionusing System; class GFG{ public static int Nth_of_GP(int a, int r, int N) { // using formula to find the Nth // term TN = a1 * r(N-1) return ( a * (int)(Math.Pow(r, N - 1)) ); } // Driver code public static void Main() { // starting number int a = 2; // Common ratio int r = 3; // N th term to be find int N = 5; // Display the output Console.Write("The "+ N + "th term of the" + " series is : " + Nth_of_GP(a, r, N)); }} // This code is contributed by vt_m <?php// PHP Program to find nth term of// geometric progression function Nth_of_GP($a, $r, $N){ // using formula to find // the Nth term TN = a1 * r(N-1) return( $a * (int)(pow($r, $N - 1)) ); } // Driver code // starting number$a = 2; // Common ratio$r = 3; // N th term to be find$N = 5; // Display the outputecho("The " . $N . "th term of the series is : " . Nth_of_GP($a, $r, $N)); // This code is contributed by Ajit.?> <script> // JavaScript Program to find nth term of // geometric progression function Nth_of_GP(a, r, N) { // using formula to find // the Nth term // TN = a1 * r(N-1) return( a * Math.floor(Math.pow(r, N - 1)) ); } // Driver code // starting number let a = 2; // Common ratio let r = 3; // N th term to be find let N = 5; // Display the output document.write("The "+ N +"th term of the series is : " + Nth_of_GP(a, r, N)); // This code is contributed by Surbhi Tyagi </script> Output : The 5th term of the series is : 162 jit_t kishoredas surbhityagi15 series Mathematical School Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Find minimum number of coins that make a given value Algorithm to solve Rubik's Cube Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Feb, 2021" }, { "code": null, "e": 200, "s": 52, "text": "Given first term (a), common ratio (r) and a integer N of the Geometric Progression series, the task is to find Nth term of the series.Examples : " }, { "code": null, "e": 344, "s": 200, "text": "Input : a = 2 r = 2, N = 4\nOutput :\nThe 4th term of the series is : 16\n\nInput : a = 2 r = 3, N = 5\nOutput :\nThe 5th term of the series is : 162" }, { "code": null, "e": 356, "s": 344, "text": "Approach: " }, { "code": null, "e": 655, "s": 356, "text": "We know the Geometric Progression series is like = 2, 4, 8, 16, 32 .... ... In this series 2 is the stating term of the series . Common ratio = 4 / 2 = 2 (ratio common in the series). so we can write the series as :t1 = a1 t2 = a1 * r(2-1) t3 = a1 * r(3-1) t4 = a1 * r(4-1) . . . . tN = a1 * r(N-1)" }, { "code": null, "e": 742, "s": 655, "text": "To find the Nth term in the Geometric Progression series we use the simple formula . " }, { "code": null, "e": 759, "s": 742, "text": "TN = a1 * r(N-1)" }, { "code": null, "e": 767, "s": 763, "text": "C++" }, { "code": null, "e": 772, "s": 767, "text": "Java" }, { "code": null, "e": 780, "s": 772, "text": "Python3" }, { "code": null, "e": 783, "s": 780, "text": "C#" }, { "code": null, "e": 787, "s": 783, "text": "PHP" }, { "code": null, "e": 798, "s": 787, "text": "Javascript" }, { "code": "// CPP Program to find nth term of// geometric progression#include <bits/stdc++.h> using namespace std; int Nth_of_GP(int a, int r, int N){ // using formula to find // the Nth term // TN = a1 * r(N-1) return( a * (int)(pow(r, N - 1)) ); } // Driver codeint main(){ // starting number int a = 2; // Common ratio int r = 3; // N th term to be find int N = 5; // Display the output cout << \"The \"<< N <<\"th term of the series is : \" << Nth_of_GP(a, r, N); return 0;}", "e": 1329, "s": 798, "text": null }, { "code": "// java program to find nth term// of geometric progressionimport java.io.*;import java.lang.*; class GFG{ public static int Nth_of_GP(int a, int r, int N) { // using formula to find the Nth // term TN = a1 * r(N-1) return ( a * (int)(Math.pow(r, N - 1)) ); } // Driver code public static void main(String[] args) { // starting number int a = 2; // Common ratio int r = 3; // N th term to be find int N = 5; // Display the output System.out.print(\"The \"+ N + \"th term of the\" + \" series is : \" + Nth_of_GP(a, r, N)); }}", "e": 2044, "s": 1329, "text": null }, { "code": "# Python3 Program to find nth# term of geometric progressionimport math def Nth_of_GP(a, r, N): # Using formula to find the Nth # term TN = a1 * r(N-1) return( a * (int)(math.pow(r, N - 1)) ) # Driver codea = 2 # Starting numberr = 3 # Common ratioN = 5 # N th term to be find print(\"The\", N, \"th term of the series is :\", Nth_of_GP(a, r, N)) # This code is contributed by Smitha Dinesh Semwal", "e": 2484, "s": 2044, "text": null }, { "code": "// C# program to find nth term// of geometric progressionusing System; class GFG{ public static int Nth_of_GP(int a, int r, int N) { // using formula to find the Nth // term TN = a1 * r(N-1) return ( a * (int)(Math.Pow(r, N - 1)) ); } // Driver code public static void Main() { // starting number int a = 2; // Common ratio int r = 3; // N th term to be find int N = 5; // Display the output Console.Write(\"The \"+ N + \"th term of the\" + \" series is : \" + Nth_of_GP(a, r, N)); }} // This code is contributed by vt_m", "e": 3204, "s": 2484, "text": null }, { "code": "<?php// PHP Program to find nth term of// geometric progression function Nth_of_GP($a, $r, $N){ // using formula to find // the Nth term TN = a1 * r(N-1) return( $a * (int)(pow($r, $N - 1)) ); } // Driver code // starting number$a = 2; // Common ratio$r = 3; // N th term to be find$N = 5; // Display the outputecho(\"The \" . $N . \"th term of the series is : \" . Nth_of_GP($a, $r, $N)); // This code is contributed by Ajit.?>", "e": 3665, "s": 3204, "text": null }, { "code": "<script> // JavaScript Program to find nth term of // geometric progression function Nth_of_GP(a, r, N) { // using formula to find // the Nth term // TN = a1 * r(N-1) return( a * Math.floor(Math.pow(r, N - 1)) ); } // Driver code // starting number let a = 2; // Common ratio let r = 3; // N th term to be find let N = 5; // Display the output document.write(\"The \"+ N +\"th term of the series is : \" + Nth_of_GP(a, r, N)); // This code is contributed by Surbhi Tyagi </script>", "e": 4238, "s": 3665, "text": null }, { "code": null, "e": 4249, "s": 4238, "text": "Output : " }, { "code": null, "e": 4285, "s": 4249, "text": "The 5th term of the series is : 162" }, { "code": null, "e": 4293, "s": 4287, "text": "jit_t" }, { "code": null, "e": 4304, "s": 4293, "text": "kishoredas" }, { "code": null, "e": 4318, "s": 4304, "text": "surbhityagi15" }, { "code": null, "e": 4325, "s": 4318, "text": "series" }, { "code": null, "e": 4338, "s": 4325, "text": "Mathematical" }, { "code": null, "e": 4357, "s": 4338, "text": "School Programming" }, { "code": null, "e": 4370, "s": 4357, "text": "Mathematical" }, { "code": null, "e": 4377, "s": 4370, "text": "series" }, { "code": null, "e": 4475, "s": 4377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4499, "s": 4475, "text": "Merge two sorted arrays" }, { "code": null, "e": 4520, "s": 4499, "text": "Operators in C / C++" }, { "code": null, "e": 4534, "s": 4520, "text": "Prime Numbers" }, { "code": null, "e": 4587, "s": 4534, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 4619, "s": 4587, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 4637, "s": 4619, "text": "Python Dictionary" }, { "code": null, "e": 4662, "s": 4637, "text": "Reverse a string in Java" }, { "code": null, "e": 4678, "s": 4662, "text": "Arrays in C/C++" }, { "code": null, "e": 4701, "s": 4678, "text": "Introduction To PYTHON" } ]
Tailwind CSS Resize
23 Mar, 2022 This class accepts lots of value in tailwind CSS in which all the properties are covered as a class form. This class is used to resize the element according to user requirements. It does not apply to inline elements or to block elements where overflow is visible. In CSS, we do that by using the CSS resize property. Resize resize-none: This class is to prevent an element from being resizable. resize-y: This class is to make an element vertically resizable. resize-x: This class is to make an element horizontally resizable. resize: This class is to make an element horizontally and vertically resizable. Syntax: <element class="pointer-{axis-boolean}">...</element> Example: HTML <!DOCTYPE html><html><head> <link href= "https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Resize Class</b> <div id="main" class="p-2 justify-around ml-32 h-26 w-2/3 flex items-stretch bg-green-200 border-solid border-4 border-green-900 gap-4"> <textarea class="resize border rounded-md w-24 h-12"></textarea> <textarea class="resize-y border rounded-md w-24 h-12"></textarea> <textarea class="resize-x border rounded-md w-24 h-12"></textarea> <textarea class="resize-none border rounded-md w-24 h-12"></textarea> </div> </body> </html> Output: Tailwind CSS resize class surinderdawra388 Tailwind CSS Tailwind-Interactivity CSS Web Technologies 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Mar, 2022" }, { "code": null, "e": 346, "s": 28, "text": "This class accepts lots of value in tailwind CSS in which all the properties are covered as a class form. This class is used to resize the element according to user requirements. It does not apply to inline elements or to block elements where overflow is visible. In CSS, we do that by using the CSS resize property. " }, { "code": null, "e": 353, "s": 346, "text": "Resize" }, { "code": null, "e": 424, "s": 353, "text": "resize-none: This class is to prevent an element from being resizable." }, { "code": null, "e": 489, "s": 424, "text": "resize-y: This class is to make an element vertically resizable." }, { "code": null, "e": 556, "s": 489, "text": "resize-x: This class is to make an element horizontally resizable." }, { "code": null, "e": 636, "s": 556, "text": "resize: This class is to make an element horizontally and vertically resizable." }, { "code": null, "e": 644, "s": 636, "text": "Syntax:" }, { "code": null, "e": 698, "s": 644, "text": "<element class=\"pointer-{axis-boolean}\">...</element>" }, { "code": null, "e": 707, "s": 698, "text": "Example:" }, { "code": null, "e": 712, "s": 707, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link href= \"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Resize Class</b> <div id=\"main\" class=\"p-2 justify-around ml-32 h-26 w-2/3 flex items-stretch bg-green-200 border-solid border-4 border-green-900 gap-4\"> <textarea class=\"resize border rounded-md w-24 h-12\"></textarea> <textarea class=\"resize-y border rounded-md w-24 h-12\"></textarea> <textarea class=\"resize-x border rounded-md w-24 h-12\"></textarea> <textarea class=\"resize-none border rounded-md w-24 h-12\"></textarea> </div> </body> </html>", "e": 1640, "s": 712, "text": null }, { "code": null, "e": 1648, "s": 1640, "text": "Output:" }, { "code": null, "e": 1674, "s": 1648, "text": "Tailwind CSS resize class" }, { "code": null, "e": 1691, "s": 1674, "text": "surinderdawra388" }, { "code": null, "e": 1704, "s": 1691, "text": "Tailwind CSS" }, { "code": null, "e": 1727, "s": 1704, "text": "Tailwind-Interactivity" }, { "code": null, "e": 1731, "s": 1727, "text": "CSS" }, { "code": null, "e": 1748, "s": 1731, "text": "Web Technologies" }, { "code": null, "e": 1846, "s": 1748, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1894, "s": 1846, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1956, "s": 1894, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2006, "s": 1956, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2064, "s": 2006, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 2114, "s": 2064, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2176, "s": 2114, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2209, "s": 2176, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2270, "s": 2209, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2320, "s": 2270, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Regular Expression in Python with Examples | Set 1
08 Jun, 2022 A Regular Expressions (RegEx) is a special sequence of characters that uses a search pattern to find a string or set of strings. It can detect the presence or absence of a text by matching it with a particular pattern, and also can split a pattern into one or more sub-patterns. Python provides a re module that supports the use of regex in Python. Its primary function is to offer a search, where it takes a regular expression and a string. Here, it either returns the first match or else none. Example: Python3 import re s = 'GeeksforGeeks: A computer science portal for geeks' match = re.search(r'portal', s) print('Start Index:', match.start())print('End Index:', match.end()) Start Index: 34 End Index: 40 The above code gives the starting index and the ending index of the string portal. Note: Here r character (r’portal’) stands for raw, not regex. The raw string is slightly different from a regular string, it won’t interpret the \ character as an escape character. This is because the regular expression engine uses \ character for its own escaping purpose. Before starting with the Python regex module let’s see how to actually write regex using metacharacters or special sequences. To understand the RE analogy, MetaCharacters are useful, important, and will be used in functions of module re. Below is the list of metacharacters. Let’s discuss each of these metacharacters in detail The backslash (\) makes sure that the character is not treated in a special way. This can be considered a way of escaping metacharacters. For example, if you want to search for the dot(.) in the string then you will find that dot(.) will be treated as a special character as is one of the metacharacters (as shown in the above table). So for this case, we will use the backslash(\) just before the dot(.) so that it will lose its specialty. See the below example for a better understanding. Example: Python3 import re s = 'geeks.forgeeks' # without using \match = re.search(r'.', s)print(match) # using \match = re.search(r'\.', s)print(match) <_sre.SRE_Match object; span=(0, 1), match='g'> <_sre.SRE_Match object; span=(5, 6), match='.'> Square Brackets ([]) represent a character class consisting of a set of characters that we wish to match. For example, the character class [abc] will match any single a, b, or c. We can also specify a range of characters using – inside the square brackets. For example, [0, 3] is sample as [0123] [a-c] is same as [abc] We can also invert the character class using the caret(^) symbol. For example, [^0-3] means any number except 0, 1, 2, or 3 [^a-c] means any character except a, b, or c Caret (^) symbol matches the beginning of the string i.e. checks whether the string starts with the given character(s) or not. For example – ^g will check if the string starts with g such as geeks, globe, girl, g, etc. ^ge will check if the string starts with ge such as geeks, geeksforgeeks, etc. Dollar($) symbol matches the end of the string i.e checks whether the string ends with the given character(s) or not. For example – s$ will check for the string that ends with a such as geeks, ends, s, etc. ks$ will check for the string that ends with ks such as geeks, geeksforgeeks, ks, etc. Dot(.) symbol matches only a single character except for the newline character (\n). For example – a.b will check for the string that contains any character at the place of the dot such as acb, acbd, abbb, etc .. will check if the string contains at least 2 characters Or symbol works as the or operator meaning it checks whether the pattern before or after the or symbol is present in the string or not. For example – a|b will match any string that contains a or b such as acd, bcd, abcd, etc. Question mark(?) checks if the string before the question mark in the regex occurs at least once or not at all. For example – ab?c will be matched for the string ac, acb, dabc but will not be matched for abbc because there are two b. Similarly, it will not be matched for abdc because b is not followed by c. Star (*) symbol matches zero or more occurrences of the regex preceding the * symbol. For example – ab*c will be matched for the string ac, abc, abbbc, dabc, etc. but will not be matched for abdc because b is not followed by c. Plus (+) symbol matches one or more occurrences of the regex preceding the + symbol. For example – ab+c will be matched for the string abc, abbc, dabc, but will not be matched for ac, abdc because there is no b in ac and b is not followed by c in abdc. Braces match any repetitions preceding regex from m to n both inclusive. For example – a{2, 4} will be matched for the string aaab, baaaac, gaad, but will not be matched for strings like abc, bc because there is only one a or no a in both the cases. Group symbol is used to group sub-patterns. For example – (a|b)cd will match for strings like acd, abcd, gacd, etc. Special sequences do not match for the actual character in the string instead it tells the specific location in the search string where the match must occur. It makes it easier to write commonly used patterns. Python has a module named re that is used for regular expressions in Python. We can import this module by using the import statement. Example: Importing re module in Python Python3 import re Let’s see various functions provided by this module to work with regex in Python. Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. Example: Finding all occurrences of a pattern Python3 # A Python program to demonstrate working of# findall()import re # A sample text string where regular expression# is searched.string = """Hello my Number is 123456789 and my friend's number is 987654321""" # A sample regular expression to find digits.regex = '\d+' match = re.findall(regex, string)print(match) # This example is contributed by Ayush Saluja. ['123456789', '987654321'] Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions. Example 1: Python # Module Regular Expression is imported# using __import__().import re # compile() creates regular expression# character class [a-e],# which is equivalent to [abcde].# class [abcde] will match with string with# 'a', 'b', 'c', 'd', 'e'.p = re.compile('[a-e]') # findall() searches for the Regular Expression# and return a list upon findingprint(p.findall("Aye, said Mr. Gibenson Stark")) Output: ['e', 'a', 'd', 'b', 'e', 'a'] Understanding the Output: First occurrence is ‘e’ in “Aye” and not ‘A’, as it is Case Sensitive. Next Occurrence is ‘a’ in “said”, then ‘d’ in “said”, followed by ‘b’ and ‘e’ in “Gibenson”, the Last ‘a’ matches with “Stark”. Metacharacter backslash ‘\’ has a very important role as it signals various sequences. If the backslash is to be used without its special meaning as metacharacter, use’\\’ Example 2: Set class [\s,.] will match any whitespace character, ‘,’, or, ‘.’ . Python import re # \d is equivalent to [0-9].p = re.compile('\d')print(p.findall("I went to him at 11 A.M. on 4th July 1886")) # \d+ will match a group on [0-9], group# of one or greater sizep = re.compile('\d+')print(p.findall("I went to him at 11 A.M. on 4th July 1886")) Output: ['1', '1', '4', '1', '8', '8', '6'] ['11', '4', '1886'] Example 3: Python import re # \w is equivalent to [a-zA-Z0-9_].p = re.compile('\w')print(p.findall("He said * in some_lang.")) # \w+ matches to group of alphanumeric character.p = re.compile('\w+')print(p.findall("I went to him at 11 A.M., he \said *** in some_language.")) # \W matches to non alphanumeric characters.p = re.compile('\W')print(p.findall("he said *** in some_language.")) Output: ['H', 'e', 's', 'a', 'i', 'd', 'i', 'n', 's', 'o', 'm', 'e', '_', 'l', 'a', 'n', 'g'] ['I', 'went', 'to', 'him', 'at', '11', 'A', 'M', 'he', 'said', 'in', 'some_language'] [' ', ' ', '*', '*', '*', ' ', ' ', '.'] Example 4: Python import re # '*' replaces the no. of occurrence# of a character.p = re.compile('ab*')print(p.findall("ababbaabbb")) Output: ['ab', 'abb', 'a', 'abbb'] Understanding the Output: Our RE is ab*, which ‘a’ accompanied by any no. of ‘b’s, starting from 0. Output ‘ab’, is valid because of single ‘a’ accompanied by single ‘b’. Output ‘abb’, is valid because of single ‘a’ accompanied by 2 ‘b’. Output ‘a’, is valid because of single ‘a’ accompanied by 0 ‘b’. Output ‘abbb’, is valid because of single ‘a’ accompanied by 3 ‘b’. Split string by the occurrences of a character or a pattern, upon finding that pattern, the remaining characters from the string are returned as part of the resulting list. Syntax : re.split(pattern, string, maxsplit=0, flags=0) The First parameter, pattern denotes the regular expression, string is the given string in which pattern will be searched for and in which splitting occurs, maxsplit if not provided is considered to be zero ‘0’, and if any nonzero value is provided, then at most that many splits occur. If maxsplit = 1, then the string will split once only, resulting in a list of length 2. The flags are very useful and can help to shorten code, they are not necessary parameters, eg: flags = re.IGNORECASE, in this split, the case, i.e. the lowercase or the uppercase will be ignored. Example 1: Python from re import split # '\W+' denotes Non-Alphanumeric Characters# or group of characters Upon finding ','# or whitespace ' ', the split(), splits the# string from that pointprint(split('\W+', 'Words, words , Words'))print(split('\W+', "Word's words Words")) # Here ':', ' ' ,',' are not AlphaNumeric thus,# the point where splitting occursprint(split('\W+', 'On 12th Jan 2016, at 11:02 AM')) # '\d+' denotes Numeric Characters or group of# characters Splitting occurs at '12', '2016',# '11', '02' onlyprint(split('\d+', 'On 12th Jan 2016, at 11:02 AM')) Output: ['Words', 'words', 'Words'] ['Word', 's', 'words', 'Words'] ['On', '12th', 'Jan', '2016', 'at', '11', '02', 'AM'] ['On ', 'th Jan ', ', at ', ':', ' AM'] Example 2: Python import re # Splitting will occurs only once, at# '12', returned list will have length 2print(re.split('\d+', 'On 12th Jan 2016, at 11:02 AM', 1)) # 'Boy' and 'boy' will be treated same when# flags = re.IGNORECASEprint(re.split('[a-f]+', 'Aey, Boy oh boy, come here', flags=re.IGNORECASE))print(re.split('[a-f]+', 'Aey, Boy oh boy, come here')) Output: ['On ', 'th Jan 2016, at 11:02 AM'] ['', 'y, ', 'oy oh ', 'oy, ', 'om', ' h', 'r', ''] ['A', 'y, Boy oh ', 'oy, ', 'om', ' h', 'r', ''] The ‘sub’ in the function stands for SubString, a certain regular expression pattern is searched in the given string(3rd parameter), and upon finding the substring pattern is replaced by repl(2nd parameter), count checks and maintains the number of times this occurs. Syntax: re.sub(pattern, repl, string, count=0, flags=0) Example 1: Python import re # Regular Expression pattern 'ub' matches the# string at "Subject" and "Uber". As the CASE# has been ignored, using Flag, 'ub' should# match twice with the string Upon matching,# 'ub' is replaced by '~*' in "Subject", and# in "Uber", 'Ub' is replaced.print(re.sub('ub', '~*', 'Subject has Uber booked already', flags=re.IGNORECASE)) # Consider the Case Sensitivity, 'Ub' in# "Uber", will not be replaced.print(re.sub('ub', '~*', 'Subject has Uber booked already')) # As count has been given value 1, the maximum# times replacement occurs is 1print(re.sub('ub', '~*', 'Subject has Uber booked already', count=1, flags=re.IGNORECASE)) # 'r' before the pattern denotes RE, \s is for# start and end of a String.print(re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)) Output S~*ject has ~*er booked already S~*ject has Uber booked already S~*ject has Uber booked already Baked Beans & Spam subn() is similar to sub() in all ways, except in its way of providing output. It returns a tuple with a count of the total of replacement and the new string rather than just the string. Syntax: re.subn(pattern, repl, string, count=0, flags=0) Example: Python import re print(re.subn('ub', '~*', 'Subject has Uber booked already')) t = re.subn('ub', '~*', 'Subject has Uber booked already', flags=re.IGNORECASE)print(t)print(len(t)) # This will give same output as sub() would haveprint(t[0]) Output ('S~*ject has Uber booked already', 1) ('S~*ject has ~*er booked already', 2) Length of Tuple is: 2 S~*ject has ~*er booked already Returns string with all non-alphanumerics backslashed, this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. Syntax: re.escape(string) Example: Python import re # escape() returns a string with BackSlash '\',# before every Non-Alphanumeric Character# In 1st case only ' ', is not alphanumeric# In 2nd case, ' ', caret '^', '-', '[]', '\'# are not alphanumericprint(re.escape("This is Awesome even 1 AM"))print(re.escape("I Asked what is this [a-9], he said \t ^WoW")) This\ is\ Awesome\ even\ 1\ AM I\ Asked\ what\ is\ this\ \[a\-9\]\,\ he\ said\ \ \ \^WoW This method either returns None (if the pattern doesn’t match), or a re.MatchObject contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. Example: Searching for an occurrence of the pattern Python3 # A Python program to demonstrate working of re.match().import re # Lets use a regular expression to match a date string# in the form of Month name followed by day numberregex = r"([a-zA-Z]+) (\d+)" match = re.search(regex, "I was born on June 24") if match != None: # We reach here when the expression "([a-zA-Z]+) (\d+)" # matches the date string. # This will print [14, 21), since it matches at index 14 # and ends at 21. print ("Match at index %s, %s" % (match.start(), match.end())) # We us group() method to get all the matches and # captured groups. The groups contain the matched values. # In particular: # match.group(0) always returns the fully matched string # match.group(1) match.group(2), ... return the capture # groups in order from left to right in the input string # match.group() is equivalent to match.group(0) # So this will print "June 24" print ("Full match: %s" % (match.group(0))) # So this will print "June" print ("Month: %s" % (match.group(1))) # So this will print "24" print ("Day: %s" % (match.group(2))) else: print ("The regex pattern does not match.") Match at index 14, 21 Full match: June 24 Month: June Day: 24 A Match object contains all the information about the search and the result and if there is no match found then None will be returned. Let’s see some of the commonly used methods and attributes of the match object. match.re attribute returns the regular expression passed and match.string attribute returns the string passed. Example: Getting the string and the regex of the matched object Python3 import re s = "Welcome to GeeksForGeeks" # here x is the match objectres = re.search(r"\bG", s) print(res.re)print(res.string) re.compile('\\bG') Welcome to GeeksForGeeks start() method returns the starting index of the matched substring end() method returns the ending index of the matched substring span() method returns a tuple containing the starting and the ending index of the matched substring Example: Getting index of matched object Python3 import re s = "Welcome to GeeksForGeeks" # here x is the match objectres = re.search(r"\bGee", s) print(res.start())print(res.end())print(res.span()) 11 14 (11, 14) group() method returns the part of the string for which the patterns match. See the below example for a better understanding. Example: Getting matched substring Python3 import re s = "Welcome to GeeksForGeeks" # here x is the match objectres = re.search(r"\D{2} t", s) print(res.group()) me t In the above example, our pattern specifies for the string that contains at least 2 characters which are followed by a space, and that space is followed by a t. Python Programming Tutorial | Python Modules - Part 2 (Regular Expression) | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPython Programming Tutorial | Python Modules - Part 2 (Regular Expression) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=JKNLy55G2z0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Related Article : https://www.geeksforgeeks.org/regular-expressions-python-set-1-search-match-find/ Reference: https://docs.python.org/2/library/re.html This article is contributed by Piyush Doorwar. 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. nidhi_biet ManasChhabra2 shubham_singh chaudhary_19 manasdutta nikhilaggarwal3 ruhelaa48 sagar0719kumar kapoorsagar226 muvvalaaravind gautamverma01gv simmytarika5 arshadali02177 kushagrathegame1 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2022" }, { "code": null, "e": 550, "s": 54, "text": "A Regular Expressions (RegEx) is a special sequence of characters that uses a search pattern to find a string or set of strings. It can detect the presence or absence of a text by matching it with a particular pattern, and also can split a pattern into one or more sub-patterns. Python provides a re module that supports the use of regex in Python. Its primary function is to offer a search, where it takes a regular expression and a string. Here, it either returns the first match or else none." }, { "code": null, "e": 559, "s": 550, "text": "Example:" }, { "code": null, "e": 567, "s": 559, "text": "Python3" }, { "code": "import re s = 'GeeksforGeeks: A computer science portal for geeks' match = re.search(r'portal', s) print('Start Index:', match.start())print('End Index:', match.end())", "e": 735, "s": 567, "text": null }, { "code": null, "e": 765, "s": 735, "text": "Start Index: 34\nEnd Index: 40" }, { "code": null, "e": 849, "s": 765, "text": "The above code gives the starting index and the ending index of the string portal. " }, { "code": null, "e": 1123, "s": 849, "text": "Note: Here r character (r’portal’) stands for raw, not regex. The raw string is slightly different from a regular string, it won’t interpret the \\ character as an escape character. This is because the regular expression engine uses \\ character for its own escaping purpose." }, { "code": null, "e": 1250, "s": 1123, "text": "Before starting with the Python regex module let’s see how to actually write regex using metacharacters or special sequences. " }, { "code": null, "e": 1399, "s": 1250, "text": "To understand the RE analogy, MetaCharacters are useful, important, and will be used in functions of module re. Below is the list of metacharacters." }, { "code": null, "e": 1453, "s": 1399, "text": "Let’s discuss each of these metacharacters in detail " }, { "code": null, "e": 1944, "s": 1453, "text": "The backslash (\\) makes sure that the character is not treated in a special way. This can be considered a way of escaping metacharacters. For example, if you want to search for the dot(.) in the string then you will find that dot(.) will be treated as a special character as is one of the metacharacters (as shown in the above table). So for this case, we will use the backslash(\\) just before the dot(.) so that it will lose its specialty. See the below example for a better understanding." }, { "code": null, "e": 1954, "s": 1944, "text": "Example: " }, { "code": null, "e": 1962, "s": 1954, "text": "Python3" }, { "code": "import re s = 'geeks.forgeeks' # without using \\match = re.search(r'.', s)print(match) # using \\match = re.search(r'\\.', s)print(match)", "e": 2098, "s": 1962, "text": null }, { "code": null, "e": 2194, "s": 2098, "text": "<_sre.SRE_Match object; span=(0, 1), match='g'>\n<_sre.SRE_Match object; span=(5, 6), match='.'>" }, { "code": null, "e": 2374, "s": 2194, "text": "Square Brackets ([]) represent a character class consisting of a set of characters that we wish to match. For example, the character class [abc] will match any single a, b, or c. " }, { "code": null, "e": 2466, "s": 2374, "text": "We can also specify a range of characters using – inside the square brackets. For example, " }, { "code": null, "e": 2493, "s": 2466, "text": "[0, 3] is sample as [0123]" }, { "code": null, "e": 2516, "s": 2493, "text": "[a-c] is same as [abc]" }, { "code": null, "e": 2596, "s": 2516, "text": "We can also invert the character class using the caret(^) symbol. For example, " }, { "code": null, "e": 2641, "s": 2596, "text": "[^0-3] means any number except 0, 1, 2, or 3" }, { "code": null, "e": 2686, "s": 2641, "text": "[^a-c] means any character except a, b, or c" }, { "code": null, "e": 2829, "s": 2686, "text": "Caret (^) symbol matches the beginning of the string i.e. checks whether the string starts with the given character(s) or not. For example – " }, { "code": null, "e": 2907, "s": 2829, "text": "^g will check if the string starts with g such as geeks, globe, girl, g, etc." }, { "code": null, "e": 2986, "s": 2907, "text": "^ge will check if the string starts with ge such as geeks, geeksforgeeks, etc." }, { "code": null, "e": 3119, "s": 2986, "text": "Dollar($) symbol matches the end of the string i.e checks whether the string ends with the given character(s) or not. For example – " }, { "code": null, "e": 3194, "s": 3119, "text": "s$ will check for the string that ends with a such as geeks, ends, s, etc." }, { "code": null, "e": 3281, "s": 3194, "text": "ks$ will check for the string that ends with ks such as geeks, geeksforgeeks, ks, etc." }, { "code": null, "e": 3382, "s": 3281, "text": "Dot(.) symbol matches only a single character except for the newline character (\\n). For example – " }, { "code": null, "e": 3493, "s": 3382, "text": "a.b will check for the string that contains any character at the place of the dot such as acb, acbd, abbb, etc" }, { "code": null, "e": 3552, "s": 3493, "text": ".. will check if the string contains at least 2 characters" }, { "code": null, "e": 3704, "s": 3552, "text": "Or symbol works as the or operator meaning it checks whether the pattern before or after the or symbol is present in the string or not. For example – " }, { "code": null, "e": 3780, "s": 3704, "text": "a|b will match any string that contains a or b such as acd, bcd, abcd, etc." }, { "code": null, "e": 3908, "s": 3780, "text": "Question mark(?) checks if the string before the question mark in the regex occurs at least once or not at all. For example – " }, { "code": null, "e": 4091, "s": 3908, "text": "ab?c will be matched for the string ac, acb, dabc but will not be matched for abbc because there are two b. Similarly, it will not be matched for abdc because b is not followed by c." }, { "code": null, "e": 4193, "s": 4091, "text": "Star (*) symbol matches zero or more occurrences of the regex preceding the * symbol. For example – " }, { "code": null, "e": 4321, "s": 4193, "text": "ab*c will be matched for the string ac, abc, abbbc, dabc, etc. but will not be matched for abdc because b is not followed by c." }, { "code": null, "e": 4422, "s": 4321, "text": "Plus (+) symbol matches one or more occurrences of the regex preceding the + symbol. For example – " }, { "code": null, "e": 4576, "s": 4422, "text": "ab+c will be matched for the string abc, abbc, dabc, but will not be matched for ac, abdc because there is no b in ac and b is not followed by c in abdc." }, { "code": null, "e": 4665, "s": 4576, "text": "Braces match any repetitions preceding regex from m to n both inclusive. For example – " }, { "code": null, "e": 4828, "s": 4665, "text": "a{2, 4} will be matched for the string aaab, baaaac, gaad, but will not be matched for strings like abc, bc because there is only one a or no a in both the cases." }, { "code": null, "e": 4888, "s": 4828, "text": "Group symbol is used to group sub-patterns. For example – " }, { "code": null, "e": 4946, "s": 4888, "text": "(a|b)cd will match for strings like acd, abcd, gacd, etc." }, { "code": null, "e": 5158, "s": 4946, "text": "Special sequences do not match for the actual character in the string instead it tells the specific location in the search string where the match must occur. It makes it easier to write commonly used patterns. " }, { "code": null, "e": 5292, "s": 5158, "text": "Python has a module named re that is used for regular expressions in Python. We can import this module by using the import statement." }, { "code": null, "e": 5332, "s": 5292, "text": "Example: Importing re module in Python " }, { "code": null, "e": 5340, "s": 5332, "text": "Python3" }, { "code": "import re", "e": 5350, "s": 5340, "text": null }, { "code": null, "e": 5433, "s": 5350, "text": "Let’s see various functions provided by this module to work with regex in Python. " }, { "code": null, "e": 5594, "s": 5433, "text": "Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found." }, { "code": null, "e": 5641, "s": 5594, "text": "Example: Finding all occurrences of a pattern " }, { "code": null, "e": 5649, "s": 5641, "text": "Python3" }, { "code": "# A Python program to demonstrate working of# findall()import re # A sample text string where regular expression# is searched.string = \"\"\"Hello my Number is 123456789 and my friend's number is 987654321\"\"\" # A sample regular expression to find digits.regex = '\\d+' match = re.findall(regex, string)print(match) # This example is contributed by Ayush Saluja.", "e": 6018, "s": 5649, "text": null }, { "code": null, "e": 6045, "s": 6018, "text": "['123456789', '987654321']" }, { "code": null, "e": 6217, "s": 6045, "text": "Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions. " }, { "code": null, "e": 6228, "s": 6217, "text": "Example 1:" }, { "code": null, "e": 6235, "s": 6228, "text": "Python" }, { "code": "# Module Regular Expression is imported# using __import__().import re # compile() creates regular expression# character class [a-e],# which is equivalent to [abcde].# class [abcde] will match with string with# 'a', 'b', 'c', 'd', 'e'.p = re.compile('[a-e]') # findall() searches for the Regular Expression# and return a list upon findingprint(p.findall(\"Aye, said Mr. Gibenson Stark\"))", "e": 6621, "s": 6235, "text": null }, { "code": null, "e": 6630, "s": 6621, "text": "Output: " }, { "code": null, "e": 6661, "s": 6630, "text": "['e', 'a', 'd', 'b', 'e', 'a']" }, { "code": null, "e": 6688, "s": 6661, "text": "Understanding the Output: " }, { "code": null, "e": 6759, "s": 6688, "text": "First occurrence is ‘e’ in “Aye” and not ‘A’, as it is Case Sensitive." }, { "code": null, "e": 6887, "s": 6759, "text": "Next Occurrence is ‘a’ in “said”, then ‘d’ in “said”, followed by ‘b’ and ‘e’ in “Gibenson”, the Last ‘a’ matches with “Stark”." }, { "code": null, "e": 7059, "s": 6887, "text": "Metacharacter backslash ‘\\’ has a very important role as it signals various sequences. If the backslash is to be used without its special meaning as metacharacter, use’\\\\’" }, { "code": null, "e": 7142, "s": 7059, "text": "Example 2: Set class [\\s,.] will match any whitespace character, ‘,’, or, ‘.’ . " }, { "code": null, "e": 7149, "s": 7142, "text": "Python" }, { "code": "import re # \\d is equivalent to [0-9].p = re.compile('\\d')print(p.findall(\"I went to him at 11 A.M. on 4th July 1886\")) # \\d+ will match a group on [0-9], group# of one or greater sizep = re.compile('\\d+')print(p.findall(\"I went to him at 11 A.M. on 4th July 1886\"))", "e": 7416, "s": 7149, "text": null }, { "code": null, "e": 7425, "s": 7416, "text": "Output: " }, { "code": null, "e": 7481, "s": 7425, "text": "['1', '1', '4', '1', '8', '8', '6']\n['11', '4', '1886']" }, { "code": null, "e": 7492, "s": 7481, "text": "Example 3:" }, { "code": null, "e": 7499, "s": 7492, "text": "Python" }, { "code": "import re # \\w is equivalent to [a-zA-Z0-9_].p = re.compile('\\w')print(p.findall(\"He said * in some_lang.\")) # \\w+ matches to group of alphanumeric character.p = re.compile('\\w+')print(p.findall(\"I went to him at 11 A.M., he \\said *** in some_language.\")) # \\W matches to non alphanumeric characters.p = re.compile('\\W')print(p.findall(\"he said *** in some_language.\"))", "e": 7869, "s": 7499, "text": null }, { "code": null, "e": 7878, "s": 7869, "text": "Output: " }, { "code": null, "e": 8091, "s": 7878, "text": "['H', 'e', 's', 'a', 'i', 'd', 'i', 'n', 's', 'o', 'm', 'e', '_', 'l', 'a', 'n', 'g']\n['I', 'went', 'to', 'him', 'at', '11', 'A', 'M', 'he', 'said', 'in', 'some_language']\n[' ', ' ', '*', '*', '*', ' ', ' ', '.']" }, { "code": null, "e": 8102, "s": 8091, "text": "Example 4:" }, { "code": null, "e": 8109, "s": 8102, "text": "Python" }, { "code": "import re # '*' replaces the no. of occurrence# of a character.p = re.compile('ab*')print(p.findall(\"ababbaabbb\"))", "e": 8224, "s": 8109, "text": null }, { "code": null, "e": 8233, "s": 8224, "text": "Output: " }, { "code": null, "e": 8260, "s": 8233, "text": "['ab', 'abb', 'a', 'abbb']" }, { "code": null, "e": 8287, "s": 8260, "text": "Understanding the Output: " }, { "code": null, "e": 8361, "s": 8287, "text": "Our RE is ab*, which ‘a’ accompanied by any no. of ‘b’s, starting from 0." }, { "code": null, "e": 8432, "s": 8361, "text": "Output ‘ab’, is valid because of single ‘a’ accompanied by single ‘b’." }, { "code": null, "e": 8499, "s": 8432, "text": "Output ‘abb’, is valid because of single ‘a’ accompanied by 2 ‘b’." }, { "code": null, "e": 8564, "s": 8499, "text": "Output ‘a’, is valid because of single ‘a’ accompanied by 0 ‘b’." }, { "code": null, "e": 8632, "s": 8564, "text": "Output ‘abbb’, is valid because of single ‘a’ accompanied by 3 ‘b’." }, { "code": null, "e": 8806, "s": 8632, "text": "Split string by the occurrences of a character or a pattern, upon finding that pattern, the remaining characters from the string are returned as part of the resulting list. " }, { "code": null, "e": 8816, "s": 8806, "text": "Syntax : " }, { "code": null, "e": 8863, "s": 8816, "text": "re.split(pattern, string, maxsplit=0, flags=0)" }, { "code": null, "e": 9434, "s": 8863, "text": "The First parameter, pattern denotes the regular expression, string is the given string in which pattern will be searched for and in which splitting occurs, maxsplit if not provided is considered to be zero ‘0’, and if any nonzero value is provided, then at most that many splits occur. If maxsplit = 1, then the string will split once only, resulting in a list of length 2. The flags are very useful and can help to shorten code, they are not necessary parameters, eg: flags = re.IGNORECASE, in this split, the case, i.e. the lowercase or the uppercase will be ignored." }, { "code": null, "e": 9445, "s": 9434, "text": "Example 1:" }, { "code": null, "e": 9452, "s": 9445, "text": "Python" }, { "code": "from re import split # '\\W+' denotes Non-Alphanumeric Characters# or group of characters Upon finding ','# or whitespace ' ', the split(), splits the# string from that pointprint(split('\\W+', 'Words, words , Words'))print(split('\\W+', \"Word's words Words\")) # Here ':', ' ' ,',' are not AlphaNumeric thus,# the point where splitting occursprint(split('\\W+', 'On 12th Jan 2016, at 11:02 AM')) # '\\d+' denotes Numeric Characters or group of# characters Splitting occurs at '12', '2016',# '11', '02' onlyprint(split('\\d+', 'On 12th Jan 2016, at 11:02 AM'))", "e": 10006, "s": 9452, "text": null }, { "code": null, "e": 10015, "s": 10006, "text": "Output: " }, { "code": null, "e": 10169, "s": 10015, "text": "['Words', 'words', 'Words']\n['Word', 's', 'words', 'Words']\n['On', '12th', 'Jan', '2016', 'at', '11', '02', 'AM']\n['On ', 'th Jan ', ', at ', ':', ' AM']" }, { "code": null, "e": 10180, "s": 10169, "text": "Example 2:" }, { "code": null, "e": 10187, "s": 10180, "text": "Python" }, { "code": "import re # Splitting will occurs only once, at# '12', returned list will have length 2print(re.split('\\d+', 'On 12th Jan 2016, at 11:02 AM', 1)) # 'Boy' and 'boy' will be treated same when# flags = re.IGNORECASEprint(re.split('[a-f]+', 'Aey, Boy oh boy, come here', flags=re.IGNORECASE))print(re.split('[a-f]+', 'Aey, Boy oh boy, come here'))", "e": 10531, "s": 10187, "text": null }, { "code": null, "e": 10540, "s": 10531, "text": "Output: " }, { "code": null, "e": 10676, "s": 10540, "text": "['On ', 'th Jan 2016, at 11:02 AM']\n['', 'y, ', 'oy oh ', 'oy, ', 'om', ' h', 'r', '']\n['A', 'y, Boy oh ', 'oy, ', 'om', ' h', 'r', '']" }, { "code": null, "e": 10945, "s": 10676, "text": "The ‘sub’ in the function stands for SubString, a certain regular expression pattern is searched in the given string(3rd parameter), and upon finding the substring pattern is replaced by repl(2nd parameter), count checks and maintains the number of times this occurs. " }, { "code": null, "e": 10953, "s": 10945, "text": "Syntax:" }, { "code": null, "e": 11002, "s": 10953, "text": " re.sub(pattern, repl, string, count=0, flags=0)" }, { "code": null, "e": 11013, "s": 11002, "text": "Example 1:" }, { "code": null, "e": 11020, "s": 11013, "text": "Python" }, { "code": "import re # Regular Expression pattern 'ub' matches the# string at \"Subject\" and \"Uber\". As the CASE# has been ignored, using Flag, 'ub' should# match twice with the string Upon matching,# 'ub' is replaced by '~*' in \"Subject\", and# in \"Uber\", 'Ub' is replaced.print(re.sub('ub', '~*', 'Subject has Uber booked already', flags=re.IGNORECASE)) # Consider the Case Sensitivity, 'Ub' in# \"Uber\", will not be replaced.print(re.sub('ub', '~*', 'Subject has Uber booked already')) # As count has been given value 1, the maximum# times replacement occurs is 1print(re.sub('ub', '~*', 'Subject has Uber booked already', count=1, flags=re.IGNORECASE)) # 'r' before the pattern denotes RE, \\s is for# start and end of a String.print(re.sub(r'\\sAND\\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE))", "e": 11851, "s": 11020, "text": null }, { "code": null, "e": 11859, "s": 11851, "text": "Output " }, { "code": null, "e": 11974, "s": 11859, "text": "S~*ject has ~*er booked already\nS~*ject has Uber booked already\nS~*ject has Uber booked already\nBaked Beans & Spam" }, { "code": null, "e": 12162, "s": 11974, "text": "subn() is similar to sub() in all ways, except in its way of providing output. It returns a tuple with a count of the total of replacement and the new string rather than just the string. " }, { "code": null, "e": 12170, "s": 12162, "text": "Syntax:" }, { "code": null, "e": 12220, "s": 12170, "text": " re.subn(pattern, repl, string, count=0, flags=0)" }, { "code": null, "e": 12229, "s": 12220, "text": "Example:" }, { "code": null, "e": 12236, "s": 12229, "text": "Python" }, { "code": "import re print(re.subn('ub', '~*', 'Subject has Uber booked already')) t = re.subn('ub', '~*', 'Subject has Uber booked already', flags=re.IGNORECASE)print(t)print(len(t)) # This will give same output as sub() would haveprint(t[0])", "e": 12480, "s": 12236, "text": null }, { "code": null, "e": 12488, "s": 12480, "text": "Output " }, { "code": null, "e": 12621, "s": 12488, "text": "('S~*ject has Uber booked already', 1)\n('S~*ject has ~*er booked already', 2)\nLength of Tuple is: 2\nS~*ject has ~*er booked already" }, { "code": null, "e": 12795, "s": 12621, "text": "Returns string with all non-alphanumerics backslashed, this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it." }, { "code": null, "e": 12803, "s": 12795, "text": "Syntax:" }, { "code": null, "e": 12821, "s": 12803, "text": "re.escape(string)" }, { "code": null, "e": 12830, "s": 12821, "text": "Example:" }, { "code": null, "e": 12837, "s": 12830, "text": "Python" }, { "code": "import re # escape() returns a string with BackSlash '\\',# before every Non-Alphanumeric Character# In 1st case only ' ', is not alphanumeric# In 2nd case, ' ', caret '^', '-', '[]', '\\'# are not alphanumericprint(re.escape(\"This is Awesome even 1 AM\"))print(re.escape(\"I Asked what is this [a-9], he said \\t ^WoW\"))", "e": 13154, "s": 12837, "text": null }, { "code": null, "e": 13246, "s": 13154, "text": "This\\ is\\ Awesome\\ even\\ 1\\ AM\nI\\ Asked\\ what\\ is\\ this\\ \\[a\\-9\\]\\,\\ he\\ said\\ \\ \\ \\^WoW" }, { "code": null, "e": 13514, "s": 13246, "text": "This method either returns None (if the pattern doesn’t match), or a re.MatchObject contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data." }, { "code": null, "e": 13566, "s": 13514, "text": "Example: Searching for an occurrence of the pattern" }, { "code": null, "e": 13574, "s": 13566, "text": "Python3" }, { "code": "# A Python program to demonstrate working of re.match().import re # Lets use a regular expression to match a date string# in the form of Month name followed by day numberregex = r\"([a-zA-Z]+) (\\d+)\" match = re.search(regex, \"I was born on June 24\") if match != None: # We reach here when the expression \"([a-zA-Z]+) (\\d+)\" # matches the date string. # This will print [14, 21), since it matches at index 14 # and ends at 21. print (\"Match at index %s, %s\" % (match.start(), match.end())) # We us group() method to get all the matches and # captured groups. The groups contain the matched values. # In particular: # match.group(0) always returns the fully matched string # match.group(1) match.group(2), ... return the capture # groups in order from left to right in the input string # match.group() is equivalent to match.group(0) # So this will print \"June 24\" print (\"Full match: %s\" % (match.group(0))) # So this will print \"June\" print (\"Month: %s\" % (match.group(1))) # So this will print \"24\" print (\"Day: %s\" % (match.group(2))) else: print (\"The regex pattern does not match.\")", "e": 14723, "s": 13574, "text": null }, { "code": null, "e": 14785, "s": 14723, "text": "Match at index 14, 21\nFull match: June 24\nMonth: June\nDay: 24" }, { "code": null, "e": 15000, "s": 14785, "text": "A Match object contains all the information about the search and the result and if there is no match found then None will be returned. Let’s see some of the commonly used methods and attributes of the match object." }, { "code": null, "e": 15111, "s": 15000, "text": "match.re attribute returns the regular expression passed and match.string attribute returns the string passed." }, { "code": null, "e": 15175, "s": 15111, "text": "Example: Getting the string and the regex of the matched object" }, { "code": null, "e": 15183, "s": 15175, "text": "Python3" }, { "code": "import re s = \"Welcome to GeeksForGeeks\" # here x is the match objectres = re.search(r\"\\bG\", s) print(res.re)print(res.string)", "e": 15310, "s": 15183, "text": null }, { "code": null, "e": 15354, "s": 15310, "text": "re.compile('\\\\bG')\nWelcome to GeeksForGeeks" }, { "code": null, "e": 15421, "s": 15354, "text": "start() method returns the starting index of the matched substring" }, { "code": null, "e": 15484, "s": 15421, "text": "end() method returns the ending index of the matched substring" }, { "code": null, "e": 15584, "s": 15484, "text": "span() method returns a tuple containing the starting and the ending index of the matched substring" }, { "code": null, "e": 15626, "s": 15584, "text": "Example: Getting index of matched object " }, { "code": null, "e": 15634, "s": 15626, "text": "Python3" }, { "code": "import re s = \"Welcome to GeeksForGeeks\" # here x is the match objectres = re.search(r\"\\bGee\", s) print(res.start())print(res.end())print(res.span())", "e": 15784, "s": 15634, "text": null }, { "code": null, "e": 15799, "s": 15784, "text": "11\n14\n(11, 14)" }, { "code": null, "e": 15925, "s": 15799, "text": "group() method returns the part of the string for which the patterns match. See the below example for a better understanding." }, { "code": null, "e": 15961, "s": 15925, "text": "Example: Getting matched substring " }, { "code": null, "e": 15969, "s": 15961, "text": "Python3" }, { "code": "import re s = \"Welcome to GeeksForGeeks\" # here x is the match objectres = re.search(r\"\\D{2} t\", s) print(res.group())", "e": 16088, "s": 15969, "text": null }, { "code": null, "e": 16093, "s": 16088, "text": "me t" }, { "code": null, "e": 16255, "s": 16093, "text": "In the above example, our pattern specifies for the string that contains at least 2 characters which are followed by a space, and that space is followed by a t. " }, { "code": null, "e": 17221, "s": 16255, "text": "Python Programming Tutorial | Python Modules - Part 2 (Regular Expression) | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersPython Programming Tutorial | Python Modules - Part 2 (Regular Expression) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou'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.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:30•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=JKNLy55G2z0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 17321, "s": 17221, "text": "Related Article : https://www.geeksforgeeks.org/regular-expressions-python-set-1-search-match-find/" }, { "code": null, "e": 17374, "s": 17321, "text": "Reference: https://docs.python.org/2/library/re.html" }, { "code": null, "e": 17672, "s": 17374, "text": "This article is contributed by Piyush Doorwar. 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." }, { "code": null, "e": 17798, "s": 17672, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 17809, "s": 17798, "text": "nidhi_biet" }, { "code": null, "e": 17823, "s": 17809, "text": "ManasChhabra2" }, { "code": null, "e": 17837, "s": 17823, "text": "shubham_singh" }, { "code": null, "e": 17850, "s": 17837, "text": "chaudhary_19" }, { "code": null, "e": 17861, "s": 17850, "text": "manasdutta" }, { "code": null, "e": 17877, "s": 17861, "text": "nikhilaggarwal3" }, { "code": null, "e": 17887, "s": 17877, "text": "ruhelaa48" }, { "code": null, "e": 17902, "s": 17887, "text": "sagar0719kumar" }, { "code": null, "e": 17917, "s": 17902, "text": "kapoorsagar226" }, { "code": null, "e": 17932, "s": 17917, "text": "muvvalaaravind" }, { "code": null, "e": 17948, "s": 17932, "text": "gautamverma01gv" }, { "code": null, "e": 17961, "s": 17948, "text": "simmytarika5" }, { "code": null, "e": 17976, "s": 17961, "text": "arshadali02177" }, { "code": null, "e": 17993, "s": 17976, "text": "kushagrathegame1" }, { "code": null, "e": 18000, "s": 17993, "text": "Python" } ]
What is the difference between Python’s Module, Package and Library?
10 Jul, 2020 Module: The module is a simple Python file that contains collections of functions and global variables and with having a .py extension file. It is an executable file and to organize all the modules we have the concept called Package in Python. Example: Save the code in file called demo_module.py def myModule(name): print("This is My Module : "+ name) Import module named demo_module and call myModule function inside it. import demo_module demo_module.myModule("Math") Output: This is My Module : Math Package: The package is a simple directory having collections of modules. This directory contains Python modules and also having __init__.py file by which the interpreter interprets it as a Package. The package is simply a namespace. The package also contains sub-packages inside it. Example: Student(Package) | __init__.py (Constructor) | details.py (Module) | marks.py (Module) | collegeDetails.py (Module) Library: The library is having a collection of related functionality of codes that allows you to perform many tasks without writing your code. It is a reusable chunk of code that we can use by importing it in our program, we can just use it by importing that library and calling the method of that library with period(.). Example: Importing pandas library and call read_csv method using alias of pandas i.e. pd. import pandas as pd df = pd.read_csv("file_name.csv") python-basics 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": "\n10 Jul, 2020" }, { "code": null, "e": 298, "s": 54, "text": "Module: The module is a simple Python file that contains collections of functions and global variables and with having a .py extension file. It is an executable file and to organize all the modules we have the concept called Package in Python." }, { "code": null, "e": 351, "s": 298, "text": "Example: Save the code in file called demo_module.py" }, { "code": "def myModule(name): print(\"This is My Module : \"+ name)", "e": 410, "s": 351, "text": null }, { "code": null, "e": 480, "s": 410, "text": "Import module named demo_module and call myModule function inside it." }, { "code": "import demo_module demo_module.myModule(\"Math\")", "e": 529, "s": 480, "text": null }, { "code": null, "e": 537, "s": 529, "text": "Output:" }, { "code": null, "e": 562, "s": 537, "text": "This is My Module : Math" }, { "code": null, "e": 846, "s": 562, "text": "Package: The package is a simple directory having collections of modules. This directory contains Python modules and also having __init__.py file by which the interpreter interprets it as a Package. The package is simply a namespace. The package also contains sub-packages inside it." }, { "code": null, "e": 855, "s": 846, "text": "Example:" }, { "code": null, "e": 971, "s": 855, "text": "Student(Package)\n| __init__.py (Constructor)\n| details.py (Module)\n| marks.py (Module)\n| collegeDetails.py (Module)" }, { "code": null, "e": 1293, "s": 971, "text": "Library: The library is having a collection of related functionality of codes that allows you to perform many tasks without writing your code. It is a reusable chunk of code that we can use by importing it in our program, we can just use it by importing that library and calling the method of that library with period(.)." }, { "code": null, "e": 1383, "s": 1293, "text": "Example: Importing pandas library and call read_csv method using alias of pandas i.e. pd." }, { "code": "import pandas as pd df = pd.read_csv(\"file_name.csv\")", "e": 1438, "s": 1383, "text": null }, { "code": null, "e": 1452, "s": 1438, "text": "python-basics" }, { "code": null, "e": 1459, "s": 1452, "text": "Python" }, { "code": null, "e": 1557, "s": 1459, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1575, "s": 1557, "text": "Python Dictionary" }, { "code": null, "e": 1617, "s": 1575, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1639, "s": 1617, "text": "Enumerate() in Python" }, { "code": null, "e": 1674, "s": 1639, "text": "Read a file line by line in Python" }, { "code": null, "e": 1700, "s": 1674, "text": "Python String | replace()" }, { "code": null, "e": 1732, "s": 1700, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1761, "s": 1732, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1788, "s": 1761, "text": "Python Classes and Objects" }, { "code": null, "e": 1818, "s": 1788, "text": "Iterate over a list in Python" } ]
How to find index of a given element in a Vector in C++
06 Jul, 2022 Given a vector V consisting of N integers and an element K, the task is to find the index of element K in the vector V. If the element does not exist in vector then print -1. Examples: Input: V = {1, 45, 54, 71, 76, 17}, K = 54 Output: 2 Explanation : The index of 54 is 2, hence output is 2.Input: V = {3, 7, 9, 11, 13}, K = 12 Output: -1 Approach: Follow the steps below to solve the problem: find(): Used to find the position of element in the vector. Subtract from the iterator returned from the find function, the base iterator of the vector . Finally return the index returned by the subtraction. Below is the implementation of the above approach : C++ // C++ program to find the index// of an element in a vector#include <bits/stdc++.h>using namespace std; // Function to print the// index of an elementvoid getIndex(vector<int> v, int K){ auto it = find(v.begin(), v.end(), K); // If element was found if (it != v.end()) { // calculating the index // of K int index = it - v.begin(); cout << index << endl; } else { // If the element is not // present in the vector cout << "-1" << endl; }}// Driver Codeint main(){ // Vector vector<int> v = { 1, 45, 54, 71, 76, 17 }; // Value whose index // needs to be found int K = 54; getIndex(v, K); return 0;} 2 Time Complexity: O(N) Auxiliary Space: O(1) sethaditya35 cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Priority Queue in C++ Standard Template Library (STL) Inheritance in C++ Object Oriented Programming in C++ The C++ Standard Template Library (STL) C++ Classes and Objects Sorting a vector in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 227, "s": 52, "text": "Given a vector V consisting of N integers and an element K, the task is to find the index of element K in the vector V. If the element does not exist in vector then print -1." }, { "code": null, "e": 238, "s": 227, "text": "Examples: " }, { "code": null, "e": 394, "s": 238, "text": "Input: V = {1, 45, 54, 71, 76, 17}, K = 54 Output: 2 Explanation : The index of 54 is 2, hence output is 2.Input: V = {3, 7, 9, 11, 13}, K = 12 Output: -1 " }, { "code": null, "e": 451, "s": 394, "text": "Approach: Follow the steps below to solve the problem: " }, { "code": null, "e": 511, "s": 451, "text": "find(): Used to find the position of element in the vector." }, { "code": null, "e": 605, "s": 511, "text": "Subtract from the iterator returned from the find function, the base iterator of the vector ." }, { "code": null, "e": 659, "s": 605, "text": "Finally return the index returned by the subtraction." }, { "code": null, "e": 713, "s": 659, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 717, "s": 713, "text": "C++" }, { "code": "// C++ program to find the index// of an element in a vector#include <bits/stdc++.h>using namespace std; // Function to print the// index of an elementvoid getIndex(vector<int> v, int K){ auto it = find(v.begin(), v.end(), K); // If element was found if (it != v.end()) { // calculating the index // of K int index = it - v.begin(); cout << index << endl; } else { // If the element is not // present in the vector cout << \"-1\" << endl; }}// Driver Codeint main(){ // Vector vector<int> v = { 1, 45, 54, 71, 76, 17 }; // Value whose index // needs to be found int K = 54; getIndex(v, K); return 0;}", "e": 1417, "s": 717, "text": null }, { "code": null, "e": 1423, "s": 1417, "text": "2\n\n\n\n" }, { "code": null, "e": 1469, "s": 1425, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 1482, "s": 1469, "text": "sethaditya35" }, { "code": null, "e": 1493, "s": 1482, "text": "cpp-vector" }, { "code": null, "e": 1497, "s": 1493, "text": "STL" }, { "code": null, "e": 1501, "s": 1497, "text": "C++" }, { "code": null, "e": 1505, "s": 1501, "text": "STL" }, { "code": null, "e": 1509, "s": 1505, "text": "CPP" }, { "code": null, "e": 1607, "s": 1509, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1634, "s": 1607, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 1677, "s": 1634, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 1711, "s": 1677, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 1736, "s": 1711, "text": "unordered_map in C++ STL" }, { "code": null, "e": 1790, "s": 1736, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 1809, "s": 1790, "text": "Inheritance in C++" }, { "code": null, "e": 1844, "s": 1809, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 1884, "s": 1844, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 1908, "s": 1884, "text": "C++ Classes and Objects" } ]
What is JSON Array ?
27 Dec, 2021 JSON Array is almost same as JavaScript Array. JSON array can store values of type string, array, boolean, number, object, or null. In JSON array, values are separated by commas. Array elements can be accessed using the [] operator. JSON Array is of different types. Let’s understand them with the help of examples. JSON Array of String: JSON array of Strings contains string elements only. For example, the array below has 6 string elements, “Ram”, “Shyam”, “Radhika”, “Akshay”, “Prashant” and “Varun”, each element is separated with a comma (,). ["Ram", "Shyam", "Radhika", "Akshay", "Prashant", "Varun"] Example: Here we will assign a JSON Array of Strings to the key students in jsonStringArray object. Then we access the first element of array using the [ ] operator. HTML <!DOCTYPE html><html> <body> <p id="para"></p> <script> var jsonStringArray = { // Assigned a JSON array of strings // to the key "students". "students": ["Ram", "Shyam", "Radhika", "Akshay", "Prashant", "Varun"], }; // It returned an array. Then we accessed // the first index of the array // (which is "Ram") using [] syntax. var x = jsonStringArray.students[0]; // Set the inner HTML of "para" paragraph // to the value of variable "x". document.getElementById("para").innerHTML = x; </script></body> </html> Output: Ram JSON Array of Numbers: JSON array of Numbers contains number elements only. For example the array below has 5 elements, 23, 44, 76, 34, 98. [23, 44, 76, 34, 98] Example: Here we assign a JSON Array of Numbers to the key marks in jsonNumberArray object. Then we access the first element of array using [ ] operator. HTML <!DOCTYPE html><html> <body> <p id="para"></p> <script> var jsonNumberArray = { // Assigned a JSON array of numbers // to the key "marks". "marks": [23, 44, 76, 34, 98], }; // It returned an number array. // Then we accessed the first // index of the array // (which is 23) using [] syntax. var x = jsonNumberArray.marks[0]; // Set the inner HTML of "para" paragraph // to the value of variable "x". document.getElementById("para").innerHTML = x; </script></body> </html> Output: 23 JSON Array of Booleans: JSON array of Booleans contains boolean elements only (either true or false). For example, the array below has 5 elements in it each one of that is either true or false. [true, true, true, false, false, true] Example: Here we assign a JSON Array of Booleans to the key boolean in jsonBooleanArray object. Then we access the first element of array using [ ] operator. HTML <!DOCTYPE html><html> <body> <p id="para"></p> <script> var jsonBooleanArray = { // Assigned a JSON array of boolean // to the key "booleans". "booleans": [true, true, true, false, false, true], }; // Here we accessed the booleans property // of jsonBooleanArray Object. // It returned an boolean array. Then we accessed the // first index of the array // (which is true) using [] syntax. var x = jsonBooleanArray.booleans[0]; // Set the inner HTML of "para" paragraph // to the value of variable "x". document.getElementById("para").innerHTML = x; </script></body> </html> Output: true JSON Array of Objects: A JSON object is same as JavaScript object. We can also create a JSON Array containing many JSON objects in it, then we can iterate over that array or use the [ ] to get the object we need. In the example below, there are three JSON objects in the array assigned to key “books”. Each object has “name” and “author” property. { "books":[ {"name":"Let Us C", "author":"Yashavant Kanetkar"}, {"name":"Rich Dad Poor Dad", "author":"Robert Kiyosaki "}, {"name":"Introduction to Algorithms", "author":"Cormen"}, ] } Example: Here we assign a JSON Array of Objects to the key books in jsonObjectArray object. Then we access the first element of array using [ ] operator. HTML <!DOCTYPE html><html> <body> <p id="para"></p> <script> var jsonObjectArray = { // Assigned a JSON array of objects // to the key "books" "books": [ { "name": "Let Us C", "author": "Yashavant Kanetkar" }, { "name": "Rich Dad Poor Dad", "author": "Robert Kiyosaki " }, { "name": "Introduction to Algorithms", "author": "Cormen" }, ] }; // Here we accessed the books property of // jsonObjectArray Object. // It returned an object array. Then we // accessed the first index of the array // (which is an JSON object) using [] syntax var x = jsonObjectArray.books[0]; // Set the inner HTML of "para" paragraph // to the value of variable "x". document.getElementById("para").innerHTML = x.name + " by " + x.author; </script></body> </html> Output: Let Us C by Yashavant Kanetkar 5. JSON Array of Arrays OR JSON Multidimensional Array: It is also possible to create a JSON array containing other arrays as elements in it. In the example below we have a JSON array which contains arrays [“a”, “b”, “c”], [“d”, “e”, “f”], [“g” , “h”, “i”] in it. We can use [ ] operator to get the array at any index and use the [ ] operator again to get the element of the selected array. { "matrix": [ [ "a", "b", "c" ], [ "d", "e", "f" ], [ "g", "h", "i" ] ], }; Example: Here we assign a JSON Array of Arrays to the key matrix in jsonMultiArray object. Then we access the first element of array using [ ] operator. HTML <!DOCTYPE html><html> <body> <p id="para"></p> <script> var jsonMultiArray = { // Assigned a JSON array of // Arrays to the key "matrix". "matrix": [ ["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"] ], }; // Here we accessed the matrix property // of jsonMultiArray Object. // It returned an matrix(2D array). Then we // accessed the first element of // the first index of matrix using [] syntax. var x = jsonMultiArray.matrix[0][0]; // Set the inner HTML of "para" paragraph // to the value of variable "x". document.getElementById("para").innerHTML = x; </script></body> </html> Output: a prachisoda1234 simmytarika5 surinderdawra388 JavaScript-Questions JSON Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array JavaScript String includes() Method Implementation of LinkedList in Javascript DOM (Document Object Model) Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Dec, 2021" }, { "code": null, "e": 261, "s": 28, "text": "JSON Array is almost same as JavaScript Array. JSON array can store values of type string, array, boolean, number, object, or null. In JSON array, values are separated by commas. Array elements can be accessed using the [] operator." }, { "code": null, "e": 344, "s": 261, "text": "JSON Array is of different types. Let’s understand them with the help of examples." }, { "code": null, "e": 576, "s": 344, "text": "JSON Array of String: JSON array of Strings contains string elements only. For example, the array below has 6 string elements, “Ram”, “Shyam”, “Radhika”, “Akshay”, “Prashant” and “Varun”, each element is separated with a comma (,)." }, { "code": null, "e": 635, "s": 576, "text": "[\"Ram\", \"Shyam\", \"Radhika\", \"Akshay\", \"Prashant\", \"Varun\"]" }, { "code": null, "e": 802, "s": 635, "text": "Example: Here we will assign a JSON Array of Strings to the key students in jsonStringArray object. Then we access the first element of array using the [ ] operator. " }, { "code": null, "e": 807, "s": 802, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"para\"></p> <script> var jsonStringArray = { // Assigned a JSON array of strings // to the key \"students\". \"students\": [\"Ram\", \"Shyam\", \"Radhika\", \"Akshay\", \"Prashant\", \"Varun\"], }; // It returned an array. Then we accessed // the first index of the array // (which is \"Ram\") using [] syntax. var x = jsonStringArray.students[0]; // Set the inner HTML of \"para\" paragraph // to the value of variable \"x\". document.getElementById(\"para\").innerHTML = x; </script></body> </html>", "e": 1459, "s": 807, "text": null }, { "code": null, "e": 1467, "s": 1459, "text": "Output:" }, { "code": null, "e": 1471, "s": 1467, "text": "Ram" }, { "code": null, "e": 1611, "s": 1471, "text": "JSON Array of Numbers: JSON array of Numbers contains number elements only. For example the array below has 5 elements, 23, 44, 76, 34, 98." }, { "code": null, "e": 1632, "s": 1611, "text": "[23, 44, 76, 34, 98]" }, { "code": null, "e": 1787, "s": 1632, "text": "Example: Here we assign a JSON Array of Numbers to the key marks in jsonNumberArray object. Then we access the first element of array using [ ] operator. " }, { "code": null, "e": 1792, "s": 1787, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"para\"></p> <script> var jsonNumberArray = { // Assigned a JSON array of numbers // to the key \"marks\". \"marks\": [23, 44, 76, 34, 98], }; // It returned an number array. // Then we accessed the first // index of the array // (which is 23) using [] syntax. var x = jsonNumberArray.marks[0]; // Set the inner HTML of \"para\" paragraph // to the value of variable \"x\". document.getElementById(\"para\").innerHTML = x; </script></body> </html>", "e": 2385, "s": 1792, "text": null }, { "code": null, "e": 2393, "s": 2385, "text": "Output:" }, { "code": null, "e": 2396, "s": 2393, "text": "23" }, { "code": null, "e": 2590, "s": 2396, "text": "JSON Array of Booleans: JSON array of Booleans contains boolean elements only (either true or false). For example, the array below has 5 elements in it each one of that is either true or false." }, { "code": null, "e": 2629, "s": 2590, "text": "[true, true, true, false, false, true]" }, { "code": null, "e": 2788, "s": 2629, "text": "Example: Here we assign a JSON Array of Booleans to the key boolean in jsonBooleanArray object. Then we access the first element of array using [ ] operator. " }, { "code": null, "e": 2793, "s": 2788, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"para\"></p> <script> var jsonBooleanArray = { // Assigned a JSON array of boolean // to the key \"booleans\". \"booleans\": [true, true, true, false, false, true], }; // Here we accessed the booleans property // of jsonBooleanArray Object. // It returned an boolean array. Then we accessed the // first index of the array // (which is true) using [] syntax. var x = jsonBooleanArray.booleans[0]; // Set the inner HTML of \"para\" paragraph // to the value of variable \"x\". document.getElementById(\"para\").innerHTML = x; </script></body> </html>", "e": 3502, "s": 2793, "text": null }, { "code": null, "e": 3510, "s": 3502, "text": "Output:" }, { "code": null, "e": 3515, "s": 3510, "text": "true" }, { "code": null, "e": 3864, "s": 3515, "text": "JSON Array of Objects: A JSON object is same as JavaScript object. We can also create a JSON Array containing many JSON objects in it, then we can iterate over that array or use the [ ] to get the object we need. In the example below, there are three JSON objects in the array assigned to key “books”. Each object has “name” and “author” property. " }, { "code": null, "e": 4070, "s": 3864, "text": "{\n \"books\":[\n {\"name\":\"Let Us C\", \"author\":\"Yashavant Kanetkar\"}, \n {\"name\":\"Rich Dad Poor Dad\", \"author\":\"Robert Kiyosaki \"}, \n {\"name\":\"Introduction to Algorithms\", \"author\":\"Cormen\"},\n ]\n}" }, { "code": null, "e": 4225, "s": 4070, "text": "Example: Here we assign a JSON Array of Objects to the key books in jsonObjectArray object. Then we access the first element of array using [ ] operator. " }, { "code": null, "e": 4230, "s": 4225, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"para\"></p> <script> var jsonObjectArray = { // Assigned a JSON array of objects // to the key \"books\" \"books\": [ { \"name\": \"Let Us C\", \"author\": \"Yashavant Kanetkar\" }, { \"name\": \"Rich Dad Poor Dad\", \"author\": \"Robert Kiyosaki \" }, { \"name\": \"Introduction to Algorithms\", \"author\": \"Cormen\" }, ] }; // Here we accessed the books property of // jsonObjectArray Object. // It returned an object array. Then we // accessed the first index of the array // (which is an JSON object) using [] syntax var x = jsonObjectArray.books[0]; // Set the inner HTML of \"para\" paragraph // to the value of variable \"x\". document.getElementById(\"para\").innerHTML = x.name + \" by \" + x.author; </script></body> </html>", "e": 5331, "s": 4230, "text": null }, { "code": null, "e": 5339, "s": 5331, "text": "Output:" }, { "code": null, "e": 5370, "s": 5339, "text": "Let Us C by Yashavant Kanetkar" }, { "code": null, "e": 5761, "s": 5370, "text": "5. JSON Array of Arrays OR JSON Multidimensional Array: It is also possible to create a JSON array containing other arrays as elements in it. In the example below we have a JSON array which contains arrays [“a”, “b”, “c”], [“d”, “e”, “f”], [“g” , “h”, “i”] in it. We can use [ ] operator to get the array at any index and use the [ ] operator again to get the element of the selected array." }, { "code": null, "e": 5882, "s": 5761, "text": "{\n \"matrix\": [ \n [ \"a\", \"b\", \"c\" ], \n [ \"d\", \"e\", \"f\" ], \n [ \"g\", \"h\", \"i\" ] \n ],\n};" }, { "code": null, "e": 6036, "s": 5882, "text": "Example: Here we assign a JSON Array of Arrays to the key matrix in jsonMultiArray object. Then we access the first element of array using [ ] operator. " }, { "code": null, "e": 6041, "s": 6036, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"para\"></p> <script> var jsonMultiArray = { // Assigned a JSON array of // Arrays to the key \"matrix\". \"matrix\": [ [\"a\", \"b\", \"c\"], [\"d\", \"e\", \"f\"], [\"g\", \"h\", \"i\"] ], }; // Here we accessed the matrix property // of jsonMultiArray Object. // It returned an matrix(2D array). Then we // accessed the first element of // the first index of matrix using [] syntax. var x = jsonMultiArray.matrix[0][0]; // Set the inner HTML of \"para\" paragraph // to the value of variable \"x\". document.getElementById(\"para\").innerHTML = x; </script></body> </html>", "e": 6813, "s": 6041, "text": null }, { "code": null, "e": 6821, "s": 6813, "text": "Output:" }, { "code": null, "e": 6823, "s": 6821, "text": "a" }, { "code": null, "e": 6838, "s": 6823, "text": "prachisoda1234" }, { "code": null, "e": 6851, "s": 6838, "text": "simmytarika5" }, { "code": null, "e": 6868, "s": 6851, "text": "surinderdawra388" }, { "code": null, "e": 6889, "s": 6868, "text": "JavaScript-Questions" }, { "code": null, "e": 6894, "s": 6889, "text": "JSON" }, { "code": null, "e": 6901, "s": 6894, "text": "Picked" }, { "code": null, "e": 6912, "s": 6901, "text": "JavaScript" }, { "code": null, "e": 6929, "s": 6912, "text": "Web Technologies" }, { "code": null, "e": 7027, "s": 6929, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7088, "s": 7027, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7128, "s": 7088, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 7164, "s": 7128, "text": "JavaScript String includes() Method" }, { "code": null, "e": 7207, "s": 7164, "text": "Implementation of LinkedList in Javascript" }, { "code": null, "e": 7235, "s": 7207, "text": "DOM (Document Object Model)" }, { "code": null, "e": 7268, "s": 7235, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 7318, "s": 7268, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 7380, "s": 7318, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7438, "s": 7380, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Min and Max in a List in Java
24 Jun, 2022 Given an unsorted list of integers, find maximum and minimum values in it. Input : list = [10, 4, 3, 2, 1, 20] Output : max = 20, min = 1 Input : list = [10, 400, 3, 2, 1, -1] Output : max = 400, min = -1 Sorting This is least efficient approach but will get the work done. The idea is to sort the list in natural order, then the first or last element would be the minimum and maximum element respectively. Below’s the implementation in Java. // This java program find minimum and maximum value// of an unsorted list of Integer by using Collectionimport java.util.ArrayList;import java.util.Collections;import java.util.List; public class GFG { // function to find minimum value in an unsorted // list in Java using Collection public static Integer findMin(List<Integer> list) { // check list is empty or not if (list == null || list.size() == 0) { return Integer.MAX_VALUE; } // create a new list to avoid modification // in the original list List<Integer> sortedlist = new ArrayList<>(list); // sort list in natural order Collections.sort(sortedlist); // first element in the sorted list // would be minimum return sortedlist.get(0); } // function return maximum value in an unsorted // list in Java using Collection public static Integer findMax(List<Integer> list) { // check list is empty or not if (list == null || list.size() == 0) { return Integer.MIN_VALUE; } // create a new list to avoid modification // in the original list List<Integer> sortedlist = new ArrayList<>(list); // sort list in natural order Collections.sort(sortedlist); // last element in the sorted list would be maximum return sortedlist.get(sortedlist.size() - 1); } public static void main(String[] args) { // create an ArrayList Object list List<Integer> list = new ArrayList<>(); // add element in ArrayList object list list.add(44); list.add(11); list.add(22); list.add(33); // print min amd max value of ArrayList System.out.println("Min: " + findMin(list)); System.out.println("Max: " + findMax(list)); }} Output: Min: 11 Max: 44 Collections.max() Collections.min() method return the minimum element in the specified collection and Collections.max () returns the maximum element in the specified collection, according to the natural ordering of its elements. // This java program find minimum and maximum value// of an unsorted list of Integer by using Collectionimport java.util.ArrayList;import java.util.Collections;import java.util.List; public class GFG { // function to find minimum value in an unsorted // list in Java using Collection public static Integer findMin(List<Integer> list) { // check list is empty or not if (list == null || list.size() == 0) { return Integer.MAX_VALUE; } // return minimum value of the ArrayList return Collections.min(list); } // function return maximum value in an unsorted // list in Java using Collection public static Integer findMax(List<Integer> list) { // check list is empty or not if (list == null || list.size() == 0) { return Integer.MIN_VALUE; } // return maximum value of the ArrayList return Collections.max(list); } public static void main(String[] args) { // create an ArrayList Object list List<Integer> list = new ArrayList<>(); // add element in ArrayList object list list.add(44); list.add(11); list.add(22); list.add(33); // print min amd max value of ArrayList System.out.println("Min: " + findMin(list)); System.out.println("Max: " + findMax(list)); }} Output: Min: 11 Max: 44 Naive Here is naive way of finding find minimum and maximum value in an unsorted list where we check against all values present in the list and maintain minimum & maximum value found so far. // This java program find minimum and maximum value// of an unsorted list of Integerimport java.util.ArrayList;import java.util.List; public class GFG { // Naive function to find minimum value in an // unsorted list in Java public static Integer findMin(List<Integer> list) { // initialize min to some maximum value Integer min = Integer.MAX_VALUE; // loop through every element in the list and // compare min found so far with current value for (Integer i : list) { // update min if found to be more than // the current element if (min > i) { min = i; } } return min; } // This function return maximum value in an // unsorted list in Java public static Integer findMax(List<Integer> list) { // initialize max variable to minimum value Integer max = Integer.MIN_VALUE; // loop for compare to current max value // with all list element and find maximum value for (Integer i : list) { // update max if found to be less than // the current element if (max < i) { max = i; } } return max; } public static void main(String[] args) { // create an ArrayList Object list List<Integer> list = new ArrayList<>(); // add element in ArrayList object list list.add(44); list.add(11); list.add(22); list.add(33); // print min amd max value of ArrayList System.out.println("Min: " + findMin(list)); System.out.println("Max: " + findMax(list)); }} Output: Min: 11 Max: 44 java-LinkedList Java-List-Programs Technical Scripter 2018 Java Linked List Technical Scripter Linked List Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java Stream In Java ArrayList in Java Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Jun, 2022" }, { "code": null, "e": 128, "s": 53, "text": "Given an unsorted list of integers, find maximum and minimum values in it." }, { "code": null, "e": 260, "s": 128, "text": "Input : list = [10, 4, 3, 2, 1, 20]\nOutput : max = 20, min = 1\n\nInput : list = [10, 400, 3, 2, 1, -1]\nOutput : max = 400, min = -1\n" }, { "code": null, "e": 268, "s": 260, "text": "Sorting" }, { "code": null, "e": 498, "s": 268, "text": "This is least efficient approach but will get the work done. The idea is to sort the list in natural order, then the first or last element would be the minimum and maximum element respectively. Below’s the implementation in Java." }, { "code": "// This java program find minimum and maximum value// of an unsorted list of Integer by using Collectionimport java.util.ArrayList;import java.util.Collections;import java.util.List; public class GFG { // function to find minimum value in an unsorted // list in Java using Collection public static Integer findMin(List<Integer> list) { // check list is empty or not if (list == null || list.size() == 0) { return Integer.MAX_VALUE; } // create a new list to avoid modification // in the original list List<Integer> sortedlist = new ArrayList<>(list); // sort list in natural order Collections.sort(sortedlist); // first element in the sorted list // would be minimum return sortedlist.get(0); } // function return maximum value in an unsorted // list in Java using Collection public static Integer findMax(List<Integer> list) { // check list is empty or not if (list == null || list.size() == 0) { return Integer.MIN_VALUE; } // create a new list to avoid modification // in the original list List<Integer> sortedlist = new ArrayList<>(list); // sort list in natural order Collections.sort(sortedlist); // last element in the sorted list would be maximum return sortedlist.get(sortedlist.size() - 1); } public static void main(String[] args) { // create an ArrayList Object list List<Integer> list = new ArrayList<>(); // add element in ArrayList object list list.add(44); list.add(11); list.add(22); list.add(33); // print min amd max value of ArrayList System.out.println(\"Min: \" + findMin(list)); System.out.println(\"Max: \" + findMax(list)); }}", "e": 2354, "s": 498, "text": null }, { "code": null, "e": 2362, "s": 2354, "text": "Output:" }, { "code": null, "e": 2378, "s": 2362, "text": "Min: 11\nMax: 44" }, { "code": null, "e": 2396, "s": 2378, "text": "Collections.max()" }, { "code": null, "e": 2607, "s": 2396, "text": "Collections.min() method return the minimum element in the specified collection and Collections.max () returns the maximum element in the specified collection, according to the natural ordering of its elements." }, { "code": "// This java program find minimum and maximum value// of an unsorted list of Integer by using Collectionimport java.util.ArrayList;import java.util.Collections;import java.util.List; public class GFG { // function to find minimum value in an unsorted // list in Java using Collection public static Integer findMin(List<Integer> list) { // check list is empty or not if (list == null || list.size() == 0) { return Integer.MAX_VALUE; } // return minimum value of the ArrayList return Collections.min(list); } // function return maximum value in an unsorted // list in Java using Collection public static Integer findMax(List<Integer> list) { // check list is empty or not if (list == null || list.size() == 0) { return Integer.MIN_VALUE; } // return maximum value of the ArrayList return Collections.max(list); } public static void main(String[] args) { // create an ArrayList Object list List<Integer> list = new ArrayList<>(); // add element in ArrayList object list list.add(44); list.add(11); list.add(22); list.add(33); // print min amd max value of ArrayList System.out.println(\"Min: \" + findMin(list)); System.out.println(\"Max: \" + findMax(list)); }}", "e": 3986, "s": 2607, "text": null }, { "code": null, "e": 3994, "s": 3986, "text": "Output:" }, { "code": null, "e": 4010, "s": 3994, "text": "Min: 11\nMax: 44" }, { "code": null, "e": 4016, "s": 4010, "text": "Naive" }, { "code": null, "e": 4201, "s": 4016, "text": "Here is naive way of finding find minimum and maximum value in an unsorted list where we check against all values present in the list and maintain minimum & maximum value found so far." }, { "code": "// This java program find minimum and maximum value// of an unsorted list of Integerimport java.util.ArrayList;import java.util.List; public class GFG { // Naive function to find minimum value in an // unsorted list in Java public static Integer findMin(List<Integer> list) { // initialize min to some maximum value Integer min = Integer.MAX_VALUE; // loop through every element in the list and // compare min found so far with current value for (Integer i : list) { // update min if found to be more than // the current element if (min > i) { min = i; } } return min; } // This function return maximum value in an // unsorted list in Java public static Integer findMax(List<Integer> list) { // initialize max variable to minimum value Integer max = Integer.MIN_VALUE; // loop for compare to current max value // with all list element and find maximum value for (Integer i : list) { // update max if found to be less than // the current element if (max < i) { max = i; } } return max; } public static void main(String[] args) { // create an ArrayList Object list List<Integer> list = new ArrayList<>(); // add element in ArrayList object list list.add(44); list.add(11); list.add(22); list.add(33); // print min amd max value of ArrayList System.out.println(\"Min: \" + findMin(list)); System.out.println(\"Max: \" + findMax(list)); }}", "e": 5881, "s": 4201, "text": null }, { "code": null, "e": 5889, "s": 5881, "text": "Output:" }, { "code": null, "e": 5905, "s": 5889, "text": "Min: 11\nMax: 44" }, { "code": null, "e": 5921, "s": 5905, "text": "java-LinkedList" }, { "code": null, "e": 5940, "s": 5921, "text": "Java-List-Programs" }, { "code": null, "e": 5964, "s": 5940, "text": "Technical Scripter 2018" }, { "code": null, "e": 5969, "s": 5964, "text": "Java" }, { "code": null, "e": 5981, "s": 5969, "text": "Linked List" }, { "code": null, "e": 6000, "s": 5981, "text": "Technical Scripter" }, { "code": null, "e": 6012, "s": 6000, "text": "Linked List" }, { "code": null, "e": 6017, "s": 6012, "text": "Java" }, { "code": null, "e": 6115, "s": 6017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6166, "s": 6115, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 6197, "s": 6166, "text": "How to iterate any Map in Java" }, { "code": null, "e": 6216, "s": 6197, "text": "Interfaces in Java" }, { "code": null, "e": 6231, "s": 6216, "text": "Stream In Java" }, { "code": null, "e": 6249, "s": 6231, "text": "ArrayList in Java" }, { "code": null, "e": 6284, "s": 6249, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 6323, "s": 6284, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 6345, "s": 6323, "text": "Reverse a linked list" }, { "code": null, "e": 6393, "s": 6345, "text": "Stack Data Structure (Introduction and Program)" } ]
Minimum number of Appends needed to make a string palindrome in C++
Given a string, find minimum characters to be appended to make a string palindrome. If string is abcac then we can make string palindrome by appending 2 highlighed characters i.e. abcacba Check if string is already palindrome, if yes then no need to append any characters. One by one remove a character from string and check whether remaining string is palindrome or not Repeat above process until string becomes palidrome Return the number of characters removed so far as a final answer #include <iostream> #include <cstring> using namespace std; bool isPalindrome(char *str) { int n = strlen(str); if (n == 1) { return true; } int start = 0, end = n - 1; while (start < end) { if (str[start] != str[end]) { return false; } ++start; --end; } return true; } int requiredAppends(char *str) { if (isPalindrome(str)) { return 0; } return 1 + requiredAppends(str + 1); } int main() { char *str = "abcac"; cout << "Characters to be appended = " << requiredAppends(str) << endl; return 0; } When you compile and execute above program. It generates following output − Characters to be appended = 2
[ { "code": null, "e": 1271, "s": 1187, "text": "Given a string, find minimum characters to be appended to make a string palindrome." }, { "code": null, "e": 1375, "s": 1271, "text": "If string is abcac then we can make string palindrome by appending 2 highlighed characters i.e. abcacba" }, { "code": null, "e": 1460, "s": 1375, "text": "Check if string is already palindrome, if yes then no need to append any characters." }, { "code": null, "e": 1558, "s": 1460, "text": "One by one remove a character from string and check whether remaining string is palindrome or not" }, { "code": null, "e": 1610, "s": 1558, "text": "Repeat above process until string becomes palidrome" }, { "code": null, "e": 1675, "s": 1610, "text": "Return the number of characters removed so far as a final answer" }, { "code": null, "e": 2256, "s": 1675, "text": "#include <iostream>\n#include <cstring>\nusing namespace std;\nbool isPalindrome(char *str) {\n int n = strlen(str);\n if (n == 1) {\n return true;\n }\n int start = 0, end = n - 1;\n while (start < end) {\n if (str[start] != str[end]) {\n return false;\n }\n ++start;\n --end;\n }\n return true;\n}\nint requiredAppends(char *str) {\n if (isPalindrome(str)) {\n return 0;\n }\n return 1 + requiredAppends(str + 1);\n}\nint main() {\n char *str = \"abcac\";\n cout << \"Characters to be appended = \" << requiredAppends(str) << endl;\n return 0;\n}" }, { "code": null, "e": 2332, "s": 2256, "text": "When you compile and execute above program. It generates following output −" }, { "code": null, "e": 2362, "s": 2332, "text": "Characters to be appended = 2" } ]
How to push data into firebase Realtime Database using ReactJS ?
17 Jun, 2021 The following approach covers how to push data into firebase’s real-time database using react. We have used the firebase module to achieve so. Creating React Application And Installing Module: Step 1: Create a React-app using the following command: npx create-react-app myapp Step 2: After creating your project folder i.e. myapp, move to it using the following command: cd myapp Project structure: Our project structure will look like this. Step 3: After creating the ReactJS application, Install the firebase module using the following command: npm install firebase@8.3.1 --save Step 4: Go to your firebase dashboard and create a new project and copy your credentials. const firebaseConfig = { apiKey: "your api key", authDomain: "your credentials", projectId: "your credentials", storageBucket: "your credentials", messagingSenderId: "your credentials", appId: "your credentials" }; Step 5: Initialize the Firebase into your project by creating firebase.js file with the following code. firebase.js import firebase from 'firebase'; const firebaseConfig = { // Your Credentials}; firebase.initializeApp(firebaseConfig);var database = firebase.database(); export default database; Step 6: Now go to your Realtime Database section in the firebase project and update your security rules. Here we are in testing mode, so we allow both read and write as true. After updating the code shown below, click on publish. Step 7: Now implement the main part. Here, We are going to use a method called set which pushes data to our real-time database. App.js import {useState} from 'react';import database from './firebase'; function App() { const [name , setName] = useState(); const [age , setAge] = useState(); // Push Function const Push = () => { database.ref("user").set({ name : name, age : age, }).catch(alert); } return ( <div className="App" style={{marginTop : 250}}> <center> <input placeholder="Enter your name" value={name} onChange={(e) => setName(e.target.value)}/> <br/><br/> <input placeholder="Enter your age" value={age} onChange={(e) => setAge(e.target.value)}/> <br/><br/> <button onClick={Push}>PUSH</button> </center> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Firebase React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 53, "s": 25, "text": "\n17 Jun, 2021" }, { "code": null, "e": 196, "s": 53, "text": "The following approach covers how to push data into firebase’s real-time database using react. We have used the firebase module to achieve so." }, { "code": null, "e": 246, "s": 196, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 302, "s": 246, "text": "Step 1: Create a React-app using the following command:" }, { "code": null, "e": 329, "s": 302, "text": "npx create-react-app myapp" }, { "code": null, "e": 424, "s": 329, "text": "Step 2: After creating your project folder i.e. myapp, move to it using the following command:" }, { "code": null, "e": 433, "s": 424, "text": "cd myapp" }, { "code": null, "e": 497, "s": 435, "text": "Project structure: Our project structure will look like this." }, { "code": null, "e": 602, "s": 497, "text": "Step 3: After creating the ReactJS application, Install the firebase module using the following command:" }, { "code": null, "e": 636, "s": 602, "text": "npm install firebase@8.3.1 --save" }, { "code": null, "e": 726, "s": 636, "text": "Step 4: Go to your firebase dashboard and create a new project and copy your credentials." }, { "code": null, "e": 977, "s": 726, "text": "const firebaseConfig = {\n apiKey: \"your api key\",\n authDomain: \"your credentials\",\n projectId: \"your credentials\",\n storageBucket: \"your credentials\",\n messagingSenderId: \"your credentials\",\n appId: \"your credentials\"\n};" }, { "code": null, "e": 1081, "s": 977, "text": "Step 5: Initialize the Firebase into your project by creating firebase.js file with the following code." }, { "code": null, "e": 1093, "s": 1081, "text": "firebase.js" }, { "code": "import firebase from 'firebase'; const firebaseConfig = { // Your Credentials}; firebase.initializeApp(firebaseConfig);var database = firebase.database(); export default database;", "e": 1281, "s": 1093, "text": null }, { "code": null, "e": 1512, "s": 1281, "text": "Step 6: Now go to your Realtime Database section in the firebase project and update your security rules. Here we are in testing mode, so we allow both read and write as true. After updating the code shown below, click on publish. " }, { "code": null, "e": 1640, "s": 1512, "text": "Step 7: Now implement the main part. Here, We are going to use a method called set which pushes data to our real-time database." }, { "code": null, "e": 1647, "s": 1640, "text": "App.js" }, { "code": "import {useState} from 'react';import database from './firebase'; function App() { const [name , setName] = useState(); const [age , setAge] = useState(); // Push Function const Push = () => { database.ref(\"user\").set({ name : name, age : age, }).catch(alert); } return ( <div className=\"App\" style={{marginTop : 250}}> <center> <input placeholder=\"Enter your name\" value={name} onChange={(e) => setName(e.target.value)}/> <br/><br/> <input placeholder=\"Enter your age\" value={age} onChange={(e) => setAge(e.target.value)}/> <br/><br/> <button onClick={Push}>PUSH</button> </center> </div> );} export default App;", "e": 2348, "s": 1647, "text": null }, { "code": null, "e": 2461, "s": 2348, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2471, "s": 2461, "text": "npm start" }, { "code": null, "e": 2570, "s": 2471, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2579, "s": 2570, "text": "Firebase" }, { "code": null, "e": 2595, "s": 2579, "text": "React-Questions" }, { "code": null, "e": 2603, "s": 2595, "text": "ReactJS" }, { "code": null, "e": 2620, "s": 2603, "text": "Web Technologies" }, { "code": null, "e": 2718, "s": 2620, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2756, "s": 2718, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2775, "s": 2756, "text": "ReactJS setState()" }, { "code": null, "e": 2843, "s": 2775, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 2878, "s": 2843, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 2899, "s": 2878, "text": "ReactJS defaultProps" }, { "code": null, "e": 2961, "s": 2899, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2994, "s": 2961, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3055, "s": 2994, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3105, "s": 3055, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Introduction To Subnetting
07 Jun, 2022 When a bigger network is divided into smaller networks, to maintain security, then that is known as Subnetting. So, maintenance is easier for smaller networks. Now, let’s talk about dividing a network into two parts: To divide a network into two parts, you need to choose one bit for each Subnet from the host ID part. In the above diagram, there are two Subnets. Note: It is a class C IP so, there are 24 bits in the network id part and 8 bits in the host id part. For Subnet-1: The first bit which is chosen from the host id part is zero and the range will be from (193.1.2.00000000 till you get all 1’s in the host ID part i.e, 193.1.2.01111111) except for the first bit which is chosen zero for subnet id part. Thus, the range of subnet-1: 193.1.2.0 to 193.1.2.127 For Subnet-2: The first bit chosen from the host id part is one and the range will be from (193.1.2.100000000 till you get all 1’s in the host ID part i.e, 193.1.2.11111111). Thus, the range of subnet-2: 193.1.2.128 to 193.1.2.255 Note: To divide a network into four (22) parts you need to choose two bits from the host id part for each subnet i.e, (00, 01, 10, 11).To divide a network into eight (23) parts you need to choose three bits from the host id part for each subnet i.e, (000, 001, 010, 011, 100, 101, 110, 111) and so on. To divide a network into four (22) parts you need to choose two bits from the host id part for each subnet i.e, (00, 01, 10, 11). To divide a network into eight (23) parts you need to choose three bits from the host id part for each subnet i.e, (000, 001, 010, 011, 100, 101, 110, 111) and so on. Example1. An organization is assigned a class C network address of 201.35.2.0. It uses a netmask of 255.255.255.192 to divide this into sub-networks. Which of the following is/are valid host IP addresses? A. 201.35.2.129 B. 201.35.2.191 C. 201.35.2.255 D. Both (A) and (C) Solution: Converting the last octet of the netmask into the binary form: 255.255.255.11000000 Converting the last octet of option A into the binary form: 201.35.2.10000001 Converting the last octet of option B into the binary form: 201.35.2.10111111 Converting the last octet of option C into the binary form: 201.35.2.11111111 From the above, we see that Option B and C is not a valid host IP address (as they are broadcast address of a subnetwork) and OPTION A is not a broadcast address and it can be assigned to a host IP. Example 2. An organization has a class C network address of 201.32.64.0. It uses a subnet mask of 255.255.255.248. Which of the following is NOT a valid broadcast address for any subnetworks? A. 201.32.64.135 B. 201.32.64.240 C. 201.32.64.207 D. 201.32.64.231 Solution: Converting the last octet of the netmask into the binary form: 255.255.255.11111000 Converting the last octet of option A into the binary form: 201.32.64.10000111 Converting the last octet of option B into the binary form: 201.32.64.11110000 Converting the last octet of option C into the binary form: 201.32.64.11001111 Converting the last octet of option D into the binary form: 201.32.64.11100111 From the above, we can see that, in OPTION A, C, and D all the host bits are 1 and give the valid broadcast address of subnetworks. and OPTION B the last three bits of the Host address are not 1 therefore it’s not a valid broadcast address. guptavivek0503 Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Network Topology RSA Algorithm in Cryptography TCP Server-Client implementation in C GSM in Wireless Communication Socket Programming in Python ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC)
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jun, 2022" }, { "code": null, "e": 371, "s": 52, "text": "When a bigger network is divided into smaller networks, to maintain security, then that is known as Subnetting. So, maintenance is easier for smaller networks. Now, let’s talk about dividing a network into two parts: To divide a network into two parts, you need to choose one bit for each Subnet from the host ID part." }, { "code": null, "e": 521, "s": 374, "text": "In the above diagram, there are two Subnets. Note: It is a class C IP so, there are 24 bits in the network id part and 8 bits in the host id part." }, { "code": null, "e": 799, "s": 521, "text": "For Subnet-1: The first bit which is chosen from the host id part is zero and the range will be from (193.1.2.00000000 till you get all 1’s in the host ID part i.e, 193.1.2.01111111) except for the first bit which is chosen zero for subnet id part. Thus, the range of subnet-1:" }, { "code": null, "e": 825, "s": 799, "text": "193.1.2.0 to 193.1.2.127 " }, { "code": null, "e": 1029, "s": 825, "text": "For Subnet-2: The first bit chosen from the host id part is one and the range will be from (193.1.2.100000000 till you get all 1’s in the host ID part i.e, 193.1.2.11111111). Thus, the range of subnet-2:" }, { "code": null, "e": 1057, "s": 1029, "text": "193.1.2.128 to 193.1.2.255 " }, { "code": null, "e": 1063, "s": 1057, "text": "Note:" }, { "code": null, "e": 1359, "s": 1063, "text": "To divide a network into four (22) parts you need to choose two bits from the host id part for each subnet i.e, (00, 01, 10, 11).To divide a network into eight (23) parts you need to choose three bits from the host id part for each subnet i.e, (000, 001, 010, 011, 100, 101, 110, 111) and so on." }, { "code": null, "e": 1489, "s": 1359, "text": "To divide a network into four (22) parts you need to choose two bits from the host id part for each subnet i.e, (00, 01, 10, 11)." }, { "code": null, "e": 1656, "s": 1489, "text": "To divide a network into eight (23) parts you need to choose three bits from the host id part for each subnet i.e, (000, 001, 010, 011, 100, 101, 110, 111) and so on." }, { "code": null, "e": 1861, "s": 1656, "text": "Example1. An organization is assigned a class C network address of 201.35.2.0. It uses a netmask of 255.255.255.192 to divide this into sub-networks. Which of the following is/are valid host IP addresses?" }, { "code": null, "e": 1939, "s": 1861, "text": "A. 201.35.2.129 \nB. 201.35.2.191 \nC. 201.35.2.255 \nD. Both (A) and (C)" }, { "code": null, "e": 1949, "s": 1939, "text": "Solution:" }, { "code": null, "e": 2033, "s": 1949, "text": "Converting the last octet of the netmask into the binary form: 255.255.255.11000000" }, { "code": null, "e": 2111, "s": 2033, "text": "Converting the last octet of option A into the binary form: 201.35.2.10000001" }, { "code": null, "e": 2189, "s": 2111, "text": "Converting the last octet of option B into the binary form: 201.35.2.10111111" }, { "code": null, "e": 2267, "s": 2189, "text": "Converting the last octet of option C into the binary form: 201.35.2.11111111" }, { "code": null, "e": 2390, "s": 2267, "text": "From the above, we see that Option B and C is not a valid host IP address (as they are broadcast address of a subnetwork) " }, { "code": null, "e": 2467, "s": 2390, "text": "and OPTION A is not a broadcast address and it can be assigned to a host IP." }, { "code": null, "e": 2659, "s": 2467, "text": "Example 2. An organization has a class C network address of 201.32.64.0. It uses a subnet mask of 255.255.255.248. Which of the following is NOT a valid broadcast address for any subnetworks?" }, { "code": null, "e": 2742, "s": 2659, "text": "A. 201.32.64.135 \nB. 201.32.64.240 \nC. 201.32.64.207 \nD. 201.32.64.231" }, { "code": null, "e": 2752, "s": 2742, "text": "Solution:" }, { "code": null, "e": 2836, "s": 2752, "text": "Converting the last octet of the netmask into the binary form: 255.255.255.11111000" }, { "code": null, "e": 2915, "s": 2836, "text": "Converting the last octet of option A into the binary form: 201.32.64.10000111" }, { "code": null, "e": 2994, "s": 2915, "text": "Converting the last octet of option B into the binary form: 201.32.64.11110000" }, { "code": null, "e": 3073, "s": 2994, "text": "Converting the last octet of option C into the binary form: 201.32.64.11001111" }, { "code": null, "e": 3152, "s": 3073, "text": "Converting the last octet of option D into the binary form: 201.32.64.11100111" }, { "code": null, "e": 3284, "s": 3152, "text": "From the above, we can see that, in OPTION A, C, and D all the host bits are 1 and give the valid broadcast address of subnetworks." }, { "code": null, "e": 3393, "s": 3284, "text": "and OPTION B the last three bits of the Host address are not 1 therefore it’s not a valid broadcast address." }, { "code": null, "e": 3408, "s": 3393, "text": "guptavivek0503" }, { "code": null, "e": 3426, "s": 3408, "text": "Computer Networks" }, { "code": null, "e": 3434, "s": 3426, "text": "GATE CS" }, { "code": null, "e": 3452, "s": 3434, "text": "Computer Networks" }, { "code": null, "e": 3550, "s": 3452, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3576, "s": 3550, "text": "Types of Network Topology" }, { "code": null, "e": 3606, "s": 3576, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 3644, "s": 3606, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 3674, "s": 3644, "text": "GSM in Wireless Communication" }, { "code": null, "e": 3703, "s": 3674, "text": "Socket Programming in Python" }, { "code": null, "e": 3727, "s": 3703, "text": "ACID Properties in DBMS" }, { "code": null, "e": 3754, "s": 3727, "text": "Types of Operating Systems" }, { "code": null, "e": 3775, "s": 3754, "text": "Normal Forms in DBMS" }, { "code": null, "e": 3824, "s": 3775, "text": "Page Replacement Algorithms in Operating Systems" } ]
Packages in R Programming - GeeksforGeeks
22 Nov, 2021 The package is an appropriate way to organize the work and share it with others. Typically, a package will include code (not only R code!), documentation for the package and the functions inside, some tests to check everything works as it should, and data sets. Packages in R Programming language are a set of R functions, compiled code, and sample data. These are stored under a directory called “library” within the R environment. By default, R installs a group of packages during installation. Once we start the R console, only the default packages are available by default. Other packages that are already installed need to be loaded explicitly to be utilized by the R program that’s getting to use them. A repository is a place where packages are located and stored so you can install packages from it. Organizations and Developers have a local repository, typically they are online and accessible to everyone. Some of the most popular repositories for R packages are: CRAN: Comprehensive R Archive Network(CRAN) is the official repository, it is a network of ftp and web servers maintained by the R community around the world. The R community coordinates it, and for a package to be published in CRAN, the Package needs to pass several tests to ensure that the package is following CRAN policies. Bioconductor: Bioconductor is a topic-specific repository, intended for open source software for bioinformatics. Similar to CRAN, it has its own submission and review processes, and its community is very active having several conferences and meetings per year in order to maintain quality. Github: Github is the most popular repository for open source projects. It’s popular as it comes from the unlimited space for open source, the integration with git, a version control software, and its ease to share and collaborate with others. There are multiple ways to install R Package, some of them are, Installing Packages From CRAN: For installing Package from CRAN we need the name of the package and use the following command: install.packages("package name") Installing Package from CRAN is the most common and easiest way as we just have to use only one command. In order to install more than a package at a time, we just have to write them as a character vector in the first argument of the install.packages() function: Example: install.packages(c("vioplot", "MASS")) Installing Bioconductor Packages: In Bioconductor, the standard way to install a package is by first executing the following script: source("https://bioconductor.org/biocLite.R") This will install some basic functions which are needed to install bioconductor packages, such as the biocLite() function. To install the core packages of Bioconductor just type it without further arguments: biocLite() If we just want a few particular packages from this repository then type their names directly as a character vector: Example: biocLite(c("GenomicFeatures", "AnnotationDbi")) To check what packages are installed on your computer, type this command: installed.packages() To update all the packages, type this command: update.packages() To update a specific package, type this command: install.packages("PACKAGE NAME") In R Studio goto Tools -> Install Package, and there we will get a pop-up window to type the package you want to install: Under Packages, type, and search Package which we want to install and then click on install button. When a package is installed, we are ready to use its functionalities. If we just need a sporadic use of a few functions or data inside a package we can access them with the following notation. packagename::functionname() Example: Let’s access the births function of package babynames. Then type this command, babynames::births Output: There is always confusion between a package and a library, and we find people calling libraries as packages. library(): It is the command used to load a package, and it refers to the place where the package is contained, usually a folder on our computer. Package: It is a collection of functions bundled conveniently. The package is an appropriate way to organize our own work and share it with others. We can just input a vector of names to the install.packages() function to install a package, in the case of the library() function, this is not possible. We can load a set of packages one at a time, or if you prefer, use one of the many work arounds developed by R users. To unload a given package, use the detach() function. The use will be: detach("package:babynames", unload = TRUE) The traditional way of discovering packages is just by learning R, in many tutorials and courses the most popular packages are usually mentioned and used. The first alternative can be to browse categories of CRAN packages. CRAN is the official repository, also gives us the option to browse through packages. Another alternative to finding packages can be R Documentation, a help documentation aggregator for R packages from CRAN, BioConductor, and GitHub, which offers you a search box ready for your requests directly on the main page. kumar_satyam Picked R-Packages R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Convert Factor to Numeric and Numeric to Factor in R Programming Group by function in R using Dplyr How to Change Axis Scales in R Plots?
[ { "code": null, "e": 30315, "s": 30287, "text": "\n22 Nov, 2021" }, { "code": null, "e": 30578, "s": 30315, "text": "The package is an appropriate way to organize the work and share it with others. Typically, a package will include code (not only R code!), documentation for the package and the functions inside, some tests to check everything works as it should, and data sets. " }, { "code": null, "e": 31026, "s": 30578, "text": "Packages in R Programming language are a set of R functions, compiled code, and sample data. These are stored under a directory called “library” within the R environment. By default, R installs a group of packages during installation. Once we start the R console, only the default packages are available by default. Other packages that are already installed need to be loaded explicitly to be utilized by the R program that’s getting to use them. " }, { "code": null, "e": 31292, "s": 31026, "text": "A repository is a place where packages are located and stored so you can install packages from it. Organizations and Developers have a local repository, typically they are online and accessible to everyone. Some of the most popular repositories for R packages are: " }, { "code": null, "e": 31621, "s": 31292, "text": "CRAN: Comprehensive R Archive Network(CRAN) is the official repository, it is a network of ftp and web servers maintained by the R community around the world. The R community coordinates it, and for a package to be published in CRAN, the Package needs to pass several tests to ensure that the package is following CRAN policies." }, { "code": null, "e": 31911, "s": 31621, "text": "Bioconductor: Bioconductor is a topic-specific repository, intended for open source software for bioinformatics. Similar to CRAN, it has its own submission and review processes, and its community is very active having several conferences and meetings per year in order to maintain quality." }, { "code": null, "e": 32155, "s": 31911, "text": "Github: Github is the most popular repository for open source projects. It’s popular as it comes from the unlimited space for open source, the integration with git, a version control software, and its ease to share and collaborate with others." }, { "code": null, "e": 32220, "s": 32155, "text": "There are multiple ways to install R Package, some of them are, " }, { "code": null, "e": 32347, "s": 32220, "text": "Installing Packages From CRAN: For installing Package from CRAN we need the name of the package and use the following command:" }, { "code": null, "e": 32380, "s": 32347, "text": "install.packages(\"package name\")" }, { "code": null, "e": 32643, "s": 32380, "text": "Installing Package from CRAN is the most common and easiest way as we just have to use only one command. In order to install more than a package at a time, we just have to write them as a character vector in the first argument of the install.packages() function:" }, { "code": null, "e": 32653, "s": 32643, "text": "Example: " }, { "code": null, "e": 32692, "s": 32653, "text": "install.packages(c(\"vioplot\", \"MASS\"))" }, { "code": null, "e": 32825, "s": 32692, "text": "Installing Bioconductor Packages: In Bioconductor, the standard way to install a package is by first executing the following script:" }, { "code": null, "e": 32871, "s": 32825, "text": "source(\"https://bioconductor.org/biocLite.R\")" }, { "code": null, "e": 33079, "s": 32871, "text": "This will install some basic functions which are needed to install bioconductor packages, such as the biocLite() function. To install the core packages of Bioconductor just type it without further arguments:" }, { "code": null, "e": 33090, "s": 33079, "text": "biocLite()" }, { "code": null, "e": 33207, "s": 33090, "text": "If we just want a few particular packages from this repository then type their names directly as a character vector:" }, { "code": null, "e": 33217, "s": 33207, "text": "Example: " }, { "code": null, "e": 33265, "s": 33217, "text": "biocLite(c(\"GenomicFeatures\", \"AnnotationDbi\"))" }, { "code": null, "e": 33340, "s": 33265, "text": "To check what packages are installed on your computer, type this command: " }, { "code": null, "e": 33361, "s": 33340, "text": "installed.packages()" }, { "code": null, "e": 33409, "s": 33361, "text": "To update all the packages, type this command: " }, { "code": null, "e": 33427, "s": 33409, "text": "update.packages()" }, { "code": null, "e": 33477, "s": 33427, "text": "To update a specific package, type this command: " }, { "code": null, "e": 33510, "s": 33477, "text": "install.packages(\"PACKAGE NAME\")" }, { "code": null, "e": 33633, "s": 33510, "text": "In R Studio goto Tools -> Install Package, and there we will get a pop-up window to type the package you want to install: " }, { "code": null, "e": 33734, "s": 33633, "text": "Under Packages, type, and search Package which we want to install and then click on install button. " }, { "code": null, "e": 33927, "s": 33734, "text": "When a package is installed, we are ready to use its functionalities. If we just need a sporadic use of a few functions or data inside a package we can access them with the following notation." }, { "code": null, "e": 33956, "s": 33927, "text": " packagename::functionname()" }, { "code": null, "e": 34046, "s": 33956, "text": "Example: Let’s access the births function of package babynames. Then type this command, " }, { "code": null, "e": 34064, "s": 34046, "text": "babynames::births" }, { "code": null, "e": 34073, "s": 34064, "text": "Output: " }, { "code": null, "e": 34183, "s": 34073, "text": "There is always confusion between a package and a library, and we find people calling libraries as packages. " }, { "code": null, "e": 34329, "s": 34183, "text": "library(): It is the command used to load a package, and it refers to the place where the package is contained, usually a folder on our computer." }, { "code": null, "e": 34477, "s": 34329, "text": "Package: It is a collection of functions bundled conveniently. The package is an appropriate way to organize our own work and share it with others." }, { "code": null, "e": 34750, "s": 34477, "text": "We can just input a vector of names to the install.packages() function to install a package, in the case of the library() function, this is not possible. We can load a set of packages one at a time, or if you prefer, use one of the many work arounds developed by R users. " }, { "code": null, "e": 34822, "s": 34750, "text": "To unload a given package, use the detach() function. The use will be: " }, { "code": null, "e": 34865, "s": 34822, "text": "detach(\"package:babynames\", unload = TRUE)" }, { "code": null, "e": 35175, "s": 34865, "text": "The traditional way of discovering packages is just by learning R, in many tutorials and courses the most popular packages are usually mentioned and used. The first alternative can be to browse categories of CRAN packages. CRAN is the official repository, also gives us the option to browse through packages. " }, { "code": null, "e": 35404, "s": 35175, "text": "Another alternative to finding packages can be R Documentation, a help documentation aggregator for R packages from CRAN, BioConductor, and GitHub, which offers you a search box ready for your requests directly on the main page." }, { "code": null, "e": 35417, "s": 35404, "text": "kumar_satyam" }, { "code": null, "e": 35424, "s": 35417, "text": "Picked" }, { "code": null, "e": 35435, "s": 35424, "text": "R-Packages" }, { "code": null, "e": 35446, "s": 35435, "text": "R Language" }, { "code": null, "e": 35544, "s": 35446, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35589, "s": 35544, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 35647, "s": 35589, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 35699, "s": 35647, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 35731, "s": 35699, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 35794, "s": 35731, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 35838, "s": 35794, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 35890, "s": 35838, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 35955, "s": 35890, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 35990, "s": 35955, "text": "Group by function in R using Dplyr" } ]
Visualizing Bubble sort using Python - GeeksforGeeks
11 Oct, 2020 Prerequisites: Introduction to Matplotlib, Introduction to PyQt5, Bubble Sort Learning any algorithm can be difficult, and since you are here at GeekforGeeks, you definitely love to understand and implement various algorithms. It is tough for every one of us to understand algorithms at the first go. We tend to understand those things more which are visualized properly. One of the basic problems that we start with is sorting algorithms. It might have been challenging for you to learn those algorithms so here we are today showing you how you can visualize them. Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. To install it type the below command in the terminal. pip install matplotlib PyQt5: PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. To install it type the below command in the terminal. pip install PyQt5==5.9.2 So, with that all set up, let’s get started with the actual coding. First, create a file named main.py and add the following lines of code to it. Python3 # importsimport randomfrom matplotlib import pyplot as plt, animation # helper methodsdef swap(A, i, j): A[i], A[j] = A[j], A[i] # algorithmsdef bubblesort(A): swapped = True for i in range(len(A) - 1): if not swapped: return swapped = False for j in range(len(A) - 1 - i): if A[j] > A[j + 1]: swap(A, j, j + 1) swapped = True yield A def visualize(): N = 30 A = list(range(1, N + 1)) random.shuffle(A) # creates a generator object containing all # the states of the array while performing # sorting algorithm generator = bubblesort(A) # creates a figure and subsequent subplots fig, ax = plt.subplots() ax.set_title("Bubble Sort O(n\N{SUPERSCRIPT TWO})") bar_sub = ax.bar(range(len(A)), A, align="edge") # sets the maximum limit for the x-axis ax.set_xlim(0, N) text = ax.text(0.02, 0.95, "", transform=ax.transAxes) iteration = [0] # helper function to update each frame in plot def update(A, rects, iteration): for rect, val in zip(rects, A): rect.set_height(val) iteration[0] += 1 text.set_text(f"# of operations: {iteration[0]}") # creating animation object for rendering the iteration anim = animation.FuncAnimation( fig, func=update, fargs=(bar_sub, iteration), frames=generator, repeat=True, blit=False, interval=15, save_count=90000, ) # for showing the animation on screen plt.show() plt.close() if __name__ == "__main__": visualize() Output: Algorithms-BubbleSort BubbleSort Data Visualization Python-matplotlib Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 31547, "s": 31519, "text": "\n11 Oct, 2020" }, { "code": null, "e": 31625, "s": 31547, "text": "Prerequisites: Introduction to Matplotlib, Introduction to PyQt5, Bubble Sort" }, { "code": null, "e": 32113, "s": 31625, "text": "Learning any algorithm can be difficult, and since you are here at GeekforGeeks, you definitely love to understand and implement various algorithms. It is tough for every one of us to understand algorithms at the first go. We tend to understand those things more which are visualized properly. One of the basic problems that we start with is sorting algorithms. It might have been challenging for you to learn those algorithms so here we are today showing you how you can visualize them." }, { "code": null, "e": 32260, "s": 32113, "text": "Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. To install it type the below command in the terminal." }, { "code": null, "e": 32283, "s": 32260, "text": "pip install matplotlib" }, { "code": null, "e": 32549, "s": 32283, "text": " PyQt5: PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. To install it type the below command in the terminal." }, { "code": null, "e": 32574, "s": 32549, "text": "pip install PyQt5==5.9.2" }, { "code": null, "e": 32720, "s": 32574, "text": "So, with that all set up, let’s get started with the actual coding. First, create a file named main.py and add the following lines of code to it." }, { "code": null, "e": 32728, "s": 32720, "text": "Python3" }, { "code": "# importsimport randomfrom matplotlib import pyplot as plt, animation # helper methodsdef swap(A, i, j): A[i], A[j] = A[j], A[i] # algorithmsdef bubblesort(A): swapped = True for i in range(len(A) - 1): if not swapped: return swapped = False for j in range(len(A) - 1 - i): if A[j] > A[j + 1]: swap(A, j, j + 1) swapped = True yield A def visualize(): N = 30 A = list(range(1, N + 1)) random.shuffle(A) # creates a generator object containing all # the states of the array while performing # sorting algorithm generator = bubblesort(A) # creates a figure and subsequent subplots fig, ax = plt.subplots() ax.set_title(\"Bubble Sort O(n\\N{SUPERSCRIPT TWO})\") bar_sub = ax.bar(range(len(A)), A, align=\"edge\") # sets the maximum limit for the x-axis ax.set_xlim(0, N) text = ax.text(0.02, 0.95, \"\", transform=ax.transAxes) iteration = [0] # helper function to update each frame in plot def update(A, rects, iteration): for rect, val in zip(rects, A): rect.set_height(val) iteration[0] += 1 text.set_text(f\"# of operations: {iteration[0]}\") # creating animation object for rendering the iteration anim = animation.FuncAnimation( fig, func=update, fargs=(bar_sub, iteration), frames=generator, repeat=True, blit=False, interval=15, save_count=90000, ) # for showing the animation on screen plt.show() plt.close() if __name__ == \"__main__\": visualize()", "e": 34386, "s": 32728, "text": null }, { "code": null, "e": 34394, "s": 34386, "text": "Output:" }, { "code": null, "e": 34416, "s": 34394, "text": "Algorithms-BubbleSort" }, { "code": null, "e": 34427, "s": 34416, "text": "BubbleSort" }, { "code": null, "e": 34446, "s": 34427, "text": "Data Visualization" }, { "code": null, "e": 34464, "s": 34446, "text": "Python-matplotlib" }, { "code": null, "e": 34476, "s": 34464, "text": "Python-PyQt" }, { "code": null, "e": 34483, "s": 34476, "text": "Python" }, { "code": null, "e": 34581, "s": 34483, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34609, "s": 34581, "text": "Read JSON file using Python" }, { "code": null, "e": 34659, "s": 34609, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 34681, "s": 34659, "text": "Python map() function" }, { "code": null, "e": 34725, "s": 34681, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 34743, "s": 34725, "text": "Python Dictionary" }, { "code": null, "e": 34766, "s": 34743, "text": "Taking input in Python" }, { "code": null, "e": 34798, "s": 34766, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34833, "s": 34798, "text": "Read a file line by line in Python" }, { "code": null, "e": 34855, "s": 34833, "text": "Enumerate() in Python" } ]