title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
p5.js | keyPressed() Function
14 Jan, 2022 The keyPressed() function is invoked whenever a key is pressed. The most recently typed ASCII key is stored into the ‘key’ variable, however it does not distinguish between uppercase and lowercase characters. The non-ASCII character codes can be accessed in the ‘keyCode’ variable with their respective names.Holding down a key may cause multiple keyPressed() calls. This is due to how the Operating System handles keypressed and depends on how the computer is configured. A browser may have its own default behavior attached to various keys. This can be prevented by adding “return false” to the end of the method.Syntax: keyPressed() Parameters: This method does not accept any parameters.Below examples illustrate the keyPressed() function in p5.js:Example 1: javascript function setup() { createCanvas(600, 200); textSize(20); text("Press any key to display it " + "on the screen", 10, 20);} function keyPressed() { clear(); textSize(20); text("Press any key to display it " + "on the screen", 10, 20); textSize(100); text(key, 100, 150);} Output: Example 2: javascript let opac = 128; function setup() { createCanvas(700, 200); background(0, 128, 0, opac); textSize(22); text("Press the left and right arrow" + " keys to change the opacity" + " of the color.", 10, 20);} function keyPressed() { clear(); textSize(50); text("Pressing: " + key, 100, 150); // Reduce opacity if the left arrow is pressed if (key == "ArrowLeft" && opac > 0) opac -= 20; // Increase opacity if the left arrow is pressed else if (key == "ArrowRight" && opac < 255) opac += 20; // Set the new background color background(0, 128, 0, opac); textSize(22); text("Press the left and right arrow" + " keys to change the opacity" + " of the color.", 10, 20);} Output: Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Reference: https://p5js.org/reference/#/p5/keyPressed adnanirshad158 JavaScript-p5.js 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 Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills 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": "\n14 Jan, 2022" }, { "code": null, "e": 653, "s": 28, "text": "The keyPressed() function is invoked whenever a key is pressed. The most recently typed ASCII key is stored into the ‘key’ variable, however it does not distinguish between uppercase and lowercase characters. The non-ASCII character codes can be accessed in the ‘keyCode’ variable with their respective names.Holding down a key may cause multiple keyPressed() calls. This is due to how the Operating System handles keypressed and depends on how the computer is configured. A browser may have its own default behavior attached to various keys. This can be prevented by adding “return false” to the end of the method.Syntax: " }, { "code": null, "e": 666, "s": 653, "text": "keyPressed()" }, { "code": null, "e": 795, "s": 666, "text": "Parameters: This method does not accept any parameters.Below examples illustrate the keyPressed() function in p5.js:Example 1: " }, { "code": null, "e": 806, "s": 795, "text": "javascript" }, { "code": "function setup() { createCanvas(600, 200); textSize(20); text(\"Press any key to display it \" + \"on the screen\", 10, 20);} function keyPressed() { clear(); textSize(20); text(\"Press any key to display it \" + \"on the screen\", 10, 20); textSize(100); text(key, 100, 150);}", "e": 1102, "s": 806, "text": null }, { "code": null, "e": 1112, "s": 1102, "text": "Output: " }, { "code": null, "e": 1125, "s": 1112, "text": "Example 2: " }, { "code": null, "e": 1136, "s": 1125, "text": "javascript" }, { "code": "let opac = 128; function setup() { createCanvas(700, 200); background(0, 128, 0, opac); textSize(22); text(\"Press the left and right arrow\" + \" keys to change the opacity\" + \" of the color.\", 10, 20);} function keyPressed() { clear(); textSize(50); text(\"Pressing: \" + key, 100, 150); // Reduce opacity if the left arrow is pressed if (key == \"ArrowLeft\" && opac > 0) opac -= 20; // Increase opacity if the left arrow is pressed else if (key == \"ArrowRight\" && opac < 255) opac += 20; // Set the new background color background(0, 128, 0, opac); textSize(22); text(\"Press the left and right arrow\" + \" keys to change the opacity\" + \" of the color.\", 10, 20);}", "e": 1849, "s": 1136, "text": null }, { "code": null, "e": 1859, "s": 1849, "text": "Output: " }, { "code": null, "e": 2050, "s": 1859, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Reference: https://p5js.org/reference/#/p5/keyPressed " }, { "code": null, "e": 2065, "s": 2050, "text": "adnanirshad158" }, { "code": null, "e": 2082, "s": 2065, "text": "JavaScript-p5.js" }, { "code": null, "e": 2093, "s": 2082, "text": "JavaScript" }, { "code": null, "e": 2110, "s": 2093, "text": "Web Technologies" }, { "code": null, "e": 2208, "s": 2110, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2269, "s": 2208, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2341, "s": 2269, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2381, "s": 2341, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2434, "s": 2381, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2475, "s": 2434, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2508, "s": 2475, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2570, "s": 2508, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2631, "s": 2570, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2681, "s": 2631, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
C# Program to Count Number of Vowels and Consonants in a Given String
07 Jan, 2022 C# is a general-purpose programming language it is used to create mobile apps, desktop apps, web sites, and games. As we know that a, e, i, o, u are vowels, and the remaining alphabet is known as a consonant in English so now using C# language we will create a program that will return us the total number of vowels and consonants present in the given string. Example: Input: geeksforgeeks Output: Total number of vowels = 5 Total number of consonants = 8 Input: HelloGFG Output: Total number of vowels = 2 Total number of consonants = 6 Approach: To print the total number of Vowels and consonants from a given String we use the following approach: Store the string using string datatype. Declare two variables to count the number of vowels and consonants. Now using the length property find the length of the given string Now iterate the string from left to right and check if the character is either vowel or a consonant. If the character encountered is a vowel increase the count of vowel else increases the count of consonant. Example 1: C# // C# program to print the total number of Vowels// and consonants from a given stringusing System; class GFG{ public static void Main(){ string inputstring; int i, len, vowels, consonants; inputstring = "geeksforgeeks"; vowels = 0; consonants = 0; len = inputstring.Length; // Iterating the string from left to right for(i = 0; i < len; i++) { // Check if the character is a vowel if (inputstring[i] == 'a' || inputstring[i] == 'e' || inputstring[i] == 'i' || inputstring[i] == 'o' || inputstring[i] == 'u' || inputstring[i] == 'A' || inputstring[i] == 'E' || inputstring[i] == 'I' || inputstring[i] == 'O' || inputstring[i] == 'U') { // Increment the vowels vowels++; } // Check if the character is a alphabet // other than vowels else if ((inputstring[i] >= 'a' && inputstring[i] <= 'z') || (inputstring[i] >= 'A' && inputstring[i] <= 'Z')) { // Increment the consonants consonants++; } } // Display the count of vowels and consonant Console.WriteLine("count of vowel = " + vowels); Console.WriteLine("count of consonant = " + consonants);}} count of vowel = 5 count of consonant = 8 Example 2: C# // C# program to print the total number of Vowels// and consonants from a given stringusing System; class GFG{ public static void Main(){ char[] inputstring = new char[100]; int i, vowels, consonants, x; vowels = 0; consonants = 0; // Enter the length of the string Console.WriteLine("Please enter the length of the string:\n"); x = int.Parse(Console.ReadLine()); // Enter the string Console.WriteLine("Enter string:\n"); for (i = 0; i < x; i++) { inputstring[i] = Convert.ToChar(Console.Read()); } // Iterating the string for (i = 0; inputstring[i] != '\0'; i++) { // Check if the character is a vowel if (inputstring[i] == 'a' || inputstring[i] == 'e' || inputstring[i] == 'i' || inputstring[i] == 'o' || inputstring[i] == 'u' || inputstring[i] == 'A' || inputstring[i] == 'E' || inputstring[i] == 'I' || inputstring[i] == 'O' || inputstring[i] == 'U') { // Increment the vowels vowels++; } else { // Increment the consonants consonants++; } } // Display the count of vowels and consonant Console.WriteLine("\ncount of vowel = " + vowels); Console.WriteLine("count of consonant = " + consonants); Console.ReadLine(); Console.ReadLine();}} Output: Please enter the length of the string: 6 Enter string: HeyGFG count of vowel = 1 count of consonant = 5 anikakapoor rkbhola5 CSharp-programs CSharp-Strings-Programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2022" }, { "code": null, "e": 125, "s": 28, "text": "C# is a general-purpose programming language it is used to create mobile apps, desktop apps, web" }, { "code": null, "e": 388, "s": 125, "text": "sites, and games. As we know that a, e, i, o, u are vowels, and the remaining alphabet is known as a consonant in English so now using C# language we will create a program that will return us the total number of vowels and consonants present in the given string." }, { "code": null, "e": 397, "s": 388, "text": "Example:" }, { "code": null, "e": 567, "s": 397, "text": "Input: geeksforgeeks\nOutput: Total number of vowels = 5\nTotal number of consonants = 8\n\nInput: HelloGFG\nOutput: Total number of vowels = 2\nTotal number of consonants = 6" }, { "code": null, "e": 578, "s": 567, "text": "Approach: " }, { "code": null, "e": 681, "s": 578, "text": "To print the total number of Vowels and consonants from a given String we use the following approach: " }, { "code": null, "e": 721, "s": 681, "text": "Store the string using string datatype." }, { "code": null, "e": 789, "s": 721, "text": "Declare two variables to count the number of vowels and consonants." }, { "code": null, "e": 855, "s": 789, "text": "Now using the length property find the length of the given string" }, { "code": null, "e": 956, "s": 855, "text": "Now iterate the string from left to right and check if the character is either vowel or a consonant." }, { "code": null, "e": 1063, "s": 956, "text": "If the character encountered is a vowel increase the count of vowel else increases the count of consonant." }, { "code": null, "e": 1074, "s": 1063, "text": "Example 1:" }, { "code": null, "e": 1077, "s": 1074, "text": "C#" }, { "code": "// C# program to print the total number of Vowels// and consonants from a given stringusing System; class GFG{ public static void Main(){ string inputstring; int i, len, vowels, consonants; inputstring = \"geeksforgeeks\"; vowels = 0; consonants = 0; len = inputstring.Length; // Iterating the string from left to right for(i = 0; i < len; i++) { // Check if the character is a vowel if (inputstring[i] == 'a' || inputstring[i] == 'e' || inputstring[i] == 'i' || inputstring[i] == 'o' || inputstring[i] == 'u' || inputstring[i] == 'A' || inputstring[i] == 'E' || inputstring[i] == 'I' || inputstring[i] == 'O' || inputstring[i] == 'U') { // Increment the vowels vowels++; } // Check if the character is a alphabet // other than vowels else if ((inputstring[i] >= 'a' && inputstring[i] <= 'z') || (inputstring[i] >= 'A' && inputstring[i] <= 'Z')) { // Increment the consonants consonants++; } } // Display the count of vowels and consonant Console.WriteLine(\"count of vowel = \" + vowels); Console.WriteLine(\"count of consonant = \" + consonants);}}", "e": 2395, "s": 1077, "text": null }, { "code": null, "e": 2437, "s": 2395, "text": "count of vowel = 5\ncount of consonant = 8" }, { "code": null, "e": 2448, "s": 2437, "text": "Example 2:" }, { "code": null, "e": 2451, "s": 2448, "text": "C#" }, { "code": "// C# program to print the total number of Vowels// and consonants from a given stringusing System; class GFG{ public static void Main(){ char[] inputstring = new char[100]; int i, vowels, consonants, x; vowels = 0; consonants = 0; // Enter the length of the string Console.WriteLine(\"Please enter the length of the string:\\n\"); x = int.Parse(Console.ReadLine()); // Enter the string Console.WriteLine(\"Enter string:\\n\"); for (i = 0; i < x; i++) { inputstring[i] = Convert.ToChar(Console.Read()); } // Iterating the string for (i = 0; inputstring[i] != '\\0'; i++) { // Check if the character is a vowel if (inputstring[i] == 'a' || inputstring[i] == 'e' || inputstring[i] == 'i' || inputstring[i] == 'o' || inputstring[i] == 'u' || inputstring[i] == 'A' || inputstring[i] == 'E' || inputstring[i] == 'I' || inputstring[i] == 'O' || inputstring[i] == 'U') { // Increment the vowels vowels++; } else { // Increment the consonants consonants++; } } // Display the count of vowels and consonant Console.WriteLine(\"\\ncount of vowel = \" + vowels); Console.WriteLine(\"count of consonant = \" + consonants); Console.ReadLine(); Console.ReadLine();}}", "e": 3879, "s": 2451, "text": null }, { "code": null, "e": 3887, "s": 3879, "text": "Output:" }, { "code": null, "e": 3991, "s": 3887, "text": "Please enter the length of the string:\n6\nEnter string:\nHeyGFG\ncount of vowel = 1\ncount of consonant = 5" }, { "code": null, "e": 4003, "s": 3991, "text": "anikakapoor" }, { "code": null, "e": 4012, "s": 4003, "text": "rkbhola5" }, { "code": null, "e": 4028, "s": 4012, "text": "CSharp-programs" }, { "code": null, "e": 4052, "s": 4028, "text": "CSharp-Strings-Programs" }, { "code": null, "e": 4059, "s": 4052, "text": "Picked" }, { "code": null, "e": 4062, "s": 4059, "text": "C#" } ]
C Language Introduction
31 May, 2022 C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of the C language include low-level memory access, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like an operating system or compiler development. Many later languages have borrowed syntax/features directly or indirectly from the C language. Like syntax of Java, PHP, JavaScript, and many other languages are mainly based on the C language. C++ is nearly a superset of C language (Few programs may compile in C, but not in C++). Beginning with C programming: Structure of a C program After the above discussion, we can formally assess the structure of a C program. By structure, it is meant that any program can be written in this structure only. Writing a C program in any other structure will hence lead to a Compilation Error.The structure of a C program is as follows: Structure of a C program After the above discussion, we can formally assess the structure of a C program. By structure, it is meant that any program can be written in this structure only. Writing a C program in any other structure will hence lead to a Compilation Error.The structure of a C program is as follows: The components of the above structure are: Header Files Inclusion: The first and foremost component is the inclusion of the Header files in a C program. A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files.Some of C Header files: stddef.h – Defines several useful types and macros.stdint.h – Defines exact width integer types.stdio.h – Defines core input and output functionsstdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocationstring.h – Defines string handling functionsmath.h – Defines common mathematical functionsMain Method Declaration: The next part of a C program is to declare the main() function. The syntax to declare the main function is:Syntax to Declare the main method: The components of the above structure are: Header Files Inclusion: The first and foremost component is the inclusion of the Header files in a C program. A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files.Some of C Header files: stddef.h – Defines several useful types and macros.stdint.h – Defines exact width integer types.stdio.h – Defines core input and output functionsstdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocationstring.h – Defines string handling functionsmath.h – Defines common mathematical functionsMain Method Declaration: The next part of a C program is to declare the main() function. The syntax to declare the main function is:Syntax to Declare the main method: Header Files Inclusion: The first and foremost component is the inclusion of the Header files in a C program. A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files.Some of C Header files: stddef.h – Defines several useful types and macros.stdint.h – Defines exact width integer types.stdio.h – Defines core input and output functionsstdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocationstring.h – Defines string handling functionsmath.h – Defines common mathematical functionsMain Method Declaration: The next part of a C program is to declare the main() function. The syntax to declare the main function is:Syntax to Declare the main method: Header Files Inclusion: The first and foremost component is the inclusion of the Header files in a C program. A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files.Some of C Header files: stddef.h – Defines several useful types and macros.stdint.h – Defines exact width integer types.stdio.h – Defines core input and output functionsstdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocationstring.h – Defines string handling functionsmath.h – Defines common mathematical functions stddef.h – Defines several useful types and macros. stdint.h – Defines exact width integer types. stdio.h – Defines core input and output functions stdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocation string.h – Defines string handling functions math.h – Defines common mathematical functions Main Method Declaration: The next part of a C program is to declare the main() function. The syntax to declare the main function is:Syntax to Declare the main method: int main() {} Variable Declaration: The next part of any C program is the variable declaration. It refers to the variables that are to be used in the function. Please note that in the C program, no variable can be used without being declared. Also in a C program, the variables are to be declared before any operation in the function.Example: Variable Declaration: The next part of any C program is the variable declaration. It refers to the variables that are to be used in the function. Please note that in the C program, no variable can be used without being declared. Also in a C program, the variables are to be declared before any operation in the function.Example: int main() { int a; . . Body: The body of a function in the C program, refers to the operations that are performed in the functions. It can be anything like manipulations, searching, sorting, printing, etc.Example: Body: The body of a function in the C program, refers to the operations that are performed in the functions. It can be anything like manipulations, searching, sorting, printing, etc.Example: int main() { int a; printf("%d", a); . . Return Statement: The last part of any C program is the return statement. The return statement refers to the returning of the values from a function. This return statement and return value depend upon the return type of the function. For example, if the return type is void, then there will be no return statement. In any other case, there will be a return statement and the return value will be of the type of the specified return type.Example: Return Statement: The last part of any C program is the return statement. The return statement refers to the returning of the values from a function. This return statement and return value depend upon the return type of the function. For example, if the return type is void, then there will be no return statement. In any other case, there will be a return statement and the return value will be of the type of the specified return type.Example: int main() { int a; printf("%d", a); return 0; } Writing first program: Following is first program in C Writing first program: Following is first program in C C #include <stdio.h>int main(void){ printf("GeeksQuiz"); return 0;} Let us analyze the program line by line. Line 1: [ #include <stdio.h> ] In a C program, all lines that start with # are processed by a preprocessor which is a program invoked by the compiler. In a very basic term, the preprocessor takes a C program and produces another C program. The produced program has no lines starting with #, all such lines are processed by the preprocessor. In the above example, the preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called header files in C. These header files generally contain declarations of functions. We need stdio.h for the function printf() used in the program. Line 2 [ int main(void) ] There must be a starting point from where execution of compiled C program begins. In C, the execution typically begins with the first line of main(). The void written in brackets indicates that the main doesn’t take any parameter (See this for more details). main() can be written to take parameters also. We will be covering that in future posts. The int was written before main indicates return type of main(). The value returned by main indicates the status of program termination. See this post for more details on the return type.Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define scope and are mainly used in functions and control statements like if, else, loops. All functions must start and end with curly brackets. Line 4 [ printf(“GeeksQuiz”); ] printf() is a standard library function to print something on standard output. The semicolon at the end of printf indicates line termination. In C, a semicolon is always used to indicate end of a statement. Line 5 [ return 0; ] The return statement returns the value from main(). The returned value may be used by an operating system to know the termination status of your program. The value 0 typically means successful termination. How to execute the above program: In order to execute the above program, we need to first compile it using a compiler and then we can run the generated executable. There are online IDEs available for free like https://ide.geeksforgeeks.org/, http://ideone.com/, or http://codepad.org/ that can be used to start development in C without installing a compiler.Windows: There are many free IDEs available for developing programs in C like Code Blocks and Dev-CPP. IDEs provide us with environment to develop code, compile it and finally execute it. We strongly recommend Code Blocks.Linux: gcc compiler comes bundled with Linux which compiles C programs and generates executable for us to run. Code Blocks can also be used with Linux. Let us analyze the program line by line. Line 1: [ #include <stdio.h> ] In a C program, all lines that start with # are processed by a preprocessor which is a program invoked by the compiler. In a very basic term, the preprocessor takes a C program and produces another C program. The produced program has no lines starting with #, all such lines are processed by the preprocessor. In the above example, the preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called header files in C. These header files generally contain declarations of functions. We need stdio.h for the function printf() used in the program. Line 2 [ int main(void) ] There must be a starting point from where execution of compiled C program begins. In C, the execution typically begins with the first line of main(). The void written in brackets indicates that the main doesn’t take any parameter (See this for more details). main() can be written to take parameters also. We will be covering that in future posts. The int was written before main indicates return type of main(). The value returned by main indicates the status of program termination. See this post for more details on the return type.Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define scope and are mainly used in functions and control statements like if, else, loops. All functions must start and end with curly brackets. Line 4 [ printf(“GeeksQuiz”); ] printf() is a standard library function to print something on standard output. The semicolon at the end of printf indicates line termination. In C, a semicolon is always used to indicate end of a statement. Line 5 [ return 0; ] The return statement returns the value from main(). The returned value may be used by an operating system to know the termination status of your program. The value 0 typically means successful termination. How to execute the above program: In order to execute the above program, we need to first compile it using a compiler and then we can run the generated executable. There are online IDEs available for free like https://ide.geeksforgeeks.org/, http://ideone.com/, or http://codepad.org/ that can be used to start development in C without installing a compiler.Windows: There are many free IDEs available for developing programs in C like Code Blocks and Dev-CPP. IDEs provide us with environment to develop code, compile it and finally execute it. We strongly recommend Code Blocks.Linux: gcc compiler comes bundled with Linux which compiles C programs and generates executable for us to run. Code Blocks can also be used with Linux. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above C is the mother of all computer programming languages, which is widely used within the world of coding. Learn C programming from basic to advance and start your journey into the insightful world of Computer Science. Learn C Basics, Operators, Variables and Data Types in C etc. Join C Programming (Basic to Advanced) – Self Paced Course and kickstart your C programming journey today!. RishabhPrabhu anshu8tu tanwarsinghvaibhav dishaagrawal1 C Basics C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Functions that cannot be overloaded in C++ Switch Statement in C/C++ Substring in C++ Left Shift and Right Shift Operators in C/C++ std::string class in C++ Different Methods to Reverse a String in C++ Multidimensional Arrays in C / C++ Structures in C Function Pointer in C Functions in C/C++
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2022" }, { "code": null, "e": 784, "s": 52, "text": "C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of the C language include low-level memory access, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like an operating system or compiler development. Many later languages have borrowed syntax/features directly or indirectly from the C language. Like syntax of Java, PHP, JavaScript, and many other languages are mainly based on the C language. C++ is nearly a superset of C language (Few programs may compile in C, but not in C++). Beginning with C programming: " }, { "code": null, "e": 1099, "s": 784, "text": "Structure of a C program After the above discussion, we can formally assess the structure of a C program. By structure, it is meant that any program can be written in this structure only. Writing a C program in any other structure will hence lead to a Compilation Error.The structure of a C program is as follows: " }, { "code": null, "e": 1414, "s": 1099, "text": "Structure of a C program After the above discussion, we can formally assess the structure of a C program. By structure, it is meant that any program can be written in this structure only. Writing a C program in any other structure will hence lead to a Compilation Error.The structure of a C program is as follows: " }, { "code": null, "e": 2239, "s": 1414, "text": "The components of the above structure are: Header Files Inclusion: The first and foremost component is the inclusion of the Header files in a C program. A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files.Some of C Header files: stddef.h – Defines several useful types and macros.stdint.h – Defines exact width integer types.stdio.h – Defines core input and output functionsstdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocationstring.h – Defines string handling functionsmath.h – Defines common mathematical functionsMain Method Declaration: The next part of a C program is to declare the main() function. The syntax to declare the main function is:Syntax to Declare the main method: " }, { "code": null, "e": 3064, "s": 2239, "text": "The components of the above structure are: Header Files Inclusion: The first and foremost component is the inclusion of the Header files in a C program. A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files.Some of C Header files: stddef.h – Defines several useful types and macros.stdint.h – Defines exact width integer types.stdio.h – Defines core input and output functionsstdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocationstring.h – Defines string handling functionsmath.h – Defines common mathematical functionsMain Method Declaration: The next part of a C program is to declare the main() function. The syntax to declare the main function is:Syntax to Declare the main method: " }, { "code": null, "e": 3846, "s": 3064, "text": "Header Files Inclusion: The first and foremost component is the inclusion of the Header files in a C program. A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files.Some of C Header files: stddef.h – Defines several useful types and macros.stdint.h – Defines exact width integer types.stdio.h – Defines core input and output functionsstdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocationstring.h – Defines string handling functionsmath.h – Defines common mathematical functionsMain Method Declaration: The next part of a C program is to declare the main() function. The syntax to declare the main function is:Syntax to Declare the main method: " }, { "code": null, "e": 4460, "s": 3846, "text": "Header Files Inclusion: The first and foremost component is the inclusion of the Header files in a C program. A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files.Some of C Header files: stddef.h – Defines several useful types and macros.stdint.h – Defines exact width integer types.stdio.h – Defines core input and output functionsstdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocationstring.h – Defines string handling functionsmath.h – Defines common mathematical functions" }, { "code": null, "e": 4512, "s": 4460, "text": "stddef.h – Defines several useful types and macros." }, { "code": null, "e": 4558, "s": 4512, "text": "stdint.h – Defines exact width integer types." }, { "code": null, "e": 4608, "s": 4558, "text": "stdio.h – Defines core input and output functions" }, { "code": null, "e": 4708, "s": 4608, "text": "stdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocation" }, { "code": null, "e": 4753, "s": 4708, "text": "string.h – Defines string handling functions" }, { "code": null, "e": 4800, "s": 4753, "text": "math.h – Defines common mathematical functions" }, { "code": null, "e": 4969, "s": 4800, "text": "Main Method Declaration: The next part of a C program is to declare the main() function. The syntax to declare the main function is:Syntax to Declare the main method: " }, { "code": null, "e": 4983, "s": 4969, "text": "int main()\n{}" }, { "code": null, "e": 5315, "s": 4983, "text": " Variable Declaration: The next part of any C program is the variable declaration. It refers to the variables that are to be used in the function. Please note that in the C program, no variable can be used without being declared. Also in a C program, the variables are to be declared before any operation in the function.Example: " }, { "code": null, "e": 5648, "s": 5317, "text": "Variable Declaration: The next part of any C program is the variable declaration. It refers to the variables that are to be used in the function. Please note that in the C program, no variable can be used without being declared. Also in a C program, the variables are to be declared before any operation in the function.Example: " }, { "code": null, "e": 5676, "s": 5648, "text": "int main()\n{\n int a;\n.\n." }, { "code": null, "e": 5870, "s": 5676, "text": " Body: The body of a function in the C program, refers to the operations that are performed in the functions. It can be anything like manipulations, searching, sorting, printing, etc.Example: " }, { "code": null, "e": 6065, "s": 5872, "text": "Body: The body of a function in the C program, refers to the operations that are performed in the functions. It can be anything like manipulations, searching, sorting, printing, etc.Example: " }, { "code": null, "e": 6115, "s": 6065, "text": "int main()\n{\n int a;\n\n printf(\"%d\", a);\n.\n." }, { "code": null, "e": 6564, "s": 6115, "text": " Return Statement: The last part of any C program is the return statement. The return statement refers to the returning of the values from a function. This return statement and return value depend upon the return type of the function. For example, if the return type is void, then there will be no return statement. In any other case, there will be a return statement and the return value will be of the type of the specified return type.Example: " }, { "code": null, "e": 7014, "s": 6566, "text": "Return Statement: The last part of any C program is the return statement. The return statement refers to the returning of the values from a function. This return statement and return value depend upon the return type of the function. For example, if the return type is void, then there will be no return statement. In any other case, there will be a return statement and the return value will be of the type of the specified return type.Example: " }, { "code": null, "e": 7077, "s": 7014, "text": "int main()\n{\n int a;\n\n printf(\"%d\", a);\n\n return 0;\n}" }, { "code": null, "e": 7134, "s": 7077, "text": " Writing first program: Following is first program in C " }, { "code": null, "e": 7192, "s": 7136, "text": "Writing first program: Following is first program in C " }, { "code": null, "e": 7194, "s": 7192, "text": "C" }, { "code": "#include <stdio.h>int main(void){ printf(\"GeeksQuiz\"); return 0;}", "e": 7266, "s": 7194, "text": null }, { "code": null, "e": 9883, "s": 7266, "text": "Let us analyze the program line by line. Line 1: [ #include <stdio.h> ] In a C program, all lines that start with # are processed by a preprocessor which is a program invoked by the compiler. In a very basic term, the preprocessor takes a C program and produces another C program. The produced program has no lines starting with #, all such lines are processed by the preprocessor. In the above example, the preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called header files in C. These header files generally contain declarations of functions. We need stdio.h for the function printf() used in the program. Line 2 [ int main(void) ] There must be a starting point from where execution of compiled C program begins. In C, the execution typically begins with the first line of main(). The void written in brackets indicates that the main doesn’t take any parameter (See this for more details). main() can be written to take parameters also. We will be covering that in future posts. The int was written before main indicates return type of main(). The value returned by main indicates the status of program termination. See this post for more details on the return type.Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define scope and are mainly used in functions and control statements like if, else, loops. All functions must start and end with curly brackets. Line 4 [ printf(“GeeksQuiz”); ] printf() is a standard library function to print something on standard output. The semicolon at the end of printf indicates line termination. In C, a semicolon is always used to indicate end of a statement. Line 5 [ return 0; ] The return statement returns the value from main(). The returned value may be used by an operating system to know the termination status of your program. The value 0 typically means successful termination. How to execute the above program: In order to execute the above program, we need to first compile it using a compiler and then we can run the generated executable. There are online IDEs available for free like https://ide.geeksforgeeks.org/, http://ideone.com/, or http://codepad.org/ that can be used to start development in C without installing a compiler.Windows: There are many free IDEs available for developing programs in C like Code Blocks and Dev-CPP. IDEs provide us with environment to develop code, compile it and finally execute it. We strongly recommend Code Blocks.Linux: gcc compiler comes bundled with Linux which compiles C programs and generates executable for us to run. Code Blocks can also be used with Linux. " }, { "code": null, "e": 11767, "s": 9883, "text": "Let us analyze the program line by line. Line 1: [ #include <stdio.h> ] In a C program, all lines that start with # are processed by a preprocessor which is a program invoked by the compiler. In a very basic term, the preprocessor takes a C program and produces another C program. The produced program has no lines starting with #, all such lines are processed by the preprocessor. In the above example, the preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called header files in C. These header files generally contain declarations of functions. We need stdio.h for the function printf() used in the program. Line 2 [ int main(void) ] There must be a starting point from where execution of compiled C program begins. In C, the execution typically begins with the first line of main(). The void written in brackets indicates that the main doesn’t take any parameter (See this for more details). main() can be written to take parameters also. We will be covering that in future posts. The int was written before main indicates return type of main(). The value returned by main indicates the status of program termination. See this post for more details on the return type.Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define scope and are mainly used in functions and control statements like if, else, loops. All functions must start and end with curly brackets. Line 4 [ printf(“GeeksQuiz”); ] printf() is a standard library function to print something on standard output. The semicolon at the end of printf indicates line termination. In C, a semicolon is always used to indicate end of a statement. Line 5 [ return 0; ] The return statement returns the value from main(). The returned value may be used by an operating system to know the termination status of your program. The value 0 typically means successful termination. " }, { "code": null, "e": 12501, "s": 11767, "text": "How to execute the above program: In order to execute the above program, we need to first compile it using a compiler and then we can run the generated executable. There are online IDEs available for free like https://ide.geeksforgeeks.org/, http://ideone.com/, or http://codepad.org/ that can be used to start development in C without installing a compiler.Windows: There are many free IDEs available for developing programs in C like Code Blocks and Dev-CPP. IDEs provide us with environment to develop code, compile it and finally execute it. We strongly recommend Code Blocks.Linux: gcc compiler comes bundled with Linux which compiles C programs and generates executable for us to run. Code Blocks can also be used with Linux. " }, { "code": null, "e": 12626, "s": 12501, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 13012, "s": 12626, "text": "C is the mother of all computer programming languages, which is widely used within the world of coding. Learn C programming from basic to advance and start your journey into the insightful world of Computer Science. Learn C Basics, Operators, Variables and Data Types in C etc. Join C Programming (Basic to Advanced) – Self Paced Course and kickstart your C programming journey today!." }, { "code": null, "e": 13026, "s": 13012, "text": "RishabhPrabhu" }, { "code": null, "e": 13035, "s": 13026, "text": "anshu8tu" }, { "code": null, "e": 13054, "s": 13035, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 13068, "s": 13054, "text": "dishaagrawal1" }, { "code": null, "e": 13077, "s": 13068, "text": "C Basics" }, { "code": null, "e": 13088, "s": 13077, "text": "C Language" }, { "code": null, "e": 13186, "s": 13088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13229, "s": 13186, "text": "Functions that cannot be overloaded in C++" }, { "code": null, "e": 13255, "s": 13229, "text": "Switch Statement in C/C++" }, { "code": null, "e": 13272, "s": 13255, "text": "Substring in C++" }, { "code": null, "e": 13318, "s": 13272, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 13343, "s": 13318, "text": "std::string class in C++" }, { "code": null, "e": 13388, "s": 13343, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 13423, "s": 13388, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 13439, "s": 13423, "text": "Structures in C" }, { "code": null, "e": 13461, "s": 13439, "text": "Function Pointer in C" } ]
8 Reasons to Start Using Pydantic to Improve Data Parsing and Validation | by Ahmed Besbes | Towards Data Science
In one of my previous posts, I looked at dataclasses as a way of writing python classes that act as data containers. I found the dataclasses project amazing: it implements a lot of nifty methods under the hood to prevent you from writing boilerplate code, it provides a concise and pythonic syntax and it enforces modern programming practices. However, an important feature this module misses is data validation: a process by which you enforce schema constraints on your data, at runtime. This is where the Pydantic project comes into play. In this post, we’ll introduce data validation and why you should think about it when developing Python applications. Then, we’ll introduce the Pydantic libray as a way of solving this problem. We’ll go through 8 of its useful features and see how you can quickly embed them into your apps with a few lines of code. As always: less talk, more code. Let’s have a look 🔍 Data validation is a process that makes your data compliant with a set of rules, schemas or constraints that you defined for each attribute. This makes your code ingest and return data in the exact way it was expected to. Data validation prevents unexpected errors that occur due to problems such as malformed user inputs. In that sense, it also acts as a sanitization process. Let’s have an example: Imagine that you’re building a credit scoring API to evaluate the creditworthiness of an individual. To make this API work, you’ll have to send a post request on a given URL and provide some payload data. This data defines an individual: some of its fields are required and some others are optional. But this doesn't stop here. For some reason, this individual must have a French tax id as part of the required fields. This identifier follows a certain schema: let’s say, hypothetically, that it must have 13 digits and must end with 2 uppercase letters. The individual must provide a complete address as well: it must have a street name, a number and a zip code. The zip code must be composed of 5 digits. This can go on and on but you see the gist. 👉 Data validation makes sure the data you send to the API follows these constraints. You can still make your data follow these constraints by loading it and applying a series of conditions to each field. This could work but it can quickly result in a lot of code that becomes unmaintainable over time. What if we could encapsulate the data into a class, create a typed attribute for each of its fields and validate the field constraints at runtime when the data is loaded into the class? Well, Pydantic could be the exact answer to this problem. “Pydantic is a library that provides data validation and settings management using type annotations.” — Pydantic official documentation. I like to think of Pydantic as the little salt you sprinkle over your food (or in this particular case, your codebase) to make it taste better: Pydantic doesn’t care about the way you do things. It’s more of an abstraction layer that you add to your code without changing its logic. This layer, as you may expect, will essentially handle the data parsing and validation, among other cool features. Let’s now go through 8 of Pydantic features to understand why it’s so useful. You can define your data inside a class that inherits from theBaseModel class. Pydantic models are structures that ingest the data, parse it and make sure it conforms to the fields’ constraints defined in it. Let’s start with a simple example, where we define a Personclass that has two fields without any constraints: first_name and last_name . Just like dataclasses, we use type annotations. Unlike dataclasses, we don’t use the @dataclass decorator. We inherit from the BaseModel class instead By calling the typingmodule, we can add fields with more complex types. And you can even create types that are themselves a BaseModel class. If you want to see how Pydantic can be coupled with popular libraries such as FastAPI, have a look at my previous post on this topic. What happens when you define a Pydantic model and pass it some data that doesn’t conform to the defined schema? To understand how Pydantic would behave in this particular case, let’s look at this simple model: Let’s now feed it some inconsistent data and see what error messages are returned. Let’s omit the age field. This immediately throws a ValidationError that points out to the specific missing field. Instead of passing an integer to the age field, let’s pass it a string instead: for example"30 years"instead of 30 . Similarly, this throws a ValidationError and the message explicitly states that the field expects an integer type. 👉 It’s worth mentioning that Pydantic always tries to coerce the type you annotated. For example, if you try to pass “30” to the agefield, this would still work even though this field expects an integer value. Pydantic handles this situation off the shelf. 👉 You can make Pydantic error messages more explicit by importing the ValidationError class and calling it inside a try / except statement. Pydantic integrates well with modern IDEs such as VSCode and PyCharm. This helps you quickly debug your code and avoid silly mistakes. For example, when you instantiate an object from a Pydantic model, you immediately have autocompletion. You also have linting, assuming you use a static type checker like mypy. In the following example, if you try to apply the len function to the age attribute, VSCode will signal an error through mypy. Pydantic allows you to natively add some validation on each field by wrapping it inside the Field class. For example: you can add constraints on the length of the string fields by using the Field’s max_lengthand min_length arguments you can set boundaries on the numerical fields by using the Field’s ge and le arguments. (ge: greater or equal, le: lower or equal). Let’s have a look at the following example where we add constraints on the first_name (length between 2 and 20) and age (value lower than 150). Let’s see what errors are returned if we try to pass the following data to the Person class. data = {"first_name": "a", "last_name": "Besbes", "age": 200} You can perform more advanced fields’ customisation. Here are some arguments you can use inside the Field class regex : this adds a regular expression validator. This is useful when you want some string values to match a specific pattern multiple_of : this applies to int fields. It adds a “multiple of” validator max_items and min_items : this applies to lists and imposes a constraint on the number of items contained in them allow_mutation : this applies to any type of field. It defaults to False. When set to True, it makes the field immutable (or protected). To learn more about the large possibilities of Pydantic Field customisation, have a look at this link from the documentation. You don’t have to reinvent the wheel. Pydantic provides you with many helper functions and methods that you can use. Let’s see some examples: Starting from the following code, Let’s create a Personobject: data = {"first_name": "Ahmed", "last_name": "Besbes", "age": 30}person = Person(**data) This object has access to many useful methods. dict() : returns a dictionary from the object json() : returns a dictionary in JSON format copy() : returns a copy of the object schema() : print out the schema in JSON To learn more about helper functions, have a look at this link. str , int , float , Listare the usual types that we work with. In some situations, however, we may work with values that need specific validations such as paths, email addresses, IP addresses, to name a few. Fortunately, Pydatnic provides a list of built-in types for many of these use cases and got you covered: FilePath: for parsing file paths DirectoryPath: for parsing directory paths EmailStr: for parsing email addresses Color: for parsing HTML colors (see color type) HttpUrl: for parsing strict HTTP URLs IPvAnyAddress: for parsing IPv4 and IPv6 addresses Pydantic allows you to write your own custom validator. Let’s say that we want to add PhoneNumber field to the previous example. We want this field to respect two constraints: It’s a string of 10 digits It must start with 0 To perform a custom validation, you’ll have to import validator function from Pydantic and use it as a decorator before the function that tests the field value. Of course, you can do more sophisticated validations. Have a look at this link to learn more. Pydantic allows you to read environment variables from .env files and parse them directly inside BaseSettings class. To do this, you first need to install python-dotenv. (To learn more about python-dotenv and environment variables, you can refer to my previous post on the topic) Let’s say that you have some environment variables inside this .env file: LOGIN=AhmedAPI_KEY=SeCR€t!SEED=42 To make Pydatnic load these variables, we’ll first have to define a Settings class that inherits from the BaseSettings class. Inside the Settings class, we’ll define the variables that are listed in the .env file, while adding types and validators. And finally, we specify that the environment variables should be read from a .env file. If we run the code, the settings are printed to the terminal. If we replace 42 by forty-two inside the .env file, here’s what we’d get: Pretty cool, right? Pydantic is a fantastic tool that I really enjoyed learning and using. If you too are interested in learning more about this library, here’s a curated list of handpicked resources (blog posts and Youtube videos) I went through. Pydantic official documentation https://dev.to/tiangolo/the-future-of-fastapi-and-pydantic-is-bright-3pbm https://dev.to/amal/pydantic-for-fastapi-2385 https://dev.to/nazliander/using-pydantic-as-a-parser-and-data-validation-tool-51n3 https://dev.to/izabelakowal/some-ideas-on-how-to-implement-dtos-in-python-be3 (a French blog post): https://ichi.pro/fr/le-guide-du-debutant-sur-pydantic-204731199577737 A great Pydantic introduction from the ArjanCodes Youtube channel (a shout out to this guy who does amazing videos on programming) Pydantic: Modern Python Data Validation and Settings by Michael Kennedy — An amazing video tutorial If you’ve stuck till the end, I really thank you for your time and hope that you found this post useful to get started using Pydantic. If you don’t use Pydantic and come to know a better alternative, let me know about it in the comments 📥 That’ll be all for me today. Until next time for more programming tips and tutorials. 👋
[ { "code": null, "e": 288, "s": 171, "text": "In one of my previous posts, I looked at dataclasses as a way of writing python classes that act as data containers." }, { "code": null, "e": 515, "s": 288, "text": "I found the dataclasses project amazing: it implements a lot of nifty methods under the hood to prevent you from writing boilerplate code, it provides a concise and pythonic syntax and it enforces modern programming practices." }, { "code": null, "e": 660, "s": 515, "text": "However, an important feature this module misses is data validation: a process by which you enforce schema constraints on your data, at runtime." }, { "code": null, "e": 712, "s": 660, "text": "This is where the Pydantic project comes into play." }, { "code": null, "e": 905, "s": 712, "text": "In this post, we’ll introduce data validation and why you should think about it when developing Python applications. Then, we’ll introduce the Pydantic libray as a way of solving this problem." }, { "code": null, "e": 1027, "s": 905, "text": "We’ll go through 8 of its useful features and see how you can quickly embed them into your apps with a few lines of code." }, { "code": null, "e": 1080, "s": 1027, "text": "As always: less talk, more code. Let’s have a look 🔍" }, { "code": null, "e": 1302, "s": 1080, "text": "Data validation is a process that makes your data compliant with a set of rules, schemas or constraints that you defined for each attribute. This makes your code ingest and return data in the exact way it was expected to." }, { "code": null, "e": 1458, "s": 1302, "text": "Data validation prevents unexpected errors that occur due to problems such as malformed user inputs. In that sense, it also acts as a sanitization process." }, { "code": null, "e": 1582, "s": 1458, "text": "Let’s have an example: Imagine that you’re building a credit scoring API to evaluate the creditworthiness of an individual." }, { "code": null, "e": 1686, "s": 1582, "text": "To make this API work, you’ll have to send a post request on a given URL and provide some payload data." }, { "code": null, "e": 1809, "s": 1686, "text": "This data defines an individual: some of its fields are required and some others are optional. But this doesn't stop here." }, { "code": null, "e": 2036, "s": 1809, "text": "For some reason, this individual must have a French tax id as part of the required fields. This identifier follows a certain schema: let’s say, hypothetically, that it must have 13 digits and must end with 2 uppercase letters." }, { "code": null, "e": 2188, "s": 2036, "text": "The individual must provide a complete address as well: it must have a street name, a number and a zip code. The zip code must be composed of 5 digits." }, { "code": null, "e": 2232, "s": 2188, "text": "This can go on and on but you see the gist." }, { "code": null, "e": 2317, "s": 2232, "text": "👉 Data validation makes sure the data you send to the API follows these constraints." }, { "code": null, "e": 2534, "s": 2317, "text": "You can still make your data follow these constraints by loading it and applying a series of conditions to each field. This could work but it can quickly result in a lot of code that becomes unmaintainable over time." }, { "code": null, "e": 2720, "s": 2534, "text": "What if we could encapsulate the data into a class, create a typed attribute for each of its fields and validate the field constraints at runtime when the data is loaded into the class?" }, { "code": null, "e": 2778, "s": 2720, "text": "Well, Pydantic could be the exact answer to this problem." }, { "code": null, "e": 2915, "s": 2778, "text": "“Pydantic is a library that provides data validation and settings management using type annotations.” — Pydantic official documentation." }, { "code": null, "e": 3198, "s": 2915, "text": "I like to think of Pydantic as the little salt you sprinkle over your food (or in this particular case, your codebase) to make it taste better: Pydantic doesn’t care about the way you do things. It’s more of an abstraction layer that you add to your code without changing its logic." }, { "code": null, "e": 3313, "s": 3198, "text": "This layer, as you may expect, will essentially handle the data parsing and validation, among other cool features." }, { "code": null, "e": 3391, "s": 3313, "text": "Let’s now go through 8 of Pydantic features to understand why it’s so useful." }, { "code": null, "e": 3470, "s": 3391, "text": "You can define your data inside a class that inherits from theBaseModel class." }, { "code": null, "e": 3600, "s": 3470, "text": "Pydantic models are structures that ingest the data, parse it and make sure it conforms to the fields’ constraints defined in it." }, { "code": null, "e": 3737, "s": 3600, "text": "Let’s start with a simple example, where we define a Personclass that has two fields without any constraints: first_name and last_name ." }, { "code": null, "e": 3785, "s": 3737, "text": "Just like dataclasses, we use type annotations." }, { "code": null, "e": 3888, "s": 3785, "text": "Unlike dataclasses, we don’t use the @dataclass decorator. We inherit from the BaseModel class instead" }, { "code": null, "e": 3960, "s": 3888, "text": "By calling the typingmodule, we can add fields with more complex types." }, { "code": null, "e": 4029, "s": 3960, "text": "And you can even create types that are themselves a BaseModel class." }, { "code": null, "e": 4163, "s": 4029, "text": "If you want to see how Pydantic can be coupled with popular libraries such as FastAPI, have a look at my previous post on this topic." }, { "code": null, "e": 4275, "s": 4163, "text": "What happens when you define a Pydantic model and pass it some data that doesn’t conform to the defined schema?" }, { "code": null, "e": 4373, "s": 4275, "text": "To understand how Pydantic would behave in this particular case, let’s look at this simple model:" }, { "code": null, "e": 4456, "s": 4373, "text": "Let’s now feed it some inconsistent data and see what error messages are returned." }, { "code": null, "e": 4571, "s": 4456, "text": "Let’s omit the age field. This immediately throws a ValidationError that points out to the specific missing field." }, { "code": null, "e": 4688, "s": 4571, "text": "Instead of passing an integer to the age field, let’s pass it a string instead: for example\"30 years\"instead of 30 ." }, { "code": null, "e": 4803, "s": 4688, "text": "Similarly, this throws a ValidationError and the message explicitly states that the field expects an integer type." }, { "code": null, "e": 5060, "s": 4803, "text": "👉 It’s worth mentioning that Pydantic always tries to coerce the type you annotated. For example, if you try to pass “30” to the agefield, this would still work even though this field expects an integer value. Pydantic handles this situation off the shelf." }, { "code": null, "e": 5200, "s": 5060, "text": "👉 You can make Pydantic error messages more explicit by importing the ValidationError class and calling it inside a try / except statement." }, { "code": null, "e": 5335, "s": 5200, "text": "Pydantic integrates well with modern IDEs such as VSCode and PyCharm. This helps you quickly debug your code and avoid silly mistakes." }, { "code": null, "e": 5439, "s": 5335, "text": "For example, when you instantiate an object from a Pydantic model, you immediately have autocompletion." }, { "code": null, "e": 5512, "s": 5439, "text": "You also have linting, assuming you use a static type checker like mypy." }, { "code": null, "e": 5639, "s": 5512, "text": "In the following example, if you try to apply the len function to the age attribute, VSCode will signal an error through mypy." }, { "code": null, "e": 5744, "s": 5639, "text": "Pydantic allows you to natively add some validation on each field by wrapping it inside the Field class." }, { "code": null, "e": 5757, "s": 5744, "text": "For example:" }, { "code": null, "e": 5872, "s": 5757, "text": "you can add constraints on the length of the string fields by using the Field’s max_lengthand min_length arguments" }, { "code": null, "e": 6005, "s": 5872, "text": "you can set boundaries on the numerical fields by using the Field’s ge and le arguments. (ge: greater or equal, le: lower or equal)." }, { "code": null, "e": 6149, "s": 6005, "text": "Let’s have a look at the following example where we add constraints on the first_name (length between 2 and 20) and age (value lower than 150)." }, { "code": null, "e": 6242, "s": 6149, "text": "Let’s see what errors are returned if we try to pass the following data to the Person class." }, { "code": null, "e": 6304, "s": 6242, "text": "data = {\"first_name\": \"a\", \"last_name\": \"Besbes\", \"age\": 200}" }, { "code": null, "e": 6416, "s": 6304, "text": "You can perform more advanced fields’ customisation. Here are some arguments you can use inside the Field class" }, { "code": null, "e": 6542, "s": 6416, "text": "regex : this adds a regular expression validator. This is useful when you want some string values to match a specific pattern" }, { "code": null, "e": 6618, "s": 6542, "text": "multiple_of : this applies to int fields. It adds a “multiple of” validator" }, { "code": null, "e": 6732, "s": 6618, "text": "max_items and min_items : this applies to lists and imposes a constraint on the number of items contained in them" }, { "code": null, "e": 6869, "s": 6732, "text": "allow_mutation : this applies to any type of field. It defaults to False. When set to True, it makes the field immutable (or protected)." }, { "code": null, "e": 6995, "s": 6869, "text": "To learn more about the large possibilities of Pydantic Field customisation, have a look at this link from the documentation." }, { "code": null, "e": 7137, "s": 6995, "text": "You don’t have to reinvent the wheel. Pydantic provides you with many helper functions and methods that you can use. Let’s see some examples:" }, { "code": null, "e": 7171, "s": 7137, "text": "Starting from the following code," }, { "code": null, "e": 7200, "s": 7171, "text": "Let’s create a Personobject:" }, { "code": null, "e": 7288, "s": 7200, "text": "data = {\"first_name\": \"Ahmed\", \"last_name\": \"Besbes\", \"age\": 30}person = Person(**data)" }, { "code": null, "e": 7335, "s": 7288, "text": "This object has access to many useful methods." }, { "code": null, "e": 7381, "s": 7335, "text": "dict() : returns a dictionary from the object" }, { "code": null, "e": 7426, "s": 7381, "text": "json() : returns a dictionary in JSON format" }, { "code": null, "e": 7464, "s": 7426, "text": "copy() : returns a copy of the object" }, { "code": null, "e": 7504, "s": 7464, "text": "schema() : print out the schema in JSON" }, { "code": null, "e": 7568, "s": 7504, "text": "To learn more about helper functions, have a look at this link." }, { "code": null, "e": 7631, "s": 7568, "text": "str , int , float , Listare the usual types that we work with." }, { "code": null, "e": 7776, "s": 7631, "text": "In some situations, however, we may work with values that need specific validations such as paths, email addresses, IP addresses, to name a few." }, { "code": null, "e": 7881, "s": 7776, "text": "Fortunately, Pydatnic provides a list of built-in types for many of these use cases and got you covered:" }, { "code": null, "e": 7914, "s": 7881, "text": "FilePath: for parsing file paths" }, { "code": null, "e": 7957, "s": 7914, "text": "DirectoryPath: for parsing directory paths" }, { "code": null, "e": 7995, "s": 7957, "text": "EmailStr: for parsing email addresses" }, { "code": null, "e": 8043, "s": 7995, "text": "Color: for parsing HTML colors (see color type)" }, { "code": null, "e": 8081, "s": 8043, "text": "HttpUrl: for parsing strict HTTP URLs" }, { "code": null, "e": 8132, "s": 8081, "text": "IPvAnyAddress: for parsing IPv4 and IPv6 addresses" }, { "code": null, "e": 8188, "s": 8132, "text": "Pydantic allows you to write your own custom validator." }, { "code": null, "e": 8261, "s": 8188, "text": "Let’s say that we want to add PhoneNumber field to the previous example." }, { "code": null, "e": 8308, "s": 8261, "text": "We want this field to respect two constraints:" }, { "code": null, "e": 8335, "s": 8308, "text": "It’s a string of 10 digits" }, { "code": null, "e": 8356, "s": 8335, "text": "It must start with 0" }, { "code": null, "e": 8517, "s": 8356, "text": "To perform a custom validation, you’ll have to import validator function from Pydantic and use it as a decorator before the function that tests the field value." }, { "code": null, "e": 8611, "s": 8517, "text": "Of course, you can do more sophisticated validations. Have a look at this link to learn more." }, { "code": null, "e": 8728, "s": 8611, "text": "Pydantic allows you to read environment variables from .env files and parse them directly inside BaseSettings class." }, { "code": null, "e": 8781, "s": 8728, "text": "To do this, you first need to install python-dotenv." }, { "code": null, "e": 8891, "s": 8781, "text": "(To learn more about python-dotenv and environment variables, you can refer to my previous post on the topic)" }, { "code": null, "e": 8965, "s": 8891, "text": "Let’s say that you have some environment variables inside this .env file:" }, { "code": null, "e": 8999, "s": 8965, "text": "LOGIN=AhmedAPI_KEY=SeCR€t!SEED=42" }, { "code": null, "e": 9125, "s": 8999, "text": "To make Pydatnic load these variables, we’ll first have to define a Settings class that inherits from the BaseSettings class." }, { "code": null, "e": 9248, "s": 9125, "text": "Inside the Settings class, we’ll define the variables that are listed in the .env file, while adding types and validators." }, { "code": null, "e": 9336, "s": 9248, "text": "And finally, we specify that the environment variables should be read from a .env file." }, { "code": null, "e": 9398, "s": 9336, "text": "If we run the code, the settings are printed to the terminal." }, { "code": null, "e": 9472, "s": 9398, "text": "If we replace 42 by forty-two inside the .env file, here’s what we’d get:" }, { "code": null, "e": 9492, "s": 9472, "text": "Pretty cool, right?" }, { "code": null, "e": 9563, "s": 9492, "text": "Pydantic is a fantastic tool that I really enjoyed learning and using." }, { "code": null, "e": 9720, "s": 9563, "text": "If you too are interested in learning more about this library, here’s a curated list of handpicked resources (blog posts and Youtube videos) I went through." }, { "code": null, "e": 9752, "s": 9720, "text": "Pydantic official documentation" }, { "code": null, "e": 9826, "s": 9752, "text": "https://dev.to/tiangolo/the-future-of-fastapi-and-pydantic-is-bright-3pbm" }, { "code": null, "e": 9872, "s": 9826, "text": "https://dev.to/amal/pydantic-for-fastapi-2385" }, { "code": null, "e": 9955, "s": 9872, "text": "https://dev.to/nazliander/using-pydantic-as-a-parser-and-data-validation-tool-51n3" }, { "code": null, "e": 10033, "s": 9955, "text": "https://dev.to/izabelakowal/some-ideas-on-how-to-implement-dtos-in-python-be3" }, { "code": null, "e": 10125, "s": 10033, "text": "(a French blog post): https://ichi.pro/fr/le-guide-du-debutant-sur-pydantic-204731199577737" }, { "code": null, "e": 10256, "s": 10125, "text": "A great Pydantic introduction from the ArjanCodes Youtube channel (a shout out to this guy who does amazing videos on programming)" }, { "code": null, "e": 10356, "s": 10256, "text": "Pydantic: Modern Python Data Validation and Settings by Michael Kennedy — An amazing video tutorial" }, { "code": null, "e": 10491, "s": 10356, "text": "If you’ve stuck till the end, I really thank you for your time and hope that you found this post useful to get started using Pydantic." }, { "code": null, "e": 10595, "s": 10491, "text": "If you don’t use Pydantic and come to know a better alternative, let me know about it in the comments 📥" } ]
How to configure samba on centos
This article will guide to configure samba server in CentOS 6.x with anonymous & secured samba folders. Samba is an Open Source/Free Software suite that provides seamless access to the file services to SMB/CIFS clients. Unlike other tools samba SMB/CIFS implementations will allow to share folders between Linux servers and Windows clients. Install the samba package using this command # yum -y install samba # mkdir /samba Give folder permission to the samba server # chmod -R 0755 /samba/anonymous/ You need to modify the smb.conf file in /etc/samba/smb.conf For security reasons, I am taking the backup of the original file in /etc/samba/smb.conf # cp /etc/samba.smb.conf /etc/samba.smb.conf.old For removing the confusion, will delete the configuration file and will create a file with the below commands. # rm -rf /etc/samba.smb.conf # vi /etc/samba/smb.conf #======================= Global Settings ===================================== [global] workgroup = WORKGROUP security = share map to guest = bad user #============================ Share Definitions ============================== [MyShare] path = /samba/anonymous/ browsable =yes writable = yes guest ok = yes read only = yes # service smb restart Now you can access the share from windows machine using \\IP-ADDRES from Start -> Run. (Ex: \\192.168.2.225) As we share the files without any security there is a chance of loosing your valuable data to secure please do the settings. # groupadd smbgrp # useradd user1 -G sambagrp # smbpasswd -a user1 Output: New SMB password:<--yoursambapassword Retype new SMB password:<--yoursambapassword Now create the folder with the name secured in the /samba folder and give permissions like this − # mkdir -p /samba/secure # cd /samba # chmod -R 0777 /samba/secure/ Again edit the configuration file − # vi /etc/samba/smb.conf [...] [secured] path = /samba/secure valid users = @smbgrp guest ok = no writable = yes browsable = yes # service smb restart Further, check the settings as follows # testparm Output: Load smb config files from /etc/samba/smb.conf rlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384) Processing section "[Anonymous]" Processing section "[secured]" Loaded services file OK. Server role: ROLE_STANDALONE Press enter to see a dump of your service definitions <--ENTER Edit the Configuration files with both anonymous and secure to see the difference in shares. # vi /etc/samba/smb.conf Configuration file settings: #======================= Global Settings ===================================== [global] netbios name = CENTOS server string = Samba Server %v map to guest = Bad User dns proxy = No idmap config * : ackbend = tdb #============================ Share Definitions ============================== [Anonymous] path = /samba read only = No guest ok = Yes [secured] path = /samba/secure valid users = @smbgrp guest ok = no writable = yes browsable = yes Now you can access the share from windows machine \\IP-ADDRES from Start -> Run. (Ex: \\192.168.2.225) This will ask for the user-name and password provide the user-name and password (Ex: user1 and password for the user1) and now you can access the secured folder using credentials. Conclusion − After the configuration and successful setup, now you are able to access the folder Windows share (or) NTFS share on a Linux server to provide or share the data in between Windows and Linux machines, with or without anonymous access and you are able to provide the individual access or groups access to the folders with permissions.
[ { "code": null, "e": 1403, "s": 1062, "text": "This article will guide to configure samba server in CentOS 6.x with anonymous & secured samba folders. Samba is an Open Source/Free Software suite that provides seamless access to the file services to SMB/CIFS clients. Unlike other tools samba SMB/CIFS implementations will allow to share folders between Linux servers and Windows clients." }, { "code": null, "e": 1448, "s": 1403, "text": "Install the samba package using this command" }, { "code": null, "e": 1486, "s": 1448, "text": "# yum -y install samba\n# mkdir /samba" }, { "code": null, "e": 1529, "s": 1486, "text": "Give folder permission to the samba server" }, { "code": null, "e": 1563, "s": 1529, "text": "# chmod -R 0755 /samba/anonymous/" }, { "code": null, "e": 1623, "s": 1563, "text": "You need to modify the smb.conf file in /etc/samba/smb.conf" }, { "code": null, "e": 1712, "s": 1623, "text": "For security reasons, I am taking the backup of the original file in /etc/samba/smb.conf" }, { "code": null, "e": 1761, "s": 1712, "text": "# cp /etc/samba.smb.conf /etc/samba.smb.conf.old" }, { "code": null, "e": 1872, "s": 1761, "text": "For removing the confusion, will delete the configuration file and will create a file with the below commands." }, { "code": null, "e": 1926, "s": 1872, "text": "# rm -rf /etc/samba.smb.conf\n# vi /etc/samba/smb.conf" }, { "code": null, "e": 2252, "s": 1926, "text": "#======================= Global Settings =====================================\n[global]\nworkgroup = WORKGROUP\nsecurity = share\nmap to guest = bad user\n#============================ Share Definitions ==============================\n[MyShare]\npath = /samba/anonymous/\nbrowsable =yes\nwritable = yes\nguest ok = yes\nread only = yes" }, { "code": null, "e": 2274, "s": 2252, "text": "# service smb restart" }, { "code": null, "e": 2383, "s": 2274, "text": "Now you can access the share from windows machine using \\\\IP-ADDRES from Start -> Run. (Ex: \\\\192.168.2.225)" }, { "code": null, "e": 2508, "s": 2383, "text": "As we share the files without any security there is a chance of loosing your valuable data to secure please do the settings." }, { "code": null, "e": 2575, "s": 2508, "text": "# groupadd smbgrp\n# useradd user1 -G sambagrp\n# smbpasswd -a user1" }, { "code": null, "e": 2666, "s": 2575, "text": "Output:\nNew SMB password:<--yoursambapassword\nRetype new SMB password:<--yoursambapassword" }, { "code": null, "e": 2764, "s": 2666, "text": "Now create the folder with the name secured in the /samba folder and give permissions like this −" }, { "code": null, "e": 2832, "s": 2764, "text": "# mkdir -p /samba/secure\n# cd /samba\n# chmod -R 0777 /samba/secure/" }, { "code": null, "e": 2868, "s": 2832, "text": "Again edit the configuration file −" }, { "code": null, "e": 2997, "s": 2868, "text": "# vi /etc/samba/smb.conf\n[...]\n[secured]\npath = /samba/secure\nvalid users = @smbgrp\nguest ok = no\nwritable = yes\nbrowsable = yes" }, { "code": null, "e": 3019, "s": 2997, "text": "# service smb restart" }, { "code": null, "e": 3058, "s": 3019, "text": "Further, check the settings as follows" }, { "code": null, "e": 3379, "s": 3058, "text": "# testparm\nOutput:\nLoad smb config files from /etc/samba/smb.conf\nrlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)\nProcessing section \"[Anonymous]\"\nProcessing section \"[secured]\"\nLoaded services file OK.\nServer role: ROLE_STANDALONE\nPress enter to see a dump of your service definitions <--ENTER" }, { "code": null, "e": 3472, "s": 3379, "text": "Edit the Configuration files with both anonymous and secure to see the difference in shares." }, { "code": null, "e": 3526, "s": 3472, "text": "# vi /etc/samba/smb.conf\nConfiguration file settings:" }, { "code": null, "e": 3971, "s": 3526, "text": "#======================= Global Settings =====================================\n[global]\nnetbios name = CENTOS\nserver string = Samba Server %v\nmap to guest = Bad User\ndns proxy = No\nidmap config * : ackbend = tdb\n#============================ Share Definitions ==============================\n[Anonymous]\npath = /samba\nread only = No\nguest ok = Yes\n[secured]\npath = /samba/secure\nvalid users = @smbgrp\nguest ok = no\nwritable = yes\nbrowsable = yes" }, { "code": null, "e": 4074, "s": 3971, "text": "Now you can access the share from windows machine \\\\IP-ADDRES from Start -> Run. (Ex: \\\\192.168.2.225)" }, { "code": null, "e": 4254, "s": 4074, "text": "This will ask for the user-name and password provide the user-name and password (Ex: user1 and password for the user1) and now you can access the secured folder using credentials." }, { "code": null, "e": 4600, "s": 4254, "text": "Conclusion − After the configuration and successful setup, now you are able to access the folder Windows share (or) NTFS share on a Linux server to provide or share the data in between Windows and Linux machines, with or without anonymous access and you are able to provide the individual access or groups access to the folders with permissions." } ]
How to convert unix timestamp string to readable date in Python?
You can use the fromtimestamp function from the datetime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the datetime object corresponding to the timestamp. import datetime timestamp = datetime.datetime.fromtimestamp(1500000000) print(timestamp.strftime('%Y-%m-%d %H:%M:%S')) This will give the output − 2017-07-14 08:10:00
[ { "code": null, "e": 1272, "s": 1062, "text": "You can use the fromtimestamp function from the datetime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the datetime object corresponding to the timestamp. " }, { "code": null, "e": 1391, "s": 1272, "text": "import datetime\ntimestamp = datetime.datetime.fromtimestamp(1500000000)\nprint(timestamp.strftime('%Y-%m-%d %H:%M:%S'))" }, { "code": null, "e": 1419, "s": 1391, "text": "This will give the output −" }, { "code": null, "e": 1439, "s": 1419, "text": "2017-07-14 08:10:00" } ]
Minimum Increment to Make Array Unique in C++
Suppose we have an array of integers A, here a move consists of choosing any A[i], and incrementing it by 1. We have to find the least number of moves to make every value in A unique. So if the input is like [3,2,1,2,1,7], then the output will be 6, as after 6 moves, the array could be [3,4,1,2,5,7], it can be shown with 5 or less moves that it is impossible for the array to have all distinct values. To solve this, we will follow these steps − ret:= 0 ret:= 0 sort array A sort array A create one set called visited to keep track which value is considered before create one set called visited to keep track which value is considered before for i in range 1 to size of array A – 1if A[i] < A[i – 1], then ret := ret + (1 + A[i – 1 ]) – A[i], and A[i] := A[i – 1] + 1 for i in range 1 to size of array A – 1 if A[i] < A[i – 1], then ret := ret + (1 + A[i – 1 ]) – A[i], and A[i] := A[i – 1] + 1 if A[i] < A[i – 1], then ret := ret + (1 + A[i – 1 ]) – A[i], and A[i] := A[i – 1] + 1 return ret. return ret. Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int minIncrementForUnique(vector<int>& A) { int ret = 0; sort(A.begin(), A.end()); set <int> visited; for(int i = 1; i < A.size(); i++){ if(A[i] <= A[i - 1]){ ret+= (A[i - 1] + 1) - A[i]; A[i] = A[i - 1] + 1; } } return ret; } }; main(){ vector<int> v1 = {3,2,1,2,1,7}; Solution ob; cout << (ob.minIncrementForUnique(v1)); } [3,2,1,2,1,7] 6
[ { "code": null, "e": 1466, "s": 1062, "text": "Suppose we have an array of integers A, here a move consists of choosing any A[i], and incrementing it by 1. We have to find the least number of moves to make every value in A unique. So if the input is like [3,2,1,2,1,7], then the output will be 6, as after 6 moves, the array could be [3,4,1,2,5,7], it can be shown with 5 or less moves that it is impossible for the array to have all distinct values." }, { "code": null, "e": 1510, "s": 1466, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1518, "s": 1510, "text": "ret:= 0" }, { "code": null, "e": 1526, "s": 1518, "text": "ret:= 0" }, { "code": null, "e": 1539, "s": 1526, "text": "sort array A" }, { "code": null, "e": 1552, "s": 1539, "text": "sort array A" }, { "code": null, "e": 1629, "s": 1552, "text": "create one set called visited to keep track which value is considered before" }, { "code": null, "e": 1706, "s": 1629, "text": "create one set called visited to keep track which value is considered before" }, { "code": null, "e": 1832, "s": 1706, "text": "for i in range 1 to size of array A – 1if A[i] < A[i – 1], then ret := ret + (1 + A[i – 1 ]) – A[i], and A[i] := A[i – 1] + 1" }, { "code": null, "e": 1872, "s": 1832, "text": "for i in range 1 to size of array A – 1" }, { "code": null, "e": 1959, "s": 1872, "text": "if A[i] < A[i – 1], then ret := ret + (1 + A[i – 1 ]) – A[i], and A[i] := A[i – 1] + 1" }, { "code": null, "e": 2046, "s": 1959, "text": "if A[i] < A[i – 1], then ret := ret + (1 + A[i – 1 ]) – A[i], and A[i] := A[i – 1] + 1" }, { "code": null, "e": 2058, "s": 2046, "text": "return ret." }, { "code": null, "e": 2070, "s": 2058, "text": "return ret." }, { "code": null, "e": 2140, "s": 2070, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2151, "s": 2140, "text": " Live Demo" }, { "code": null, "e": 2643, "s": 2151, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int minIncrementForUnique(vector<int>& A) {\n int ret = 0;\n sort(A.begin(), A.end());\n set <int> visited;\n for(int i = 1; i < A.size(); i++){\n if(A[i] <= A[i - 1]){\n ret+= (A[i - 1] + 1) - A[i];\n A[i] = A[i - 1] + 1;\n }\n }\n return ret;\n }\n};\nmain(){\n vector<int> v1 = {3,2,1,2,1,7};\n Solution ob;\n cout << (ob.minIncrementForUnique(v1));\n}" }, { "code": null, "e": 2657, "s": 2643, "text": "[3,2,1,2,1,7]" }, { "code": null, "e": 2659, "s": 2657, "text": "6" } ]
Java SAX Parser - Query XML Document
Here is the input text file that we need to Query for rollno: 393 <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class UserHandler extends DefaultHandler { boolean bFirstName = false; boolean bLastName = false; boolean bNickName = false; boolean bMarks = false; String rollNo = null; @Override public void startElement( String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("student")) { rollNo = attributes.getValue("rollno"); } if(("393").equals(rollNo) && qName.equalsIgnoreCase("student")) { System.out.println("Start Element :" + qName); } if (qName.equalsIgnoreCase("firstname")) { bFirstName = true; } else if (qName.equalsIgnoreCase("lastname")) { bLastName = true; } else if (qName.equalsIgnoreCase("nickname")) { bNickName = true; } else if (qName.equalsIgnoreCase("marks")) { bMarks = true; } } @Override public void endElement( String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("student")) { if(("393").equals(rollNo) && qName.equalsIgnoreCase("student")) System.out.println("End Element :" + qName); } } @Override public void characters(char ch[], int start, int length) throws SAXException { if (bFirstName && ("393").equals(rollNo)) { //age element, set Employee age System.out.println("First Name: " + new String(ch, start, length)); bFirstName = false; } else if (bLastName && ("393").equals(rollNo)) { System.out.println("Last Name: " + new String(ch, start, length)); bLastName = false; } else if (bNickName && ("393").equals(rollNo)) { System.out.println("Nick Name: " + new String(ch, start, length)); bNickName = false; } else if (bMarks && ("393").equals(rollNo)) { System.out.println("Marks: " + new String(ch, start, length)); bMarks = false; } } } package com.tutorialspoint.xml; import java.io.File; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SAXQueryDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); UserHandler userhandler = new UserHandler(); saxParser.parse(inputFile, userhandler); } catch (Exception e) { e.printStackTrace(); } } } class UserHandler extends DefaultHandler { boolean bFirstName = false; boolean bLastName = false; boolean bNickName = false; boolean bMarks = false; String rollNo = null; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("student")) { rollNo = attributes.getValue("rollno"); } if(("393").equals(rollNo) && qName.equalsIgnoreCase("student")) { System.out.println("Start Element :" + qName); } if (qName.equalsIgnoreCase("firstname")) { bFirstName = true; } else if (qName.equalsIgnoreCase("lastname")) { bLastName = true; } else if (qName.equalsIgnoreCase("nickname")) { bNickName = true; } else if (qName.equalsIgnoreCase("marks")) { bMarks = true; } } @Override public void endElement( String uri, String localName, String qName) throws SAXException { if (qName.equalsIgnoreCase("student")) { if(("393").equals(rollNo) && qName.equalsIgnoreCase("student")) System.out.println("End Element :" + qName); } } @Override public void characters( char ch[], int start, int length) throws SAXException { if (bFirstName && ("393").equals(rollNo)) { //age element, set Employee age System.out.println("First Name: " + new String(ch, start, length)); bFirstName = false; } else if (bLastName && ("393").equals(rollNo)) { System.out.println("Last Name: " + new String(ch, start, length)); bLastName = false; } else if (bNickName && ("393").equals(rollNo)) { System.out.println("Nick Name: " + new String(ch, start, length)); bNickName = false; } else if (bMarks && ("393").equals(rollNo)) { System.out.println("Marks: " + new String(ch, start, length)); bMarks = false; } } } This would produce the following result − Start Element :student First Name: dinkar Last Name: kad Nick Name: dinkar Marks: 85 End Element :student 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2389, "s": 2323, "text": "Here is the input text file that we need to Query for rollno: 393" }, { "code": null, "e": 2940, "s": 2389, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 5106, "s": 2940, "text": "package com.tutorialspoint.xml;\n\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.helpers.DefaultHandler;\n \npublic class UserHandler extends DefaultHandler {\n\n boolean bFirstName = false;\n boolean bLastName = false;\n boolean bNickName = false;\n boolean bMarks = false;\n String rollNo = null;\n\n @Override\n public void startElement(\n String uri, String localName, String qName, Attributes attributes)\n throws SAXException {\n\n if (qName.equalsIgnoreCase(\"student\")) {\n rollNo = attributes.getValue(\"rollno\");\n }\n if((\"393\").equals(rollNo) && \n qName.equalsIgnoreCase(\"student\")) {\n System.out.println(\"Start Element :\" + qName); \n } \n if (qName.equalsIgnoreCase(\"firstname\")) {\n bFirstName = true;\n } else if (qName.equalsIgnoreCase(\"lastname\")) {\n bLastName = true;\n } else if (qName.equalsIgnoreCase(\"nickname\")) {\n bNickName = true;\n }\n else if (qName.equalsIgnoreCase(\"marks\")) {\n bMarks = true;\n }\n }\n\n @Override\n public void endElement(\n String uri, String localName, String qName) throws SAXException {\n \n if (qName.equalsIgnoreCase(\"student\")) {\n if((\"393\").equals(rollNo) && qName.equalsIgnoreCase(\"student\"))\n System.out.println(\"End Element :\" + qName);\n }\n }\n\n @Override\n public void characters(char ch[], int start, int length) throws SAXException {\n\n if (bFirstName && (\"393\").equals(rollNo)) {\n //age element, set Employee age\n System.out.println(\"First Name: \" + new String(ch, start, length));\n bFirstName = false;\n } else if (bLastName && (\"393\").equals(rollNo)) {\n System.out.println(\"Last Name: \" + new String(ch, start, length));\n bLastName = false;\n } else if (bNickName && (\"393\").equals(rollNo)) {\n System.out.println(\"Nick Name: \" + new String(ch, start, length));\n bNickName = false;\n } else if (bMarks && (\"393\").equals(rollNo)) {\n System.out.println(\"Marks: \" + new String(ch, start, length));\n bMarks = false;\n }\n }\n}" }, { "code": null, "e": 7826, "s": 5106, "text": "package com.tutorialspoint.xml;\n\nimport java.io.File;\nimport javax.xml.parsers.SAXParser;\nimport javax.xml.parsers.SAXParserFactory;\n\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.helpers.DefaultHandler;\n\npublic class SAXQueryDemo {\n\n public static void main(String[] args) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXParserFactory factory = SAXParserFactory.newInstance();\n SAXParser saxParser = factory.newSAXParser();\n UserHandler userhandler = new UserHandler();\n saxParser.parse(inputFile, userhandler); \n } catch (Exception e) {\n e.printStackTrace();\n }\n } \n}\n\nclass UserHandler extends DefaultHandler {\n\n boolean bFirstName = false;\n boolean bLastName = false;\n boolean bNickName = false;\n boolean bMarks = false;\n String rollNo = null;\n\n @Override\n public void startElement(String uri, \n String localName, String qName, Attributes attributes)\n throws SAXException {\n\n if (qName.equalsIgnoreCase(\"student\")) {\n rollNo = attributes.getValue(\"rollno\");\n }\n if((\"393\").equals(rollNo) && qName.equalsIgnoreCase(\"student\")) {\n System.out.println(\"Start Element :\" + qName); \n } \n if (qName.equalsIgnoreCase(\"firstname\")) {\n bFirstName = true;\n } else if (qName.equalsIgnoreCase(\"lastname\")) {\n bLastName = true;\n } else if (qName.equalsIgnoreCase(\"nickname\")) {\n bNickName = true;\n }\n else if (qName.equalsIgnoreCase(\"marks\")) {\n bMarks = true;\n }\n }\n\n @Override\n public void endElement(\n String uri, String localName, String qName) throws SAXException {\n \n if (qName.equalsIgnoreCase(\"student\")) {\n\n if((\"393\").equals(rollNo) \n && qName.equalsIgnoreCase(\"student\"))\n System.out.println(\"End Element :\" + qName);\n }\n }\n\n\n @Override\n public void characters(\n char ch[], int start, int length) throws SAXException {\n\n if (bFirstName && (\"393\").equals(rollNo)) {\n //age element, set Employee age\n System.out.println(\"First Name: \" + new String(ch, start, length));\n bFirstName = false;\n } else if (bLastName && (\"393\").equals(rollNo)) {\n System.out.println(\"Last Name: \" + new String(ch, start, length));\n bLastName = false;\n } else if (bNickName && (\"393\").equals(rollNo)) {\n System.out.println(\"Nick Name: \" + new String(ch, start, length));\n bNickName = false;\n } else if (bMarks && (\"393\").equals(rollNo)) {\n System.out.println(\"Marks: \" + new String(ch, start, length));\n bMarks = false;\n }\n }\n}" }, { "code": null, "e": 7868, "s": 7826, "text": "This would produce the following result −" }, { "code": null, "e": 7975, "s": 7868, "text": "Start Element :student\nFirst Name: dinkar\nLast Name: kad\nNick Name: dinkar\nMarks: 85\nEnd Element :student\n" }, { "code": null, "e": 8008, "s": 7975, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 8024, "s": 8008, "text": " Malhar Lathkar" }, { "code": null, "e": 8057, "s": 8024, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 8073, "s": 8057, "text": " Malhar Lathkar" }, { "code": null, "e": 8108, "s": 8073, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8122, "s": 8108, "text": " Anadi Sharma" }, { "code": null, "e": 8156, "s": 8122, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 8170, "s": 8156, "text": " Tushar Kale" }, { "code": null, "e": 8207, "s": 8170, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 8222, "s": 8207, "text": " Monica Mittal" }, { "code": null, "e": 8255, "s": 8222, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 8274, "s": 8255, "text": " Arnab Chakraborty" }, { "code": null, "e": 8281, "s": 8274, "text": " Print" }, { "code": null, "e": 8292, "s": 8281, "text": " Add Notes" } ]
How to get available wifi networks and display them in a list in android
This example demonstrate about How to get available wifi networks and display them in a list in android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".MainActivity"> <ListView android:id = "@+id/wifiList" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_above = "@+id/scanBtn" /> <Button android:id = "@+id/scanBtn" android:layout_width = "match_parent" android:layout_height = "50dp" android:layout_alignParentBottom = "true" android:layout_gravity = "bottom" android:layout_margin = "15dp" android:text = "Scan WiFi" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.Manifest; import android.content.Context; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.wifi.WifiManager; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private ListView wifiList; private WifiManager wifiManager; private final int MY_PERMISSIONS_ACCESS_COARSE_LOCATION = 1; WifiReceiver receiverWifi; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wifiList = findViewById(R.id.wifiList); Button buttonScan = findViewById(R.id.scanBtn); wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { Toast.makeText(getApplicationContext(), "Turning WiFi ON...", Toast.LENGTH_LONG).show(); wifiManager.setWifiEnabled(true); } buttonScan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) ! = PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_ACCESS_COARSE_LOCATION); } else { wifiManager.startScan(); } } }); } @Override protected void onPostResume() { super.onPostResume(); receiverWifi = new WifiReceiver(wifiManager, wifiList); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); registerReceiver(receiverWifi, intentFilter); getWifi(); } private void getWifi() { if (Build.VERSION.SDK_INT > = Build.VERSION_CODES.M) { Toast.makeText(MainActivity.this, "version> = marshmallow", Toast.LENGTH_SHORT).show(); if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) ! = PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, "location turned off", Toast.LENGTH_SHORT).show(); ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_ACCESS_COARSE_LOCATION); } else { Toast.makeText(MainActivity.this, "location turned on", Toast.LENGTH_SHORT).show(); wifiManager.startScan(); } } else { Toast.makeText(MainActivity.this, "scanning", Toast.LENGTH_SHORT).show(); wifiManager.startScan(); } } @Override protected void onPause() { super.onPause(); unregisterReceiver(receiverWifi); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case MY_PERMISSIONS_ACCESS_COARSE_LOCATION: if (grantResults.length > 0 && grantResults[0] = = PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, "permission granted", Toast.LENGTH_SHORT).show(); wifiManager.startScan(); } else { Toast.makeText(MainActivity.this, "permission not granted", Toast.LENGTH_SHORT).show(); return; } break; } } } Step 4 − Add the following code to src/WifiReceiver package com.example.myapplication; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; class WifiReceiver extends BroadcastReceiver { WifiManager wifiManager; StringBuilder sb; ListView wifiDeviceList; public WifiReceiver(WifiManager wifiManager, ListView wifiDeviceList) { this.wifiManager = wifiManager; this.wifiDeviceList = wifiDeviceList; } public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) { sb = new StringBuilder(); List<ScanResult> wifiList = wifiManager.getScanResults(); ArrayList<String> deviceList = new ArrayList<>(); for (ScanResult scanResult : wifiList) { sb.append("\n").append(scanResult.SSID).append(" - ").append(scanResult.capabilities); deviceList.add(scanResult.SSID + " - " + scanResult.capabilities); } Toast.makeText(context, sb, Toast.LENGTH_SHORT).show(); ArrayAdapter arrayAdapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, deviceList.toArray()); wifiDeviceList.setAdapter(arrayAdapter); } } } Step 5 − Add the following code to androidManifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <uses-permission android:name = "android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name = "android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name = "android.permission.CHANGE_WIFI_STATE" /> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = "com.example.myapplication.MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1166, "s": 1062, "text": "This example demonstrate about How to get available wifi networks and display them in a list in android" }, { "code": null, "e": 1295, "s": 1166, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1360, "s": 1295, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2210, "s": 1360, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".MainActivity\">\n <ListView\n android:id = \"@+id/wifiList\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_above = \"@+id/scanBtn\" />\n <Button\n android:id = \"@+id/scanBtn\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"50dp\"\n android:layout_alignParentBottom = \"true\"\n android:layout_gravity = \"bottom\"\n android:layout_margin = \"15dp\"\n android:text = \"Scan WiFi\" />\n</RelativeLayout>" }, { "code": null, "e": 2267, "s": 2210, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 6255, "s": 2267, "text": "package com.example.myapplication;\n\nimport android.Manifest;\nimport android.content.Context;\nimport android.content.IntentFilter;\nimport android.content.pm.PackageManager;\nimport android.net.wifi.WifiManager;\nimport android.os.Build;\nimport android.support.annotation.NonNull;\nimport android.support.v4.app.ActivityCompat;\nimport android.support.v4.content.ContextCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.Toast;\n\npublic class MainActivity extends AppCompatActivity {\n private ListView wifiList;\n private WifiManager wifiManager;\n private final int MY_PERMISSIONS_ACCESS_COARSE_LOCATION = 1;\n WifiReceiver receiverWifi;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n wifiList = findViewById(R.id.wifiList);\n Button buttonScan = findViewById(R.id.scanBtn);\n wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);\n if (!wifiManager.isWifiEnabled()) {\n Toast.makeText(getApplicationContext(), \"Turning WiFi ON...\", Toast.LENGTH_LONG).show();\n wifiManager.setWifiEnabled(true);\n }\n buttonScan.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)\n ! = PackageManager.PERMISSION_GRANTED) {\n ActivityCompat.requestPermissions(\n MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_ACCESS_COARSE_LOCATION);\n } else {\n wifiManager.startScan();\n }\n }\n });\n }\n @Override\n protected void onPostResume() {\n super.onPostResume();\n receiverWifi = new WifiReceiver(wifiManager, wifiList);\n IntentFilter intentFilter = new IntentFilter();\n intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);\n registerReceiver(receiverWifi, intentFilter);\n getWifi();\n }\n private void getWifi() {\n if (Build.VERSION.SDK_INT > = Build.VERSION_CODES.M) {\n Toast.makeText(MainActivity.this, \"version> = marshmallow\", Toast.LENGTH_SHORT).show();\n if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)\n ! = PackageManager.PERMISSION_GRANTED) {\n Toast.makeText(MainActivity.this, \"location turned off\", Toast.LENGTH_SHORT).show();\n ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},\n MY_PERMISSIONS_ACCESS_COARSE_LOCATION);\n } else {\n Toast.makeText(MainActivity.this, \"location turned on\", Toast.LENGTH_SHORT).show();\n wifiManager.startScan();\n }\n } else {\n Toast.makeText(MainActivity.this, \"scanning\", Toast.LENGTH_SHORT).show();\n wifiManager.startScan();\n }\n }\n @Override\n protected void onPause() {\n super.onPause();\n unregisterReceiver(receiverWifi);\n }\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n switch (requestCode) {\n case MY_PERMISSIONS_ACCESS_COARSE_LOCATION:\n if (grantResults.length > 0 && grantResults[0] = = PackageManager.PERMISSION_GRANTED) {\n Toast.makeText(MainActivity.this, \"permission granted\", Toast.LENGTH_SHORT).show();\n wifiManager.startScan();\n } else {\n Toast.makeText(MainActivity.this, \"permission not granted\", Toast.LENGTH_SHORT).show();\n return;\n }\n break;\n }\n }\n}" }, { "code": null, "e": 6307, "s": 6255, "text": "Step 4 − Add the following code to src/WifiReceiver" }, { "code": null, "e": 7780, "s": 6307, "text": "package com.example.myapplication;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.wifi.ScanResult;\nimport android.net.wifi.WifiManager;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass WifiReceiver extends BroadcastReceiver {\n WifiManager wifiManager;\n StringBuilder sb;\n ListView wifiDeviceList;\n public WifiReceiver(WifiManager wifiManager, ListView wifiDeviceList) {\n this.wifiManager = wifiManager;\n this.wifiDeviceList = wifiDeviceList;\n }\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) {\n sb = new StringBuilder();\n List<ScanResult> wifiList = wifiManager.getScanResults();\n ArrayList<String> deviceList = new ArrayList<>();\n for (ScanResult scanResult : wifiList) {\n sb.append(\"\\n\").append(scanResult.SSID).append(\" - \").append(scanResult.capabilities);\n deviceList.add(scanResult.SSID + \" - \" + scanResult.capabilities);\n }\n Toast.makeText(context, sb, Toast.LENGTH_SHORT).show();\n ArrayAdapter arrayAdapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, deviceList.toArray());\n wifiDeviceList.setAdapter(arrayAdapter);\n }\n }\n}" }, { "code": null, "e": 7835, "s": 7780, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 8806, "s": 7835, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.ACCESS_COARSE_LOCATION\" />\n <uses-permission android:name = \"android.permission.ACCESS_WIFI_STATE\" />\n <uses-permission android:name = \"android.permission.CHANGE_WIFI_STATE\" />\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \"com.example.myapplication.MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 9153, "s": 8806, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 9193, "s": 9153, "text": "Click here to download the project code" } ]
Sorting all array elements except one - GeeksforGeeks
CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsAll Courses For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More Competitive Programming Data Structures with C++ Data Science Explore More Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School CoursesSchool GuidePython ProgrammingLearn To Make Apps School Guide Python Programming Learn To Make Apps All Courses TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise Must Do Questions DSA Topic-wise DSA Company-wise AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data ScienceMachine LearningData Science Machine Learning Data Science CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software DesignsSoftware Design PatternsSystem Design Tutorial Software Design Patterns System Design Tutorial School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes School Programming MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship JobsApply for JobsPost a JobJOB-A-THON Apply for Jobs Post a Job JOB-A-THON Events WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri Geeks Digest Quizzes Geeks Campus Gblog Articles IDE Campus Mantri Sign In Sign In Home Saved Videos Courses For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps Practice DS & Algo. Must Do Questions DSA Topic-wise DSA Company-wise Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial School Learning School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON For Working Professionals LIVE DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More DSA Live Classes System Design Java Backend Development Full Stack LIVE Explore More Self-Paced DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More DSA- Self Paced SDE Theory Must-Do Coding Questions Explore More For Students LIVE Competitive Programming Data Structures with C++ Data Science Explore More Competitive Programming Data Structures with C++ Data Science Explore More Self-Paced DSA- Self Paced CIP JAVA / Python / C++ Explore More DSA- Self Paced CIP JAVA / Python / C++ Explore More School Courses School Guide Python Programming Learn To Make Apps School Guide Python Programming Learn To Make Apps Practice DS & Algo. Must Do Questions DSA Topic-wise DSA Company-wise Must Do Questions DSA Topic-wise DSA Company-wise Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Searching Algorithms Sorting Algorithms Graph Algorithms Pattern Searching Geometric Algorithms Mathematical Bitwise Algorithms Randomized Algorithms Greedy Algorithms Dynamic Programming Divide and Conquer Backtracking Branch and Bound All Algorithms Analysis of Algorithms Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Asymptotic Analysis Worst, Average and Best Cases Asymptotic Notations Little o and little omega notations Lower and Upper Bound Theory Analysis of Loops Solving Recurrences Amortized Analysis What does 'Space Complexity' mean ? Pseudo-polynomial Algorithms Polynomial Time Approximation Scheme A Time Complexity Question Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Arrays Linked List Stack Queue Binary Tree Binary Search Tree Heap Hashing Graph Advanced Data Structure Matrix Strings All Data Structures Interview Corner Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Company Preparation Top Topics Practice Company Questions Interview Experiences Experienced Interviews Internship Interviews Competititve Programming Design Patterns System Design Tutorial Multiple Choice Quizzes Languages C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin C C++ Java Python C# JavaScript jQuery SQL PHP Scala Perl Go Language HTML CSS Kotlin ML & Data Science Machine Learning Data Science Machine Learning Data Science CS Subjects Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering Mathematics Operating System DBMS Computer Networks Computer Organization and Architecture Theory of Computation Compiler Design Digital Logic Software Engineering GATE GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS GATE Computer Science Notes Last Minute Notes GATE CS Solved Papers GATE CS Original Papers and Official Keys GATE 2021 Dates GATE CS 2021 Syllabus Important Topics for GATE CS Web Technologies HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP HTML CSS JavaScript AngularJS ReactJS NodeJS Bootstrap jQuery PHP Software Designs Software Design Patterns System Design Tutorial Software Design Patterns System Design Tutorial School Learning School Programming School Programming Mathematics Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Number System Algebra Trigonometry Statistics Probability Geometry Mensuration Calculus Maths Notes (Class 8-12) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 12 Notes NCERT Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution RD Sharma Solutions Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Class 8 Maths Solution Class 9 Maths Solution Class 10 Maths Solution Class 11 Maths Solution Class 12 Maths Solution Physics Notes (Class 8-11) Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes Class 8 Notes Class 9 Notes Class 10 Notes Class 11 Notes CS Exams/PSUs ISRO ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam ISRO CS Original Papers and Official Keys ISRO CS Solved Papers ISRO CS Syllabus for Scientist/Engineer Exam UGC NET UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers UGC NET CS Notes Paper II UGC NET CS Notes Paper III UGC NET CS Solved Papers Student Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Campus Ambassador Program School Ambassador Program Project Geek of the Month Campus Geek of the Month Placement Course Competititve Programming Testimonials Geek on the Top Careers Internship Tutorials Jobs Apply for Jobs Post a Job JOB-A-THON Apply for Jobs Post a Job JOB-A-THON GBlog Puzzles What's New ? Array Matrix Strings Hashing Linked List Stack Queue Binary Tree Binary Search Tree Heap Graph Searching Sorting Divide & Conquer Mathematical Geometric Bitwise Greedy Backtracking Branch and Bound Dynamic Programming Pattern Searching Randomized Sorting all array elements except one Minimum adjacent swaps required to Sort Binary array Minimum Swaps required to group all 1’s together Java SAX Library StAX XML Parser in Java Window Sliding Technique Finding sum of digits of a number until sum becomes single digit Program for Sum of the digits of a given number Compute sum of digits in all numbers from 1 to n Count possible ways to construct buildings Maximum profit by buying and selling a share at most twice Maximum profit by buying and selling a share at most k times Stock Buy Sell to Maximize Profit Maximum difference between two elements such that larger element appears after the smaller number Given an array arr[], find the maximum j – i such that arr[j] > arr[i] Sliding Window Maximum (Maximum of all subarrays of size k) Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time Next Greater Element Next greater element in same order as input Next Greater Frequency Element Number of NGEs to the right Maximum product of indexes of next greater on left and right The Celebrity Problem Expression Evaluation Stack | Set 4 (Evaluation of Postfix Expression) Arrays in Java Write a program to reverse an array or string Largest Sum Contiguous Subarray Program for array rotation Arrays in C/C++ Sorting all array elements except one Minimum adjacent swaps required to Sort Binary array Minimum Swaps required to group all 1’s together Java SAX Library StAX XML Parser in Java Window Sliding Technique Finding sum of digits of a number until sum becomes single digit Program for Sum of the digits of a given number Compute sum of digits in all numbers from 1 to n Count possible ways to construct buildings Maximum profit by buying and selling a share at most twice Maximum profit by buying and selling a share at most k times Stock Buy Sell to Maximize Profit Maximum difference between two elements such that larger element appears after the smaller number Given an array arr[], find the maximum j – i such that arr[j] > arr[i] Sliding Window Maximum (Maximum of all subarrays of size k) Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time Next Greater Element Next greater element in same order as input Next Greater Frequency Element Number of NGEs to the right Maximum product of indexes of next greater on left and right The Celebrity Problem Expression Evaluation Stack | Set 4 (Evaluation of Postfix Expression) Arrays in Java Write a program to reverse an array or string Largest Sum Contiguous Subarray Program for array rotation Arrays in C/C++ Difficulty Level : Easy Given an array, a positive integer, sort the array in ascending order such that the element at index K in the unsorted array stays unmoved and all other elements are sorted. Examples: Input : arr[] = {10, 4, 11, 7, 6, 20} k = 2; Output : arr[] = {4, 6, 11, 7, 10, 20} Input : arr[] = {30, 20, 10} k = 0 Output : arr[] = {30, 10, 20} A simple solution is to copy all elements except k-th of a given array to another array. Then sort the other array using a sorting algorithm. Finally, again copy the sorted array to the original array. While copying, skip k-th element. Below is an efficient solution. Swap k-th element with the last element.Sort all elements except the last.For every element from (k+1)-th to last, move them one position ahead.1Copy k-th element back to position k. Swap k-th element with the last element. Sort all elements except the last. For every element from (k+1)-th to last, move them one position ahead.1 Copy k-th element back to position k. C++ Java Python3 C# PHP Javascript // CPP program to sort all elements except// element at index k.#include <bits/stdc++.h>using namespace std; int sortExceptK(int arr[], int k, int n){ // Move k-th element to end swap(arr[k], arr[n-1]); // Sort all elements except last sort(arr, arr + n - 1); // Store last element (originally k-th) int last = arr[n-1]; // Move all elements from k-th to one // position ahead. for (int i=n-1; i>k; i--) arr[i] = arr[i-1]; // Restore k-th element arr[k] = last;} // Driver codeint main(){ int a[] = {10, 4, 11, 7, 6, 20 }; int k = 2; int n = sizeof(a) / sizeof(a[0]); sortExceptK(a, k, n); for (int i = 0; i < n; i++) cout << a[i] << " ";} // Java program to sort all elements except// element at index k.import java.util.Arrays; class GFG { static int sortExceptK(int arr[], int k, int n) { // Move k-th element to end int temp = arr[k]; arr[k] = arr[n-1]; arr[n-1] = temp; // Sort all elements except last Arrays.sort(arr, 0, n-1); // Store last element (originally k-th) int last = arr[n-1]; // Move all elements from k-th to one // position ahead. for (int i = n-1; i > k; i--) arr[i] = arr[i-1]; // Restore k-th element arr[k] = last; return 0; } //Driver code public static void main (String[] args) { int a[] = {10, 4, 11, 7, 6, 20 }; int k = 2; int n = a.length; sortExceptK(a, k, n); for (int i = 0; i < n; i++) System.out.print(a[i] + " "); }} //This code is contributed by Anant Agarwal. # Python3 program to sort all elements except# element at index k.def sortExcept(arr, k, n): # Move k-th element to end arr[k], arr[-1] = arr[-1], arr[k] # Sort all elements except last arr = sorted(arr, key = lambda i: (i is arr[-1], i)) # Store last element (originally k-th) last = arr[-1] # Move all elements from k-th to one # position ahead. i = n - 1 while i > k: arr[i] = arr[i - 1] i -= 1 # Restore k-th element arr[k] = last return arr # Driver codeif __name__ == '__main__': a = [10, 4, 11, 7, 6, 20] k = 2 n = len(a) a = sortExcept(a, k, n) print(" ".join(list(map(str, a)))) # This code is contributed by Shivam Singh. // C# program to sort all elements except// element at index k.using System; public class GFG { static int sortExceptK(int[] arr, int k, int n) { // Move k-th element to end int temp = arr[k]; arr[k] = arr[n - 1]; arr[n - 1] = temp; // Sort all elements except last Array.Sort(arr, 0, n - 1); // Store last element (originally k-th) int last = arr[n - 1]; // Move all elements from k-th to one // position ahead. for (int i = n - 1; i > k; i--) arr[i] = arr[i - 1]; // Restore k-th element arr[k] = last; return 0; } // Driver code public static void Main() { int[] a = { 10, 4, 11, 7, 6, 20 }; int k = 2; int n = a.Length; sortExceptK(a, k, n); for (int i = 0; i < n; i++) Console.Write(a[i] + " "); }} // This article is contributed by shiv_bhakt <?php// PHP program to sort all// elements except element// at index k.function sortExceptK(&$arr, $k, $n){ // Move k-th element to end $t = $arr[$k]; $arr[$k] = $arr[$n - 1]; $arr[$n - 1] = $t; // Sort all elements // except last $t = $arr[count($arr) - 1]; $arr = array_slice($arr, 0, -1); sort($arr); array_push($arr, $t); // Store last element // (originally k-th) $last = $arr[$n - 1]; // Move all elements from // k-th to one position ahead. for ($i = $n - 1; $i > $k; $i--) $arr[$i] = $arr[$i - 1]; // Restore k-th element $arr[$k] = $last;} // Driver code$a = array(10, 4, 11, 7, 6, 20 );$k = 2;$n = count($a);sortExceptK($a, $k, $n); for ($i = 0; $i < $n; $i++) echo ($a[$i]." "); // This code is contributed by// Manish Shaw(manishshaw1)?> <script> // Javascript program to sort all elements except // element at index k. function sortExceptK(arr, k, n) { // Move k-th element to end let temp = arr[k]; arr[k] = arr[n-1]; arr[n-1] = temp; // Sort all elements except last arr.sort(function(a, b){ return a - b}); // Store last element (originally k-th) let last = arr[n-1]; // Move all elements from k-th to one // position ahead. for (let i = n-1; i > k; i--) arr[i] = arr[i-1]; // Restore k-th element arr[k] = last; // Move k-th element to end temp = arr[k]; arr[k] = arr[n-1]; arr[n-1] = temp; return 0; } let a = [10, 4, 11, 7, 6, 20 ]; let k = 2; let n = a.length; sortExceptK(a, k, n); for(let i = 0; i < n; i++) document.write(a[i] + " "); </script> 4 6 11 7 10 20 manishshaw1 SHIVAMSINGH67 rameshtravel07 Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java
[ { "code": null, "e": 407, "s": 0, "text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsAll Courses" }, { "code": null, "e": 588, "s": 407, "text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 673, "s": 588, "text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More" }, { "code": null, "e": 690, "s": 673, "text": "DSA Live Classes" }, { "code": null, "e": 704, "s": 690, "text": "System Design" }, { "code": null, "e": 729, "s": 704, "text": "Java Backend Development" }, { "code": null, "e": 745, "s": 729, "text": "Full Stack LIVE" }, { "code": null, "e": 758, "s": 745, "text": "Explore More" }, { "code": null, "e": 830, "s": 758, "text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More" }, { "code": null, "e": 846, "s": 830, "text": "DSA- Self Paced" }, { "code": null, "e": 857, "s": 846, "text": "SDE Theory" }, { "code": null, "e": 882, "s": 857, "text": "Must-Do Coding Questions" }, { "code": null, "e": 895, "s": 882, "text": "Explore More" }, { "code": null, "e": 1042, "s": 895, "text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1118, "s": 1042, "text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More" }, { "code": null, "e": 1142, "s": 1118, "text": "Competitive Programming" }, { "code": null, "e": 1167, "s": 1142, "text": "Data Structures with C++" }, { "code": null, "e": 1180, "s": 1167, "text": "Data Science" }, { "code": null, "e": 1193, "s": 1180, "text": "Explore More" }, { "code": null, "e": 1253, "s": 1193, "text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More" }, { "code": null, "e": 1269, "s": 1253, "text": "DSA- Self Paced" }, { "code": null, "e": 1273, "s": 1269, "text": "CIP" }, { "code": null, "e": 1293, "s": 1273, "text": "JAVA / Python / C++" }, { "code": null, "e": 1306, "s": 1293, "text": "Explore More" }, { "code": null, "e": 1369, "s": 1306, "text": "School CoursesSchool GuidePython ProgrammingLearn To Make Apps" }, { "code": null, "e": 1382, "s": 1369, "text": "School Guide" }, { "code": null, "e": 1401, "s": 1382, "text": "Python Programming" }, { "code": null, "e": 1420, "s": 1401, "text": "Learn To Make Apps" }, { "code": null, "e": 1432, "s": 1420, "text": "All Courses" }, { "code": null, "e": 3999, "s": 1432, "text": "TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship" }, { "code": null, "e": 4066, "s": 3999, "text": "Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise" }, { "code": null, "e": 4084, "s": 4066, "text": "Must Do Questions" }, { "code": null, "e": 4099, "s": 4084, "text": "DSA Topic-wise" }, { "code": null, "e": 4116, "s": 4099, "text": "DSA Company-wise" }, { "code": null, "e": 4697, "s": 4116, "text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms" }, { "code": null, "e": 5030, "s": 4697, "text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question" }, { "code": null, "e": 5050, "s": 5030, "text": "Asymptotic Analysis" }, { "code": null, "e": 5080, "s": 5050, "text": "Worst, Average and Best Cases" }, { "code": null, "e": 5101, "s": 5080, "text": "Asymptotic Notations" }, { "code": null, "e": 5137, "s": 5101, "text": "Little o and little omega notations" }, { "code": null, "e": 5166, "s": 5137, "text": "Lower and Upper Bound Theory" }, { "code": null, "e": 5184, "s": 5166, "text": "Analysis of Loops" }, { "code": null, "e": 5204, "s": 5184, "text": "Solving Recurrences" }, { "code": null, "e": 5223, "s": 5204, "text": "Amortized Analysis" }, { "code": null, "e": 5259, "s": 5223, "text": "What does 'Space Complexity' mean ?" }, { "code": null, "e": 5288, "s": 5259, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 5325, "s": 5288, "text": "Polynomial Time Approximation Scheme" }, { "code": null, "e": 5352, "s": 5325, "text": "A Time Complexity Question" }, { "code": null, "e": 5373, "s": 5352, "text": "Searching Algorithms" }, { "code": null, "e": 5392, "s": 5373, "text": "Sorting Algorithms" }, { "code": null, "e": 5409, "s": 5392, "text": "Graph Algorithms" }, { "code": null, "e": 5427, "s": 5409, "text": "Pattern Searching" }, { "code": null, "e": 5448, "s": 5427, "text": "Geometric Algorithms" }, { "code": null, "e": 5461, "s": 5448, "text": "Mathematical" }, { "code": null, "e": 5480, "s": 5461, "text": "Bitwise Algorithms" }, { "code": null, "e": 5502, "s": 5480, "text": "Randomized Algorithms" }, { "code": null, "e": 5520, "s": 5502, "text": "Greedy Algorithms" }, { "code": null, "e": 5540, "s": 5520, "text": "Dynamic Programming" }, { "code": null, "e": 5559, "s": 5540, "text": "Divide and Conquer" }, { "code": null, "e": 5572, "s": 5559, "text": "Backtracking" }, { "code": null, "e": 5589, "s": 5572, "text": "Branch and Bound" }, { "code": null, "e": 5604, "s": 5589, "text": "All Algorithms" }, { "code": null, "e": 5747, "s": 5604, "text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures" }, { "code": null, "e": 5754, "s": 5747, "text": "Arrays" }, { "code": null, "e": 5766, "s": 5754, "text": "Linked List" }, { "code": null, "e": 5772, "s": 5766, "text": "Stack" }, { "code": null, "e": 5778, "s": 5772, "text": "Queue" }, { "code": null, "e": 5790, "s": 5778, "text": "Binary Tree" }, { "code": null, "e": 5809, "s": 5790, "text": "Binary Search Tree" }, { "code": null, "e": 5814, "s": 5809, "text": "Heap" }, { "code": null, "e": 5822, "s": 5814, "text": "Hashing" }, { "code": null, "e": 5828, "s": 5822, "text": "Graph" }, { "code": null, "e": 5852, "s": 5828, "text": "Advanced Data Structure" }, { "code": null, "e": 5859, "s": 5852, "text": "Matrix" }, { "code": null, "e": 5867, "s": 5859, "text": "Strings" }, { "code": null, "e": 5887, "s": 5867, "text": "All Data Structures" }, { "code": null, "e": 6107, "s": 5887, "text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes" }, { "code": null, "e": 6127, "s": 6107, "text": "Company Preparation" }, { "code": null, "e": 6138, "s": 6127, "text": "Top Topics" }, { "code": null, "e": 6165, "s": 6138, "text": "Practice Company Questions" }, { "code": null, "e": 6187, "s": 6165, "text": "Interview Experiences" }, { "code": null, "e": 6210, "s": 6187, "text": "Experienced Interviews" }, { "code": null, "e": 6232, "s": 6210, "text": "Internship Interviews" }, { "code": null, "e": 6257, "s": 6232, "text": "Competititve Programming" }, { "code": null, "e": 6273, "s": 6257, "text": "Design Patterns" }, { "code": null, "e": 6296, "s": 6273, "text": "System Design Tutorial" }, { "code": null, "e": 6320, "s": 6296, "text": "Multiple Choice Quizzes" }, { "code": null, "e": 6401, "s": 6320, "text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin" }, { "code": null, "e": 6403, "s": 6401, "text": "C" }, { "code": null, "e": 6407, "s": 6403, "text": "C++" }, { "code": null, "e": 6412, "s": 6407, "text": "Java" }, { "code": null, "e": 6419, "s": 6412, "text": "Python" }, { "code": null, "e": 6422, "s": 6419, "text": "C#" }, { "code": null, "e": 6433, "s": 6422, "text": "JavaScript" }, { "code": null, "e": 6440, "s": 6433, "text": "jQuery" }, { "code": null, "e": 6444, "s": 6440, "text": "SQL" }, { "code": null, "e": 6448, "s": 6444, "text": "PHP" }, { "code": null, "e": 6454, "s": 6448, "text": "Scala" }, { "code": null, "e": 6459, "s": 6454, "text": "Perl" }, { "code": null, "e": 6471, "s": 6459, "text": "Go Language" }, { "code": null, "e": 6476, "s": 6471, "text": "HTML" }, { "code": null, "e": 6480, "s": 6476, "text": "CSS" }, { "code": null, "e": 6487, "s": 6480, "text": "Kotlin" }, { "code": null, "e": 6533, "s": 6487, "text": "ML & Data ScienceMachine LearningData Science" }, { "code": null, "e": 6550, "s": 6533, "text": "Machine Learning" }, { "code": null, "e": 6563, "s": 6550, "text": "Data Science" }, { "code": null, "e": 6730, "s": 6563, "text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering" }, { "code": null, "e": 6742, "s": 6730, "text": "Mathematics" }, { "code": null, "e": 6759, "s": 6742, "text": "Operating System" }, { "code": null, "e": 6764, "s": 6759, "text": "DBMS" }, { "code": null, "e": 6782, "s": 6764, "text": "Computer Networks" }, { "code": null, "e": 6821, "s": 6782, "text": "Computer Organization and Architecture" }, { "code": null, "e": 6843, "s": 6821, "text": "Theory of Computation" }, { "code": null, "e": 6859, "s": 6843, "text": "Compiler Design" }, { "code": null, "e": 6873, "s": 6859, "text": "Digital Logic" }, { "code": null, "e": 6894, "s": 6873, "text": "Software Engineering" }, { "code": null, "e": 7069, "s": 6894, "text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS" }, { "code": null, "e": 7097, "s": 7069, "text": "GATE Computer Science Notes" }, { "code": null, "e": 7115, "s": 7097, "text": "Last Minute Notes" }, { "code": null, "e": 7137, "s": 7115, "text": "GATE CS Solved Papers" }, { "code": null, "e": 7179, "s": 7137, "text": "GATE CS Original Papers and Official Keys" }, { "code": null, "e": 7195, "s": 7179, "text": "GATE 2021 Dates" }, { "code": null, "e": 7217, "s": 7195, "text": "GATE CS 2021 Syllabus" }, { "code": null, "e": 7246, "s": 7217, "text": "Important Topics for GATE CS" }, { "code": null, "e": 7320, "s": 7246, "text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP" }, { "code": null, "e": 7325, "s": 7320, "text": "HTML" }, { "code": null, "e": 7329, "s": 7325, "text": "CSS" }, { "code": null, "e": 7340, "s": 7329, "text": "JavaScript" }, { "code": null, "e": 7350, "s": 7340, "text": "AngularJS" }, { "code": null, "e": 7358, "s": 7350, "text": "ReactJS" }, { "code": null, "e": 7365, "s": 7358, "text": "NodeJS" }, { "code": null, "e": 7375, "s": 7365, "text": "Bootstrap" }, { "code": null, "e": 7382, "s": 7375, "text": "jQuery" }, { "code": null, "e": 7386, "s": 7382, "text": "PHP" }, { "code": null, "e": 7449, "s": 7386, "text": "Software DesignsSoftware Design PatternsSystem Design Tutorial" }, { "code": null, "e": 7474, "s": 7449, "text": "Software Design Patterns" }, { "code": null, "e": 7497, "s": 7474, "text": "System Design Tutorial" }, { "code": null, "e": 8054, "s": 7497, "text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 8073, "s": 8054, "text": "School Programming" }, { "code": null, "e": 8165, "s": 8073, "text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus" }, { "code": null, "e": 8179, "s": 8165, "text": "Number System" }, { "code": null, "e": 8187, "s": 8179, "text": "Algebra" }, { "code": null, "e": 8200, "s": 8187, "text": "Trigonometry" }, { "code": null, "e": 8211, "s": 8200, "text": "Statistics" }, { "code": null, "e": 8223, "s": 8211, "text": "Probability" }, { "code": null, "e": 8232, "s": 8223, "text": "Geometry" }, { "code": null, "e": 8244, "s": 8232, "text": "Mensuration" }, { "code": null, "e": 8253, "s": 8244, "text": "Calculus" }, { "code": null, "e": 8346, "s": 8253, "text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes" }, { "code": null, "e": 8360, "s": 8346, "text": "Class 8 Notes" }, { "code": null, "e": 8374, "s": 8360, "text": "Class 9 Notes" }, { "code": null, "e": 8389, "s": 8374, "text": "Class 10 Notes" }, { "code": null, "e": 8404, "s": 8389, "text": "Class 11 Notes" }, { "code": null, "e": 8419, "s": 8404, "text": "Class 12 Notes" }, { "code": null, "e": 8548, "s": 8419, "text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8571, "s": 8548, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8594, "s": 8571, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8618, "s": 8594, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8642, "s": 8618, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8666, "s": 8642, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8799, "s": 8666, "text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution" }, { "code": null, "e": 8822, "s": 8799, "text": "Class 8 Maths Solution" }, { "code": null, "e": 8845, "s": 8822, "text": "Class 9 Maths Solution" }, { "code": null, "e": 8869, "s": 8845, "text": "Class 10 Maths Solution" }, { "code": null, "e": 8893, "s": 8869, "text": "Class 11 Maths Solution" }, { "code": null, "e": 8917, "s": 8893, "text": "Class 12 Maths Solution" }, { "code": null, "e": 8998, "s": 8917, "text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes" }, { "code": null, "e": 9012, "s": 8998, "text": "Class 8 Notes" }, { "code": null, "e": 9026, "s": 9012, "text": "Class 9 Notes" }, { "code": null, "e": 9041, "s": 9026, "text": "Class 10 Notes" }, { "code": null, "e": 9056, "s": 9041, "text": "Class 11 Notes" }, { "code": null, "e": 9262, "s": 9056, "text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9373, "s": 9262, "text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9415, "s": 9373, "text": "ISRO CS Original Papers and Official Keys" }, { "code": null, "e": 9437, "s": 9415, "text": "ISRO CS Solved Papers" }, { "code": null, "e": 9482, "s": 9437, "text": "ISRO CS Syllabus for Scientist/Engineer Exam" }, { "code": null, "e": 9565, "s": 9482, "text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers" }, { "code": null, "e": 9591, "s": 9565, "text": "UGC NET CS Notes Paper II" }, { "code": null, "e": 9618, "s": 9591, "text": "UGC NET CS Notes Paper III" }, { "code": null, "e": 9643, "s": 9618, "text": "UGC NET CS Solved Papers" }, { "code": null, "e": 9833, "s": 9643, "text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship" }, { "code": null, "e": 9859, "s": 9833, "text": "Campus Ambassador Program" }, { "code": null, "e": 9885, "s": 9859, "text": "School Ambassador Program" }, { "code": null, "e": 9893, "s": 9885, "text": "Project" }, { "code": null, "e": 9911, "s": 9893, "text": "Geek of the Month" }, { "code": null, "e": 9936, "s": 9911, "text": "Campus Geek of the Month" }, { "code": null, "e": 9953, "s": 9936, "text": "Placement Course" }, { "code": null, "e": 9978, "s": 9953, "text": "Competititve Programming" }, { "code": null, "e": 9991, "s": 9978, "text": "Testimonials" }, { "code": null, "e": 10007, "s": 9991, "text": "Geek on the Top" }, { "code": null, "e": 10015, "s": 10007, "text": "Careers" }, { "code": null, "e": 10026, "s": 10015, "text": "Internship" }, { "code": null, "e": 10065, "s": 10026, "text": "JobsApply for JobsPost a JobJOB-A-THON" }, { "code": null, "e": 10080, "s": 10065, "text": "Apply for Jobs" }, { "code": null, "e": 10091, "s": 10080, "text": "Post a Job" }, { "code": null, "e": 10102, "s": 10091, "text": "JOB-A-THON" }, { "code": null, "e": 10109, "s": 10102, "text": "Events" }, { "code": null, "e": 10380, "s": 10113, "text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri" }, { "code": null, "e": 10393, "s": 10380, "text": "Geeks Digest" }, { "code": null, "e": 10401, "s": 10393, "text": "Quizzes" }, { "code": null, "e": 10414, "s": 10401, "text": "Geeks Campus" }, { "code": null, "e": 10429, "s": 10414, "text": "Gblog Articles" }, { "code": null, "e": 10433, "s": 10429, "text": "IDE" }, { "code": null, "e": 10447, "s": 10433, "text": "Campus Mantri" }, { "code": null, "e": 10455, "s": 10447, "text": "Sign In" }, { "code": null, "e": 10463, "s": 10455, "text": "Sign In" }, { "code": null, "e": 10468, "s": 10463, "text": "Home" }, { "code": null, "e": 10481, "s": 10468, "text": "Saved Videos" }, { "code": null, "e": 10489, "s": 10481, "text": "Courses" }, { "code": null, "e": 14680, "s": 10489, "text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\n\nPractice DS & Algo.\n \n\n\nMust Do Questions\n\nDSA Topic-wise\n\nDSA Company-wise\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nGeek on the Top\n\nCareers\n\nInternship\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 14734, "s": 14680, "text": "\nFor Working Professionals\n \n\n" }, { "code": null, "e": 14857, "s": 14734, "text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n" }, { "code": null, "e": 14876, "s": 14857, "text": "\nDSA Live Classes\n" }, { "code": null, "e": 14892, "s": 14876, "text": "\nSystem Design\n" }, { "code": null, "e": 14919, "s": 14892, "text": "\nJava Backend Development\n" }, { "code": null, "e": 14937, "s": 14919, "text": "\nFull Stack LIVE\n" }, { "code": null, "e": 14952, "s": 14937, "text": "\nExplore More\n" }, { "code": null, "e": 15060, "s": 14952, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n" }, { "code": null, "e": 15078, "s": 15060, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15091, "s": 15078, "text": "\nSDE Theory\n" }, { "code": null, "e": 15118, "s": 15091, "text": "\nMust-Do Coding Questions\n" }, { "code": null, "e": 15133, "s": 15118, "text": "\nExplore More\n" }, { "code": null, "e": 15174, "s": 15133, "text": "\nFor Students\n \n\n" }, { "code": null, "e": 15286, "s": 15174, "text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n" }, { "code": null, "e": 15312, "s": 15286, "text": "\nCompetitive Programming\n" }, { "code": null, "e": 15339, "s": 15312, "text": "\nData Structures with C++\n" }, { "code": null, "e": 15354, "s": 15339, "text": "\nData Science\n" }, { "code": null, "e": 15369, "s": 15354, "text": "\nExplore More\n" }, { "code": null, "e": 15465, "s": 15369, "text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n" }, { "code": null, "e": 15483, "s": 15465, "text": "\nDSA- Self Paced\n" }, { "code": null, "e": 15489, "s": 15483, "text": "\nCIP\n" }, { "code": null, "e": 15511, "s": 15489, "text": "\nJAVA / Python / C++\n" }, { "code": null, "e": 15526, "s": 15511, "text": "\nExplore More\n" }, { "code": null, "e": 15623, "s": 15526, "text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n" }, { "code": null, "e": 15638, "s": 15623, "text": "\nSchool Guide\n" }, { "code": null, "e": 15659, "s": 15638, "text": "\nPython Programming\n" }, { "code": null, "e": 15680, "s": 15659, "text": "\nLearn To Make Apps\n" }, { "code": null, "e": 15781, "s": 15680, "text": "\nPractice DS & Algo.\n \n\n\nMust Do Questions\n\nDSA Topic-wise\n\nDSA Company-wise\n" }, { "code": null, "e": 15801, "s": 15781, "text": "\nMust Do Questions\n" }, { "code": null, "e": 15818, "s": 15801, "text": "\nDSA Topic-wise\n" }, { "code": null, "e": 15837, "s": 15818, "text": "\nDSA Company-wise\n" }, { "code": null, "e": 16142, "s": 15837, "text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n" }, { "code": null, "e": 16165, "s": 16142, "text": "\nSearching Algorithms\n" }, { "code": null, "e": 16186, "s": 16165, "text": "\nSorting Algorithms\n" }, { "code": null, "e": 16205, "s": 16186, "text": "\nGraph Algorithms\n" }, { "code": null, "e": 16225, "s": 16205, "text": "\nPattern Searching\n" }, { "code": null, "e": 16248, "s": 16225, "text": "\nGeometric Algorithms\n" }, { "code": null, "e": 16263, "s": 16248, "text": "\nMathematical\n" }, { "code": null, "e": 16284, "s": 16263, "text": "\nBitwise Algorithms\n" }, { "code": null, "e": 16308, "s": 16284, "text": "\nRandomized Algorithms\n" }, { "code": null, "e": 16328, "s": 16308, "text": "\nGreedy Algorithms\n" }, { "code": null, "e": 16350, "s": 16328, "text": "\nDynamic Programming\n" }, { "code": null, "e": 16371, "s": 16350, "text": "\nDivide and Conquer\n" }, { "code": null, "e": 16386, "s": 16371, "text": "\nBacktracking\n" }, { "code": null, "e": 16405, "s": 16386, "text": "\nBranch and Bound\n" }, { "code": null, "e": 16422, "s": 16405, "text": "\nAll Algorithms\n" }, { "code": null, "e": 16807, "s": 16422, "text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n" }, { "code": null, "e": 16829, "s": 16807, "text": "\nAsymptotic Analysis\n" }, { "code": null, "e": 16861, "s": 16829, "text": "\nWorst, Average and Best Cases\n" }, { "code": null, "e": 16884, "s": 16861, "text": "\nAsymptotic Notations\n" }, { "code": null, "e": 16922, "s": 16884, "text": "\nLittle o and little omega notations\n" }, { "code": null, "e": 16953, "s": 16922, "text": "\nLower and Upper Bound Theory\n" }, { "code": null, "e": 16973, "s": 16953, "text": "\nAnalysis of Loops\n" }, { "code": null, "e": 16995, "s": 16973, "text": "\nSolving Recurrences\n" }, { "code": null, "e": 17016, "s": 16995, "text": "\nAmortized Analysis\n" }, { "code": null, "e": 17054, "s": 17016, "text": "\nWhat does 'Space Complexity' mean ?\n" }, { "code": null, "e": 17085, "s": 17054, "text": "\nPseudo-polynomial Algorithms\n" }, { "code": null, "e": 17124, "s": 17085, "text": "\nPolynomial Time Approximation Scheme\n" }, { "code": null, "e": 17153, "s": 17124, "text": "\nA Time Complexity Question\n" }, { "code": null, "e": 17350, "s": 17153, "text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n" }, { "code": null, "e": 17359, "s": 17350, "text": "\nArrays\n" }, { "code": null, "e": 17373, "s": 17359, "text": "\nLinked List\n" }, { "code": null, "e": 17381, "s": 17373, "text": "\nStack\n" }, { "code": null, "e": 17389, "s": 17381, "text": "\nQueue\n" }, { "code": null, "e": 17403, "s": 17389, "text": "\nBinary Tree\n" }, { "code": null, "e": 17424, "s": 17403, "text": "\nBinary Search Tree\n" }, { "code": null, "e": 17431, "s": 17424, "text": "\nHeap\n" }, { "code": null, "e": 17441, "s": 17431, "text": "\nHashing\n" }, { "code": null, "e": 17449, "s": 17441, "text": "\nGraph\n" }, { "code": null, "e": 17475, "s": 17449, "text": "\nAdvanced Data Structure\n" }, { "code": null, "e": 17484, "s": 17475, "text": "\nMatrix\n" }, { "code": null, "e": 17494, "s": 17484, "text": "\nStrings\n" }, { "code": null, "e": 17516, "s": 17494, "text": "\nAll Data Structures\n" }, { "code": null, "e": 17784, "s": 17516, "text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n" }, { "code": null, "e": 17806, "s": 17784, "text": "\nCompany Preparation\n" }, { "code": null, "e": 17819, "s": 17806, "text": "\nTop Topics\n" }, { "code": null, "e": 17848, "s": 17819, "text": "\nPractice Company Questions\n" }, { "code": null, "e": 17872, "s": 17848, "text": "\nInterview Experiences\n" }, { "code": null, "e": 17897, "s": 17872, "text": "\nExperienced Interviews\n" }, { "code": null, "e": 17921, "s": 17897, "text": "\nInternship Interviews\n" }, { "code": null, "e": 17948, "s": 17921, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 17966, "s": 17948, "text": "\nDesign Patterns\n" }, { "code": null, "e": 17991, "s": 17966, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 18017, "s": 17991, "text": "\nMultiple Choice Quizzes\n" }, { "code": null, "e": 18156, "s": 18017, "text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n" }, { "code": null, "e": 18160, "s": 18156, "text": "\nC\n" }, { "code": null, "e": 18166, "s": 18160, "text": "\nC++\n" }, { "code": null, "e": 18173, "s": 18166, "text": "\nJava\n" }, { "code": null, "e": 18182, "s": 18173, "text": "\nPython\n" }, { "code": null, "e": 18187, "s": 18182, "text": "\nC#\n" }, { "code": null, "e": 18200, "s": 18187, "text": "\nJavaScript\n" }, { "code": null, "e": 18209, "s": 18200, "text": "\njQuery\n" }, { "code": null, "e": 18215, "s": 18209, "text": "\nSQL\n" }, { "code": null, "e": 18221, "s": 18215, "text": "\nPHP\n" }, { "code": null, "e": 18229, "s": 18221, "text": "\nScala\n" }, { "code": null, "e": 18236, "s": 18229, "text": "\nPerl\n" }, { "code": null, "e": 18250, "s": 18236, "text": "\nGo Language\n" }, { "code": null, "e": 18257, "s": 18250, "text": "\nHTML\n" }, { "code": null, "e": 18263, "s": 18257, "text": "\nCSS\n" }, { "code": null, "e": 18272, "s": 18263, "text": "\nKotlin\n" }, { "code": null, "e": 18350, "s": 18272, "text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n" }, { "code": null, "e": 18369, "s": 18350, "text": "\nMachine Learning\n" }, { "code": null, "e": 18384, "s": 18369, "text": "\nData Science\n" }, { "code": null, "e": 18597, "s": 18384, "text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n" }, { "code": null, "e": 18611, "s": 18597, "text": "\nMathematics\n" }, { "code": null, "e": 18630, "s": 18611, "text": "\nOperating System\n" }, { "code": null, "e": 18637, "s": 18630, "text": "\nDBMS\n" }, { "code": null, "e": 18657, "s": 18637, "text": "\nComputer Networks\n" }, { "code": null, "e": 18698, "s": 18657, "text": "\nComputer Organization and Architecture\n" }, { "code": null, "e": 18722, "s": 18698, "text": "\nTheory of Computation\n" }, { "code": null, "e": 18740, "s": 18722, "text": "\nCompiler Design\n" }, { "code": null, "e": 18756, "s": 18740, "text": "\nDigital Logic\n" }, { "code": null, "e": 18779, "s": 18756, "text": "\nSoftware Engineering\n" }, { "code": null, "e": 18996, "s": 18779, "text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19026, "s": 18996, "text": "\nGATE Computer Science Notes\n" }, { "code": null, "e": 19046, "s": 19026, "text": "\nLast Minute Notes\n" }, { "code": null, "e": 19070, "s": 19046, "text": "\nGATE CS Solved Papers\n" }, { "code": null, "e": 19114, "s": 19070, "text": "\nGATE CS Original Papers and Official Keys\n" }, { "code": null, "e": 19132, "s": 19114, "text": "\nGATE 2021 Dates\n" }, { "code": null, "e": 19156, "s": 19132, "text": "\nGATE CS 2021 Syllabus\n" }, { "code": null, "e": 19187, "s": 19156, "text": "\nImportant Topics for GATE CS\n" }, { "code": null, "e": 19307, "s": 19187, "text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n" }, { "code": null, "e": 19314, "s": 19307, "text": "\nHTML\n" }, { "code": null, "e": 19320, "s": 19314, "text": "\nCSS\n" }, { "code": null, "e": 19333, "s": 19320, "text": "\nJavaScript\n" }, { "code": null, "e": 19345, "s": 19333, "text": "\nAngularJS\n" }, { "code": null, "e": 19355, "s": 19345, "text": "\nReactJS\n" }, { "code": null, "e": 19364, "s": 19355, "text": "\nNodeJS\n" }, { "code": null, "e": 19376, "s": 19364, "text": "\nBootstrap\n" }, { "code": null, "e": 19385, "s": 19376, "text": "\njQuery\n" }, { "code": null, "e": 19391, "s": 19385, "text": "\nPHP\n" }, { "code": null, "e": 19486, "s": 19391, "text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n" }, { "code": null, "e": 19513, "s": 19486, "text": "\nSoftware Design Patterns\n" }, { "code": null, "e": 19538, "s": 19513, "text": "\nSystem Design Tutorial\n" }, { "code": null, "e": 19602, "s": 19538, "text": "\nSchool Learning\n \n\n\nSchool Programming\n" }, { "code": null, "e": 19623, "s": 19602, "text": "\nSchool Programming\n" }, { "code": null, "e": 19759, "s": 19623, "text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n" }, { "code": null, "e": 19775, "s": 19759, "text": "\nNumber System\n" }, { "code": null, "e": 19785, "s": 19775, "text": "\nAlgebra\n" }, { "code": null, "e": 19800, "s": 19785, "text": "\nTrigonometry\n" }, { "code": null, "e": 19813, "s": 19800, "text": "\nStatistics\n" }, { "code": null, "e": 19827, "s": 19813, "text": "\nProbability\n" }, { "code": null, "e": 19838, "s": 19827, "text": "\nGeometry\n" }, { "code": null, "e": 19852, "s": 19838, "text": "\nMensuration\n" }, { "code": null, "e": 19863, "s": 19852, "text": "\nCalculus\n" }, { "code": null, "e": 19994, "s": 19863, "text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n" }, { "code": null, "e": 20010, "s": 19994, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20026, "s": 20010, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20043, "s": 20026, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20060, "s": 20043, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20077, "s": 20060, "text": "\nClass 12 Notes\n" }, { "code": null, "e": 20244, "s": 20077, "text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 20269, "s": 20244, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20294, "s": 20269, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20320, "s": 20294, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 20346, "s": 20320, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 20372, "s": 20346, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 20543, "s": 20372, "text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n" }, { "code": null, "e": 20568, "s": 20543, "text": "\nClass 8 Maths Solution\n" }, { "code": null, "e": 20593, "s": 20568, "text": "\nClass 9 Maths Solution\n" }, { "code": null, "e": 20619, "s": 20593, "text": "\nClass 10 Maths Solution\n" }, { "code": null, "e": 20645, "s": 20619, "text": "\nClass 11 Maths Solution\n" }, { "code": null, "e": 20671, "s": 20645, "text": "\nClass 12 Maths Solution\n" }, { "code": null, "e": 20788, "s": 20671, "text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n" }, { "code": null, "e": 20804, "s": 20788, "text": "\nClass 8 Notes\n" }, { "code": null, "e": 20820, "s": 20804, "text": "\nClass 9 Notes\n" }, { "code": null, "e": 20837, "s": 20820, "text": "\nClass 10 Notes\n" }, { "code": null, "e": 20854, "s": 20837, "text": "\nClass 11 Notes\n" }, { "code": null, "e": 20896, "s": 20854, "text": "\nCS Exams/PSUs\n \n\n" }, { "code": null, "e": 21041, "s": 20896, "text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21085, "s": 21041, "text": "\nISRO CS Original Papers and Official Keys\n" }, { "code": null, "e": 21109, "s": 21085, "text": "\nISRO CS Solved Papers\n" }, { "code": null, "e": 21156, "s": 21109, "text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n" }, { "code": null, "e": 21273, "s": 21156, "text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21301, "s": 21273, "text": "\nUGC NET CS Notes Paper II\n" }, { "code": null, "e": 21330, "s": 21301, "text": "\nUGC NET CS Notes Paper III\n" }, { "code": null, "e": 21357, "s": 21330, "text": "\nUGC NET CS Solved Papers\n" }, { "code": null, "e": 21597, "s": 21357, "text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nGeek on the Top\n\nCareers\n\nInternship\n" }, { "code": null, "e": 21625, "s": 21597, "text": "\nCampus Ambassador Program\n" }, { "code": null, "e": 21653, "s": 21625, "text": "\nSchool Ambassador Program\n" }, { "code": null, "e": 21663, "s": 21653, "text": "\nProject\n" }, { "code": null, "e": 21683, "s": 21663, "text": "\nGeek of the Month\n" }, { "code": null, "e": 21710, "s": 21683, "text": "\nCampus Geek of the Month\n" }, { "code": null, "e": 21729, "s": 21710, "text": "\nPlacement Course\n" }, { "code": null, "e": 21756, "s": 21729, "text": "\nCompetititve Programming\n" }, { "code": null, "e": 21771, "s": 21756, "text": "\nTestimonials\n" }, { "code": null, "e": 21789, "s": 21771, "text": "\nGeek on the Top\n" }, { "code": null, "e": 21799, "s": 21789, "text": "\nCareers\n" }, { "code": null, "e": 21812, "s": 21799, "text": "\nInternship\n" }, { "code": null, "e": 21850, "s": 21812, "text": "\nTutorials\n \n\n" }, { "code": null, "e": 21923, "s": 21850, "text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n" }, { "code": null, "e": 21940, "s": 21923, "text": "\nApply for Jobs\n" }, { "code": null, "e": 21953, "s": 21940, "text": "\nPost a Job\n" }, { "code": null, "e": 21966, "s": 21953, "text": "\nJOB-A-THON\n" }, { "code": null, "e": 21972, "s": 21966, "text": "GBlog" }, { "code": null, "e": 21980, "s": 21972, "text": "Puzzles" }, { "code": null, "e": 21993, "s": 21980, "text": "What's New ?" }, { "code": null, "e": 21999, "s": 21993, "text": "Array" }, { "code": null, "e": 22006, "s": 21999, "text": "Matrix" }, { "code": null, "e": 22014, "s": 22006, "text": "Strings" }, { "code": null, "e": 22022, "s": 22014, "text": "Hashing" }, { "code": null, "e": 22034, "s": 22022, "text": "Linked List" }, { "code": null, "e": 22040, "s": 22034, "text": "Stack" }, { "code": null, "e": 22046, "s": 22040, "text": "Queue" }, { "code": null, "e": 22058, "s": 22046, "text": "Binary Tree" }, { "code": null, "e": 22077, "s": 22058, "text": "Binary Search Tree" }, { "code": null, "e": 22082, "s": 22077, "text": "Heap" }, { "code": null, "e": 22088, "s": 22082, "text": "Graph" }, { "code": null, "e": 22098, "s": 22088, "text": "Searching" }, { "code": null, "e": 22106, "s": 22098, "text": "Sorting" }, { "code": null, "e": 22123, "s": 22106, "text": "Divide & Conquer" }, { "code": null, "e": 22136, "s": 22123, "text": "Mathematical" }, { "code": null, "e": 22146, "s": 22136, "text": "Geometric" }, { "code": null, "e": 22154, "s": 22146, "text": "Bitwise" }, { "code": null, "e": 22161, "s": 22154, "text": "Greedy" }, { "code": null, "e": 22174, "s": 22161, "text": "Backtracking" }, { "code": null, "e": 22191, "s": 22174, "text": "Branch and Bound" }, { "code": null, "e": 22211, "s": 22191, "text": "Dynamic Programming" }, { "code": null, "e": 22229, "s": 22211, "text": "Pattern Searching" }, { "code": null, "e": 22240, "s": 22229, "text": "Randomized" }, { "code": null, "e": 22278, "s": 22240, "text": "Sorting all array elements except one" }, { "code": null, "e": 22331, "s": 22278, "text": "Minimum adjacent swaps required to Sort Binary array" }, { "code": null, "e": 22380, "s": 22331, "text": "Minimum Swaps required to group all 1’s together" }, { "code": null, "e": 22397, "s": 22380, "text": "Java SAX Library" }, { "code": null, "e": 22421, "s": 22397, "text": "StAX XML Parser in Java" }, { "code": null, "e": 22446, "s": 22421, "text": "Window Sliding Technique" }, { "code": null, "e": 22511, "s": 22446, "text": "Finding sum of digits of a number until sum becomes single digit" }, { "code": null, "e": 22559, "s": 22511, "text": "Program for Sum of the digits of a given number" }, { "code": null, "e": 22608, "s": 22559, "text": "Compute sum of digits in all numbers from 1 to n" }, { "code": null, "e": 22651, "s": 22608, "text": "Count possible ways to construct buildings" }, { "code": null, "e": 22710, "s": 22651, "text": "Maximum profit by buying and selling a share at most twice" }, { "code": null, "e": 22771, "s": 22710, "text": "Maximum profit by buying and selling a share at most k times" }, { "code": null, "e": 22805, "s": 22771, "text": "Stock Buy Sell to Maximize Profit" }, { "code": null, "e": 22903, "s": 22805, "text": "Maximum difference between two elements such that larger element appears after the smaller number" }, { "code": null, "e": 22974, "s": 22903, "text": "Given an array arr[], find the maximum j – i such that arr[j] > arr[i]" }, { "code": null, "e": 23034, "s": 22974, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 23119, "s": 23034, "text": "Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time" }, { "code": null, "e": 23140, "s": 23119, "text": "Next Greater Element" }, { "code": null, "e": 23184, "s": 23140, "text": "Next greater element in same order as input" }, { "code": null, "e": 23215, "s": 23184, "text": "Next Greater Frequency Element" }, { "code": null, "e": 23243, "s": 23215, "text": "Number of NGEs to the right" }, { "code": null, "e": 23304, "s": 23243, "text": "Maximum product of indexes of next greater on left and right" }, { "code": null, "e": 23326, "s": 23304, "text": "The Celebrity Problem" }, { "code": null, "e": 23348, "s": 23326, "text": "Expression Evaluation" }, { "code": null, "e": 23397, "s": 23348, "text": "Stack | Set 4 (Evaluation of Postfix Expression)" }, { "code": null, "e": 23412, "s": 23397, "text": "Arrays in Java" }, { "code": null, "e": 23458, "s": 23412, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 23490, "s": 23458, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 23517, "s": 23490, "text": "Program for array rotation" }, { "code": null, "e": 23533, "s": 23517, "text": "Arrays in C/C++" }, { "code": null, "e": 23571, "s": 23533, "text": "Sorting all array elements except one" }, { "code": null, "e": 23624, "s": 23571, "text": "Minimum adjacent swaps required to Sort Binary array" }, { "code": null, "e": 23673, "s": 23624, "text": "Minimum Swaps required to group all 1’s together" }, { "code": null, "e": 23690, "s": 23673, "text": "Java SAX Library" }, { "code": null, "e": 23714, "s": 23690, "text": "StAX XML Parser in Java" }, { "code": null, "e": 23739, "s": 23714, "text": "Window Sliding Technique" }, { "code": null, "e": 23804, "s": 23739, "text": "Finding sum of digits of a number until sum becomes single digit" }, { "code": null, "e": 23852, "s": 23804, "text": "Program for Sum of the digits of a given number" }, { "code": null, "e": 23901, "s": 23852, "text": "Compute sum of digits in all numbers from 1 to n" }, { "code": null, "e": 23944, "s": 23901, "text": "Count possible ways to construct buildings" }, { "code": null, "e": 24003, "s": 23944, "text": "Maximum profit by buying and selling a share at most twice" }, { "code": null, "e": 24064, "s": 24003, "text": "Maximum profit by buying and selling a share at most k times" }, { "code": null, "e": 24098, "s": 24064, "text": "Stock Buy Sell to Maximize Profit" }, { "code": null, "e": 24196, "s": 24098, "text": "Maximum difference between two elements such that larger element appears after the smaller number" }, { "code": null, "e": 24267, "s": 24196, "text": "Given an array arr[], find the maximum j – i such that arr[j] > arr[i]" }, { "code": null, "e": 24327, "s": 24267, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 24412, "s": 24327, "text": "Sliding Window Maximum (Maximum of all subarrays of size k) using stack in O(n) time" }, { "code": null, "e": 24433, "s": 24412, "text": "Next Greater Element" }, { "code": null, "e": 24477, "s": 24433, "text": "Next greater element in same order as input" }, { "code": null, "e": 24508, "s": 24477, "text": "Next Greater Frequency Element" }, { "code": null, "e": 24536, "s": 24508, "text": "Number of NGEs to the right" }, { "code": null, "e": 24597, "s": 24536, "text": "Maximum product of indexes of next greater on left and right" }, { "code": null, "e": 24619, "s": 24597, "text": "The Celebrity Problem" }, { "code": null, "e": 24641, "s": 24619, "text": "Expression Evaluation" }, { "code": null, "e": 24690, "s": 24641, "text": "Stack | Set 4 (Evaluation of Postfix Expression)" }, { "code": null, "e": 24705, "s": 24690, "text": "Arrays in Java" }, { "code": null, "e": 24751, "s": 24705, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 24783, "s": 24751, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 24810, "s": 24783, "text": "Program for array rotation" }, { "code": null, "e": 24826, "s": 24810, "text": "Arrays in C/C++" }, { "code": null, "e": 24850, "s": 24826, "text": "Difficulty Level :\nEasy" }, { "code": null, "e": 25025, "s": 24850, "text": "Given an array, a positive integer, sort the array in ascending order such that the element at index K in the unsorted array stays unmoved and all other elements are sorted. " }, { "code": null, "e": 25036, "s": 25025, "text": "Examples: " }, { "code": null, "e": 25208, "s": 25036, "text": "Input : arr[] = {10, 4, 11, 7, 6, 20}\n k = 2;\nOutput : arr[] = {4, 6, 11, 7, 10, 20}\n\nInput : arr[] = {30, 20, 10}\n k = 0\nOutput : arr[] = {30, 10, 20} " }, { "code": null, "e": 25445, "s": 25208, "text": "A simple solution is to copy all elements except k-th of a given array to another array. Then sort the other array using a sorting algorithm. Finally, again copy the sorted array to the original array. While copying, skip k-th element. " }, { "code": null, "e": 25479, "s": 25445, "text": "Below is an efficient solution. " }, { "code": null, "e": 25663, "s": 25479, "text": "Swap k-th element with the last element.Sort all elements except the last.For every element from (k+1)-th to last, move them one position ahead.1Copy k-th element back to position k. " }, { "code": null, "e": 25704, "s": 25663, "text": "Swap k-th element with the last element." }, { "code": null, "e": 25739, "s": 25704, "text": "Sort all elements except the last." }, { "code": null, "e": 25811, "s": 25739, "text": "For every element from (k+1)-th to last, move them one position ahead.1" }, { "code": null, "e": 25850, "s": 25811, "text": "Copy k-th element back to position k. " }, { "code": null, "e": 25854, "s": 25850, "text": "C++" }, { "code": null, "e": 25859, "s": 25854, "text": "Java" }, { "code": null, "e": 25867, "s": 25859, "text": "Python3" }, { "code": null, "e": 25870, "s": 25867, "text": "C#" }, { "code": null, "e": 25874, "s": 25870, "text": "PHP" }, { "code": null, "e": 25885, "s": 25874, "text": "Javascript" }, { "code": "// CPP program to sort all elements except// element at index k.#include <bits/stdc++.h>using namespace std; int sortExceptK(int arr[], int k, int n){ // Move k-th element to end swap(arr[k], arr[n-1]); // Sort all elements except last sort(arr, arr + n - 1); // Store last element (originally k-th) int last = arr[n-1]; // Move all elements from k-th to one // position ahead. for (int i=n-1; i>k; i--) arr[i] = arr[i-1]; // Restore k-th element arr[k] = last;} // Driver codeint main(){ int a[] = {10, 4, 11, 7, 6, 20 }; int k = 2; int n = sizeof(a) / sizeof(a[0]); sortExceptK(a, k, n); for (int i = 0; i < n; i++) cout << a[i] << \" \";}", "e": 26590, "s": 25885, "text": null }, { "code": "// Java program to sort all elements except// element at index k.import java.util.Arrays; class GFG { static int sortExceptK(int arr[], int k, int n) { // Move k-th element to end int temp = arr[k]; arr[k] = arr[n-1]; arr[n-1] = temp; // Sort all elements except last Arrays.sort(arr, 0, n-1); // Store last element (originally k-th) int last = arr[n-1]; // Move all elements from k-th to one // position ahead. for (int i = n-1; i > k; i--) arr[i] = arr[i-1]; // Restore k-th element arr[k] = last; return 0; } //Driver code public static void main (String[] args) { int a[] = {10, 4, 11, 7, 6, 20 }; int k = 2; int n = a.length; sortExceptK(a, k, n); for (int i = 0; i < n; i++) System.out.print(a[i] + \" \"); }} //This code is contributed by Anant Agarwal.", "e": 27578, "s": 26590, "text": null }, { "code": "# Python3 program to sort all elements except# element at index k.def sortExcept(arr, k, n): # Move k-th element to end arr[k], arr[-1] = arr[-1], arr[k] # Sort all elements except last arr = sorted(arr, key = lambda i: (i is arr[-1], i)) # Store last element (originally k-th) last = arr[-1] # Move all elements from k-th to one # position ahead. i = n - 1 while i > k: arr[i] = arr[i - 1] i -= 1 # Restore k-th element arr[k] = last return arr # Driver codeif __name__ == '__main__': a = [10, 4, 11, 7, 6, 20] k = 2 n = len(a) a = sortExcept(a, k, n) print(\" \".join(list(map(str, a)))) # This code is contributed by Shivam Singh.", "e": 28291, "s": 27578, "text": null }, { "code": "// C# program to sort all elements except// element at index k.using System; public class GFG { static int sortExceptK(int[] arr, int k, int n) { // Move k-th element to end int temp = arr[k]; arr[k] = arr[n - 1]; arr[n - 1] = temp; // Sort all elements except last Array.Sort(arr, 0, n - 1); // Store last element (originally k-th) int last = arr[n - 1]; // Move all elements from k-th to one // position ahead. for (int i = n - 1; i > k; i--) arr[i] = arr[i - 1]; // Restore k-th element arr[k] = last; return 0; } // Driver code public static void Main() { int[] a = { 10, 4, 11, 7, 6, 20 }; int k = 2; int n = a.Length; sortExceptK(a, k, n); for (int i = 0; i < n; i++) Console.Write(a[i] + \" \"); }} // This article is contributed by shiv_bhakt", "e": 29237, "s": 28291, "text": null }, { "code": "<?php// PHP program to sort all// elements except element// at index k.function sortExceptK(&$arr, $k, $n){ // Move k-th element to end $t = $arr[$k]; $arr[$k] = $arr[$n - 1]; $arr[$n - 1] = $t; // Sort all elements // except last $t = $arr[count($arr) - 1]; $arr = array_slice($arr, 0, -1); sort($arr); array_push($arr, $t); // Store last element // (originally k-th) $last = $arr[$n - 1]; // Move all elements from // k-th to one position ahead. for ($i = $n - 1; $i > $k; $i--) $arr[$i] = $arr[$i - 1]; // Restore k-th element $arr[$k] = $last;} // Driver code$a = array(10, 4, 11, 7, 6, 20 );$k = 2;$n = count($a);sortExceptK($a, $k, $n); for ($i = 0; $i < $n; $i++) echo ($a[$i].\" \"); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 30066, "s": 29237, "text": null }, { "code": "<script> // Javascript program to sort all elements except // element at index k. function sortExceptK(arr, k, n) { // Move k-th element to end let temp = arr[k]; arr[k] = arr[n-1]; arr[n-1] = temp; // Sort all elements except last arr.sort(function(a, b){ return a - b}); // Store last element (originally k-th) let last = arr[n-1]; // Move all elements from k-th to one // position ahead. for (let i = n-1; i > k; i--) arr[i] = arr[i-1]; // Restore k-th element arr[k] = last; // Move k-th element to end temp = arr[k]; arr[k] = arr[n-1]; arr[n-1] = temp; return 0; } let a = [10, 4, 11, 7, 6, 20 ]; let k = 2; let n = a.length; sortExceptK(a, k, n); for(let i = 0; i < n; i++) document.write(a[i] + \" \"); </script>", "e": 31036, "s": 30066, "text": null }, { "code": null, "e": 31052, "s": 31036, "text": "4 6 11 7 10 20 " }, { "code": null, "e": 31066, "s": 31054, "text": "manishshaw1" }, { "code": null, "e": 31080, "s": 31066, "text": "SHIVAMSINGH67" }, { "code": null, "e": 31095, "s": 31080, "text": "rameshtravel07" }, { "code": null, "e": 31102, "s": 31095, "text": "Arrays" }, { "code": null, "e": 31110, "s": 31102, "text": "Sorting" }, { "code": null, "e": 31117, "s": 31110, "text": "Arrays" }, { "code": null, "e": 31125, "s": 31117, "text": "Sorting" }, { "code": null, "e": 31223, "s": 31125, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31232, "s": 31223, "text": "Comments" }, { "code": null, "e": 31245, "s": 31232, "text": "Old Comments" }, { "code": null, "e": 31293, "s": 31245, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31337, "s": 31293, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 31360, "s": 31337, "text": "Introduction to Arrays" } ]
C# Program to Check Whether the Entered Number is an Armstrong Number or Not
For an Armstrong number, let us say a number has 3 digits, then the sum of cube of its digits is equal to the number itself. For example, 153 is equal to − 13 + 33 + 53 To check for it using C#, check the value and find its remainder. Here “val” is the number you want to check for Armstrong − for (int i = val; i > 0; i = i / 10) { rem = i % 10; sum = sum + rem*rem*rem; } Now compare the addition with the actual value. If it matches, that would mean the sum of cubes are the same and it is an Armstrong number − if (sum == val) { Console.Write("Armstrong Number"); }else { Console.Write("Not an Armstrong Number"); } Let us see a complete example to check whether a number is Armstrong or not. Live Demo using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo { class ApplicationNew { static void Main(string[] args) { int val = 153, sum = 0; int rem; // check for armstrong for (int i = val; i > 0; i = i / 10) { rem = i % 10; sum = sum + rem*rem*rem; } if (sum == val) { Console.Write("Armstrong Number"); } else { Console.Write("Not an Armstrong Number"); } Console.ReadLine(); } } } Armstrong Number
[ { "code": null, "e": 1187, "s": 1062, "text": "For an Armstrong number, let us say a number has 3 digits, then the sum of cube of its digits is equal to the number itself." }, { "code": null, "e": 1218, "s": 1187, "text": "For example, 153 is equal to −" }, { "code": null, "e": 1231, "s": 1218, "text": "13 + 33 + 53" }, { "code": null, "e": 1356, "s": 1231, "text": "To check for it using C#, check the value and find its remainder. Here “val” is the number you want to check for Armstrong −" }, { "code": null, "e": 1442, "s": 1356, "text": "for (int i = val; i > 0; i = i / 10) {\n rem = i % 10;\n sum = sum + rem*rem*rem;\n}" }, { "code": null, "e": 1583, "s": 1442, "text": "Now compare the addition with the actual value. If it matches, that would mean the sum of cubes are the same and it is an Armstrong number −" }, { "code": null, "e": 1694, "s": 1583, "text": "if (sum == val) {\n Console.Write(\"Armstrong Number\");\n}else {\n Console.Write(\"Not an Armstrong Number\");\n}" }, { "code": null, "e": 1771, "s": 1694, "text": "Let us see a complete example to check whether a number is Armstrong or not." }, { "code": null, "e": 1781, "s": 1771, "text": "Live Demo" }, { "code": null, "e": 2356, "s": 1781, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace Demo {\n class ApplicationNew {\n static void Main(string[] args) {\n int val = 153, sum = 0;\n int rem;\n // check for armstrong\n for (int i = val; i > 0; i = i / 10) {\n rem = i % 10;\n sum = sum + rem*rem*rem;\n }\n if (sum == val) {\n Console.Write(\"Armstrong Number\");\n } else {\n Console.Write(\"Not an Armstrong Number\");\n }\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2373, "s": 2356, "text": "Armstrong Number" } ]
CSS3 - Shadow
CSS3 supported to add shadow to text or elements.Shadow property has divided as follows − Text shadow Box Shadow CSS3 supported to add shadow effects to text. Following is the example to add shadow effects to text − <html> <head> <style> h1 { text-shadow: 2px 2px; } h2 { text-shadow: 2px 2px red; } h3 { text-shadow: 2px 2px 5px red; } h4 { color: white; text-shadow: 2px 2px 4px #000000; } h5 { text-shadow: 0 0 3px #FF0000; } h6 { text-shadow: 0 0 3px #FF0000, 0 0 5px #0000FF; } p { color: white; text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue; } </style> </head> <body> <h1>Tutorialspoint.com</h1> <h2>Tutorialspoint.com</h2> <h3>Tutorialspoint.com</h3> <h4>Tutorialspoint.com</h4> <h5>Tutorialspoint.com</h5> <h6>Tutorialspoint.com</h6> <p>Tutorialspoint.com</p> </body> </html> It will produce the following result − Tutorialspoint.com Used to add shadow effects to elements, Following is the example to add shadow effects to element. <html> <head> <style> div { width: 300px; height: 100px; padding: 15px; background-color: red; box-shadow: 10px 10px; } </style> </head> <body> <div>This is a div element with a box-shadow</div> </body> </html> It will produce the following result − 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2716, "s": 2626, "text": "CSS3 supported to add shadow to text or elements.Shadow property has divided as follows −" }, { "code": null, "e": 2728, "s": 2716, "text": "Text shadow" }, { "code": null, "e": 2739, "s": 2728, "text": "Box Shadow" }, { "code": null, "e": 2842, "s": 2739, "text": "CSS3 supported to add shadow effects to text. Following is the example to add shadow effects to text −" }, { "code": null, "e": 3729, "s": 2842, "text": "<html>\n <head>\n <style>\n h1 {\n text-shadow: 2px 2px;\n }\n h2 {\n text-shadow: 2px 2px red;\n }\n h3 {\n text-shadow: 2px 2px 5px red;\n }\n h4 {\n color: white;\n text-shadow: 2px 2px 4px #000000;\n }\n h5 {\n text-shadow: 0 0 3px #FF0000;\n }\n h6 {\n text-shadow: 0 0 3px #FF0000, 0 0 5px #0000FF;\n }\n p {\n color: white;\n text-shadow: 1px 1px 2px black, 0 0 25px blue, 0 0 5px darkblue;\n }\n </style>\n </head>\n\n <body>\n <h1>Tutorialspoint.com</h1>\n <h2>Tutorialspoint.com</h2>\n <h3>Tutorialspoint.com</h3>\n <h4>Tutorialspoint.com</h4>\n <h5>Tutorialspoint.com</h5>\n <h6>Tutorialspoint.com</h6>\n <p>Tutorialspoint.com</p>\n </body>\n</html>" }, { "code": null, "e": 3768, "s": 3729, "text": "It will produce the following result −" }, { "code": null, "e": 3787, "s": 3768, "text": "Tutorialspoint.com" }, { "code": null, "e": 3886, "s": 3787, "text": "Used to add shadow effects to elements, Following is the example to add shadow effects to element." }, { "code": null, "e": 4206, "s": 3886, "text": "<html>\n <head>\n <style>\n div {\n width: 300px;\n height: 100px;\n padding: 15px;\n background-color: red;\n box-shadow: 10px 10px;\n }\n </style>\n </head>\n\n <body>\n <div>This is a div element with a box-shadow</div>\n </body>\n</html>" }, { "code": null, "e": 4245, "s": 4206, "text": "It will produce the following result −" }, { "code": null, "e": 4280, "s": 4245, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4294, "s": 4280, "text": " Anadi Sharma" }, { "code": null, "e": 4329, "s": 4294, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4346, "s": 4329, "text": " Frahaan Hussain" }, { "code": null, "e": 4381, "s": 4346, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4412, "s": 4381, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4447, "s": 4412, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4478, "s": 4447, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4513, "s": 4478, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4544, "s": 4513, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4577, "s": 4544, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 4608, "s": 4577, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4615, "s": 4608, "text": " Print" }, { "code": null, "e": 4626, "s": 4615, "text": " Add Notes" } ]
Spring Boot CLI - Environment Setup
Spring is a Java-based framework; hence, we need to set up JDK first. Following are the steps needed to setup Spring Boot CLI along with JDK installation. You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and have installed the JDK in C:\jdk-11.0.11, you would have to put the following line in your C:\autoexec.bat file. set PATH=C:\jdk-11.0.11;%PATH% set JAVA_HOME=C:\jdk-11.0.11 Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file. setenv PATH /usr/local/jdk-11.0.11/bin:$PATH setenv JAVA_HOME /usr/local/jdk-11.0.11 You can download the latest version of Spring Boot CLI API as ZIP archive from https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/. Once you download the installation, unpack the zip distribution into a convenient location. For example, in E:\Test\spring-boot-cli-2.6.3 on Windows, or /usr/local/spring-boot-cli-2.6.3 on Linux/Unix. Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application. Or set the path in command prompt temporarily to run the spring boot application as shown below − E:/Test/> set path=E:\Test\spring-boot-cli-2.6.3-bin\spring-2.6.3\bin;%PATH% Run the following command on command prompt to verify the installation − E:/Test/> spring --version It should print the following output confirming the successful installation − Spring CLI v2.6.3 Print Add Notes Bookmark this page
[ { "code": null, "e": 2164, "s": 2009, "text": "Spring is a Java-based framework; hence, we need to set up JDK first. Following are the steps needed to setup Spring Boot CLI along with JDK installation." }, { "code": null, "e": 2560, "s": 2164, "text": "You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively." }, { "code": null, "e": 2704, "s": 2560, "text": "If you are running Windows and have installed the JDK in C:\\jdk-11.0.11, you would have to put the following line in your C:\\autoexec.bat file." }, { "code": null, "e": 2767, "s": 2704, "text": "set PATH=C:\\jdk-11.0.11;%PATH% \nset JAVA_HOME=C:\\jdk-11.0.11 \n" }, { "code": null, "e": 2974, "s": 2767, "text": "Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button." }, { "code": null, "e": 3139, "s": 2974, "text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file." }, { "code": null, "e": 3226, "s": 3139, "text": "setenv PATH /usr/local/jdk-11.0.11/bin:$PATH \nsetenv JAVA_HOME /usr/local/jdk-11.0.11\n" }, { "code": null, "e": 3580, "s": 3226, "text": "You can download the latest version of Spring Boot CLI API as ZIP archive from https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/. Once you download the installation, unpack the zip distribution into a convenient location. For example, in E:\\Test\\spring-boot-cli-2.6.3 on Windows, or /usr/local/spring-boot-cli-2.6.3 on Linux/Unix." }, { "code": null, "e": 3715, "s": 3580, "text": "Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application." }, { "code": null, "e": 3813, "s": 3715, "text": "Or set the path in command prompt temporarily to run the spring boot application as shown below −" }, { "code": null, "e": 3891, "s": 3813, "text": "E:/Test/> set path=E:\\Test\\spring-boot-cli-2.6.3-bin\\spring-2.6.3\\bin;%PATH%\n" }, { "code": null, "e": 3964, "s": 3891, "text": "Run the following command on command prompt to verify the installation −" }, { "code": null, "e": 3992, "s": 3964, "text": "E:/Test/> spring --version\n" }, { "code": null, "e": 4070, "s": 3992, "text": "It should print the following output confirming the successful installation −" }, { "code": null, "e": 4089, "s": 4070, "text": "Spring CLI v2.6.3\n" }, { "code": null, "e": 4096, "s": 4089, "text": " Print" }, { "code": null, "e": 4107, "s": 4096, "text": " Add Notes" } ]
fsck - Unix, Linux Command
fsck - check and repair a Linux file system fsck [-sAVRTMNP] [-C [fd]] [-t fstype] [filesys...] [--] [fs-specific-options] Example-1: To Filesystem Check on a Disk Partition: # fsck /dev/sda6 output: fsck from util-linux 2.20.1 e2fsck 1.42.9 (4-Feb-2014) /dev/sda6: clean, 95/2240224 files, 3793506/4476416 blocks fsck from util-linux 2.20.1 e2fsck 1.42.9 (4-Feb-2014) /dev/sda6: clean, 95/2240224 files, 3793506/4476416 blocks dosfsck 3.0.12, 29 Oct 2011, FAT32, LFN /dev/sda7: 8 files, 50/1463400 clusters output: fsck from util-linux 2.20.1 e2fsck 1.42.9 (4-Feb-2014)/dev/sda6: clean, 11/2240224 files, 70327/4476416 blocks Example-4: Don’t execute Fsck on Mounted Filesystem using Option -M # mount | grep "/dev/sd*" /dev/sda5 on / type ext4 (rw,errors=remount-ro) /dev/sda6 on /mydata type ext2 (rw) /dev/sda7 on /backup type vfat (rw) # fsck -M /dev/sda7 (note: fsck will simply exit with the exit code 0)output: # echo $? 0 Example-5: Skip the Display Title using Option -T # fsck -TAR output: e2fsck 1.42.9 (4-Feb-2014)/dev/sda6: clean, 11/2240224 files, 70327/4476416 blocks Force a Filesystem Check Even if it’s Clean using Option -f # fsck /dev/sda6 fsck from util-linux 2.20.1 e2fsck 1.42.9 (4-Feb-2014) /dev/sda6: clean, 95/2240224 files, 3793503/4476416 blocks # fsck /dev/sda6 -foutput: fsck from util-linux 2.20.1 e2fsck 1.42.9 (4-Feb-2014) Pass 1: Checking inodes, blocks, and sizes Pass 2: Checking directory structure Pass 3: Checking directory connectivity Pass 4: Checking reference counts Pass 5: Checking group summary information /dev/sda6: 95/2240224 files (7.4% non-contiguous), 3793503/4476416 blocks Example-7: Attempt to Fix Detected Problems Automatically using Option -y # fsck -y /dev/sda6 output:fsck from util-linux 2.20.1 e2fsck 1.42.9 (4-Feb-2014) /dev/sda6 contains a file system with errors, check forced. Pass 1: Checking inodes, blocks, and sizes Inode 2060353 is a unknown file type with mode 0137642 but it looks like it is really a directory. Fix? yes Pass 2: Checking directory structure Entry 'test' in / (2) has deleted/unused inode 49059. Clear? yes Pass 3: Checking directory connectivity Pass 4: Checking reference counts Pass 5: Checking group summary information /dev/sda6: ***** FILE SYSTEM WAS MODIFIED ***** /dev/sda6: 96/2240224 files (7.3% non-contiguous), 3793508/4476416 blocks output: fsck from util-linux 2.20.1 e2fsck 1.42.9 (4-Feb-2014) /dev/sda6 contains a file system with errors, check forced. Pass 1: Checking inodes, blocks, and sizes Inode 2060353 is a unknown file type with mode 0173 but it looks like it is really a directory. Fix? no Inode 2060353, i_blocks is 8, should be 0. Fix? no Pass 2: Checking directory structure Inode 2060353 (/Movies) has invalid mode (0173). Clear? no Inode 49057 (/fwh) has invalid mode (013). Clear? no Entry 'fwh' in / (2) has an incorrect filetype (was 1, should be 0). Fix? no Pass 3: Checking directory connectivity Unconnected directory inode 65409 (???) Connect to /lost+found? no '..' in ... (65409) is ??? (2060353), should be (0). Fix? no Unconnected directory inode 2076736 (???) Connect to /lost+found? no Pass 4: Checking reference counts Inode 2 ref count is 4, should be 3. Fix? no Inode 65409 ref count is 3, should be 2. Fix? no Inode 2060353 ref count is 16, should be 15. Fix? no Unattached inode 2060354 Connect to /lost+found? no Pass 5: Checking group summary information Block bitmap differences: -(164356--164357) -4149248 Fix? no Directories count wrong for group #126 (1, counted=0). Fix? no /dev/sda6: ********** WARNING: Filesystem still has errors ********** /dev/sda6: 96/2240224 files (7.3% non-contiguous), 3793508/4476416 blocks 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10621, "s": 10577, "text": "fsck - check and repair a Linux file system" }, { "code": null, "e": 10700, "s": 10621, "text": "fsck [-sAVRTMNP] [-C [fd]] [-t fstype] [filesys...] [--] [fs-specific-options]" }, { "code": null, "e": 10711, "s": 10700, "text": "Example-1:" }, { "code": null, "e": 10752, "s": 10711, "text": "To Filesystem Check on a Disk Partition:" }, { "code": null, "e": 10769, "s": 10752, "text": "# fsck /dev/sda6" }, { "code": null, "e": 10777, "s": 10769, "text": "output:" }, { "code": null, "e": 10891, "s": 10777, "text": "fsck from util-linux 2.20.1\ne2fsck 1.42.9 (4-Feb-2014)\n/dev/sda6: clean, 95/2240224 files, 3793506/4476416 blocks" }, { "code": null, "e": 11085, "s": 10891, "text": "fsck from util-linux 2.20.1\ne2fsck 1.42.9 (4-Feb-2014)\n/dev/sda6: clean, 95/2240224 files, 3793506/4476416 blocks\ndosfsck 3.0.12, 29 Oct 2011, FAT32, LFN\n/dev/sda7: 8 files, 50/1463400 clusters" }, { "code": null, "e": 11093, "s": 11085, "text": "output:" }, { "code": null, "e": 11204, "s": 11093, "text": "fsck from util-linux 2.20.1\ne2fsck 1.42.9 (4-Feb-2014)/dev/sda6: clean, 11/2240224 files, 70327/4476416 blocks" }, { "code": null, "e": 11215, "s": 11204, "text": "Example-4:" }, { "code": null, "e": 11272, "s": 11215, "text": "Don’t execute Fsck on Mounted Filesystem using Option -M" }, { "code": null, "e": 11419, "s": 11272, "text": "# mount | grep \"/dev/sd*\"\n/dev/sda5 on / type ext4 (rw,errors=remount-ro)\n/dev/sda6 on /mydata type ext2 (rw)\n/dev/sda7 on /backup type vfat (rw)\n" }, { "code": null, "e": 11510, "s": 11419, "text": "# fsck -M /dev/sda7 (note: fsck will simply exit with the exit code 0)output:\n# echo $?\n0" }, { "code": null, "e": 11521, "s": 11510, "text": "Example-5:" }, { "code": null, "e": 11560, "s": 11521, "text": "Skip the Display Title using Option -T" }, { "code": null, "e": 11572, "s": 11560, "text": "# fsck -TAR" }, { "code": null, "e": 11580, "s": 11572, "text": "output:" }, { "code": null, "e": 11663, "s": 11580, "text": "e2fsck 1.42.9 (4-Feb-2014)/dev/sda6: clean, 11/2240224 files, 70327/4476416 blocks" }, { "code": null, "e": 11723, "s": 11663, "text": "Force a Filesystem Check Even if it’s Clean using Option -f" }, { "code": null, "e": 11881, "s": 11723, "text": "# fsck /dev/sda6\nfsck from util-linux 2.20.1\ne2fsck 1.42.9 (4-Feb-2014) /dev/sda6: clean, 95/2240224 files, 3793503/4476416 blocks # fsck /dev/sda6 -foutput:" }, { "code": null, "e": 12207, "s": 11881, "text": "fsck from util-linux 2.20.1\ne2fsck 1.42.9 (4-Feb-2014)\nPass 1: Checking inodes, blocks, and sizes\nPass 2: Checking directory structure\nPass 3: Checking directory connectivity\nPass 4: Checking reference counts\nPass 5: Checking group summary information\n/dev/sda6: 95/2240224 files (7.4% non-contiguous), 3793503/4476416 blocks" }, { "code": null, "e": 12218, "s": 12207, "text": "Example-7:" }, { "code": null, "e": 12281, "s": 12218, "text": "Attempt to Fix Detected Problems Automatically using Option -y" }, { "code": null, "e": 12301, "s": 12281, "text": "# fsck -y /dev/sda6" }, { "code": null, "e": 12920, "s": 12301, "text": "output:fsck from util-linux 2.20.1\ne2fsck 1.42.9 (4-Feb-2014)\n/dev/sda6 contains a file system with errors, check forced.\nPass 1: Checking inodes, blocks, and sizes\nInode 2060353 is a unknown file type with mode 0137642 but it looks \nlike it is really a directory.\nFix? yes\n\nPass 2: Checking directory structure\nEntry 'test' in / (2) has deleted/unused inode 49059. Clear? yes\n\nPass 3: Checking directory connectivity\nPass 4: Checking reference counts\nPass 5: Checking group summary information\n\n/dev/sda6: ***** FILE SYSTEM WAS MODIFIED *****\n/dev/sda6: 96/2240224 files (7.3% non-contiguous), 3793508/4476416 blocks" }, { "code": null, "e": 12928, "s": 12920, "text": "output:" }, { "code": null, "e": 14269, "s": 12928, "text": "fsck from util-linux 2.20.1\ne2fsck 1.42.9 (4-Feb-2014)\n/dev/sda6 contains a file system with errors, check forced.\nPass 1: Checking inodes, blocks, and sizes\nInode 2060353 is a unknown file type with mode 0173 but it looks \nlike it is really a directory.\nFix? no\nInode 2060353, i_blocks is 8, should be 0. Fix? no\n\nPass 2: Checking directory structure\nInode 2060353 (/Movies) has invalid mode (0173).\nClear? no\n\nInode 49057 (/fwh) has invalid mode (013).\nClear? no\n\nEntry 'fwh' in / (2) has an incorrect filetype (was 1, should be 0).\nFix? no\n\nPass 3: Checking directory connectivity\nUnconnected directory inode 65409 (???)\nConnect to /lost+found? no\n\n'..' in ... (65409) is ??? (2060353), should be (0).\nFix? no\n\nUnconnected directory inode 2076736 (???)\nConnect to /lost+found? no\n\nPass 4: Checking reference counts\nInode 2 ref count is 4, should be 3. Fix? no\n\nInode 65409 ref count is 3, should be 2. Fix? no\n\nInode 2060353 ref count is 16, should be 15. Fix? no\n\nUnattached inode 2060354\nConnect to /lost+found? no\n\nPass 5: Checking group summary information\nBlock bitmap differences: -(164356--164357) -4149248\nFix? no\n\nDirectories count wrong for group #126 (1, counted=0).\nFix? no\n\n/dev/sda6: ********** WARNING: Filesystem still has errors **********\n\n/dev/sda6: 96/2240224 files (7.3% non-contiguous), 3793508/4476416 blocks" }, { "code": null, "e": 14304, "s": 14269, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 14332, "s": 14304, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 14366, "s": 14332, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 14383, "s": 14366, "text": " Frahaan Hussain" }, { "code": null, "e": 14416, "s": 14383, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 14427, "s": 14416, "text": " Pradeep D" }, { "code": null, "e": 14462, "s": 14427, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 14478, "s": 14462, "text": " Musab Zayadneh" }, { "code": null, "e": 14511, "s": 14478, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 14523, "s": 14511, "text": " GUHARAJANM" }, { "code": null, "e": 14555, "s": 14523, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 14563, "s": 14555, "text": " Uplatz" }, { "code": null, "e": 14570, "s": 14563, "text": " Print" }, { "code": null, "e": 14581, "s": 14570, "text": " Add Notes" } ]
5 Cool Alternatives To Django and Flask For Deploying Endpoints And FullStack | by Emmett Boudreau | Towards Data Science
If you’ve ever deployed an endpoint or created a website with Python, then it’s likely that you’ve heard of Flask and Django. Flask and Django are the industry standard in Python when it comes to doing nearly anything with the HTTP protocol in Python. Flask is typically used for more light-weight applications that don’t need a lot of features, whereas Django fills the void on the web-app spectrum. Both are great tools, but in some niche circumstances, it can be better to instead use a similar web-framework while not retaining the same features that Flask and Django come with. Bottle is an incredibly light micro-framework for WSGI in Python. It is published under the MIT license and is entirely free for modification and distribution. A big advantage to using Bottle is that it is stored inside of a single, small Python module with no dependencies. This makes things incredibly simple and seamless when you are ready to deploy your API. One thing I really love about Bottle is how easy to use and light it is, with no added fluff like you might get with Flask and even more so Django. Sometimes minimalism is key, and Django and Flask can sometimes be a little overwhelming with all of the dynamic pieces of a small API coming into play. Another significant advantage of adding to the lightweight aspect is Bottle’s packed-in server. Bottle comes with its own web-server, meaning there is no need to configure Gunicorn3, but that isn’t to say you can’t use Gunicorn3. Bottle has support for Paste, fapws3, gae, or any other WSGI-compatible server. In terms of syntax, Bottle blurs the lines of similarity between itself and Flask with very few syntactical differences. Hello world, for example: from bottle import route, run, template@route('/hello/<name>')def index(name): return template('<b>Hello {{name}}</b>!', name=name)run(host='localhost', port=8080) Another cool web framework I like to use is GNU TurboGears. To confess, I am fond of TurboGears partially because it is published under the GNU GPL license version 2, but that isn’t to say that TurboGears isn’t a great framework. Oddly enough, TurboGears is actually built on top of several other frameworks including Django and Rails. That being said, TurboGears is a marginal step away from something like Bottle and certainly has its place being used more like Django. TurboGears was designed to be a full-stack framework, and should certainly be used that way. A great thing about TurboGears is its extensibility, the framework can be extended using all sorts of simple WSGI plugins. Additionally, it comes with support for horizontal data partitioning, or sharding. Syntactically, TurboGears is likely an entirely different beast than what any Python programmer is used to. The code tends to focus more on the object oriented paradigm, which is a completely different approach to most other frameworks. For example, here’s hello world: from tg import expose, TGControllerclass RootController(TGController): @expose() def index(self): return 'Hello World'from tg import MinimalApplicationConfiguratorconfig = MinimalApplicationConfigurator()config.update_blueprint({ 'root_controller': RootController()})from wsgiref.simple_server import make_serverprint("Serving on port 8080...")httpd = make_server('', 8080, application)httpd.serve_forever() Web2py is the one framework on this list I imagine we are all familiar with. Web2py is another module that is primarily focused on the full-stack side of things. Similar to bottle, however, Web2py has no dependencies outside of the Python standard library. What’s impressive to me about Web2py is that it is able to accomplish similar goals to frameworks like Django and TurboGears while simultaneously being much more lightweight and easy to use. Web2py is published under the GNU GPL version 3 license, which means you can use it for just about anything without having to worry about licensing. Web2py’s selling point is most likely its fully-featured IDE, which allows you to modify your website from any web-browser after it is deployed. With that in mind, it only makes sense that the primary advantage to using this software is how quickly you can create with it. Compared to Django and similar frameworks, Web2py is certainly a lot easier and quicker, but in my experience can be a bit lacking and old-fashioned when compared with more modern options. CherryPy is another framework that I really enjoy and is likely my favorite on this list. (It’s between CherryPy and Bottle) CherryPy approaches web development in a way that is more similar to TurboGears, but approaches methodology in a way that is more similar to Bottle. CherryPy is incredibly light and is considered a minimalist web framework. Despite its light weight, however, CherryPy still manages to cram in a lot of incredibly useful features including authentication, sessions, and caching to name a few. CherryPy also features an interesting and unique plugin system with extremely manipulable... Well... Everything! CherryPy is licensed under the FreeBSD license, BSD licenses are a low restriction type of license for open source software that does not put requirements on redistribution, meaning similarly to most of the other frameworks it is free and open to use. In its similarity to TurboGears, CherryPy takes a very object-oriented approach to web-development. Here is hello world: import cherrypyclass HelloWorld(object): @cherrypy.expose def index(self): return "Hello World!"cherrypy.quickstart(HelloWorld()) Quixote is another framework that is well intertwined with the object-oriented paradigm. The framework focuses primarily on speed and flexibility, but can certainly be a difficult one to get into. Separation of presentation logic and “back-end” logic is not enforced by Quixote. This can be seen as both an advantage and a disadvantage. I would say that this framework is highly manipulable but definitely a lot harder to use compared to the other options available to Python programmers. Another issue you’re going to run into with this framework is the severe, crippling, lack of documentation. Given these shortcomings, I would say that this framework is only recommended for an application that needs to be built from scratch. Though it might not be great for a lot of applications because of how long it will take to build, it certainly has its place and can get the job done in a way that other frameworks can’t. Though Flask and Django are certainly great tools, I think it’s great to take a look at the competition because occasionally having the flexibility can certainly come in handy. The things I look for in a framework might not necessarily be the same things that other people look for, and could also depend entirely on what I want to create as well. My favorite on this list is without a doubt is CherryPy, because I often look for a very lightweight option because of how I typically use Pythonic web frameworks. Most of my web deployments are simple APIs that don’t need a lot of maintenance or pieces, but at the same time need to be secure and stable enough to deliver data as needed, and CherryPy is perfect for that. I’d be curious to know what other engineers look for in their frameworks, and which ones they would choose. Web frameworks might not be the most complex beasts on Earth, but having a great one can certainly make your day a lot simpler!
[ { "code": null, "e": 755, "s": 172, "text": "If you’ve ever deployed an endpoint or created a website with Python, then it’s likely that you’ve heard of Flask and Django. Flask and Django are the industry standard in Python when it comes to doing nearly anything with the HTTP protocol in Python. Flask is typically used for more light-weight applications that don’t need a lot of features, whereas Django fills the void on the web-app spectrum. Both are great tools, but in some niche circumstances, it can be better to instead use a similar web-framework while not retaining the same features that Flask and Django come with." }, { "code": null, "e": 1118, "s": 755, "text": "Bottle is an incredibly light micro-framework for WSGI in Python. It is published under the MIT license and is entirely free for modification and distribution. A big advantage to using Bottle is that it is stored inside of a single, small Python module with no dependencies. This makes things incredibly simple and seamless when you are ready to deploy your API." }, { "code": null, "e": 1729, "s": 1118, "text": "One thing I really love about Bottle is how easy to use and light it is, with no added fluff like you might get with Flask and even more so Django. Sometimes minimalism is key, and Django and Flask can sometimes be a little overwhelming with all of the dynamic pieces of a small API coming into play. Another significant advantage of adding to the lightweight aspect is Bottle’s packed-in server. Bottle comes with its own web-server, meaning there is no need to configure Gunicorn3, but that isn’t to say you can’t use Gunicorn3. Bottle has support for Paste, fapws3, gae, or any other WSGI-compatible server." }, { "code": null, "e": 1876, "s": 1729, "text": "In terms of syntax, Bottle blurs the lines of similarity between itself and Flask with very few syntactical differences. Hello world, for example:" }, { "code": null, "e": 2043, "s": 1876, "text": "from bottle import route, run, template@route('/hello/<name>')def index(name): return template('<b>Hello {{name}}</b>!', name=name)run(host='localhost', port=8080)" }, { "code": null, "e": 2515, "s": 2043, "text": "Another cool web framework I like to use is GNU TurboGears. To confess, I am fond of TurboGears partially because it is published under the GNU GPL license version 2, but that isn’t to say that TurboGears isn’t a great framework. Oddly enough, TurboGears is actually built on top of several other frameworks including Django and Rails. That being said, TurboGears is a marginal step away from something like Bottle and certainly has its place being used more like Django." }, { "code": null, "e": 3084, "s": 2515, "text": "TurboGears was designed to be a full-stack framework, and should certainly be used that way. A great thing about TurboGears is its extensibility, the framework can be extended using all sorts of simple WSGI plugins. Additionally, it comes with support for horizontal data partitioning, or sharding. Syntactically, TurboGears is likely an entirely different beast than what any Python programmer is used to. The code tends to focus more on the object oriented paradigm, which is a completely different approach to most other frameworks. For example, here’s hello world:" }, { "code": null, "e": 3508, "s": 3084, "text": "from tg import expose, TGControllerclass RootController(TGController): @expose() def index(self): return 'Hello World'from tg import MinimalApplicationConfiguratorconfig = MinimalApplicationConfigurator()config.update_blueprint({ 'root_controller': RootController()})from wsgiref.simple_server import make_serverprint(\"Serving on port 8080...\")httpd = make_server('', 8080, application)httpd.serve_forever()" }, { "code": null, "e": 4105, "s": 3508, "text": "Web2py is the one framework on this list I imagine we are all familiar with. Web2py is another module that is primarily focused on the full-stack side of things. Similar to bottle, however, Web2py has no dependencies outside of the Python standard library. What’s impressive to me about Web2py is that it is able to accomplish similar goals to frameworks like Django and TurboGears while simultaneously being much more lightweight and easy to use. Web2py is published under the GNU GPL version 3 license, which means you can use it for just about anything without having to worry about licensing." }, { "code": null, "e": 4567, "s": 4105, "text": "Web2py’s selling point is most likely its fully-featured IDE, which allows you to modify your website from any web-browser after it is deployed. With that in mind, it only makes sense that the primary advantage to using this software is how quickly you can create with it. Compared to Django and similar frameworks, Web2py is certainly a lot easier and quicker, but in my experience can be a bit lacking and old-fashioned when compared with more modern options." }, { "code": null, "e": 4657, "s": 4567, "text": "CherryPy is another framework that I really enjoy and is likely my favorite on this list." }, { "code": null, "e": 4692, "s": 4657, "text": "(It’s between CherryPy and Bottle)" }, { "code": null, "e": 5185, "s": 4692, "text": "CherryPy approaches web development in a way that is more similar to TurboGears, but approaches methodology in a way that is more similar to Bottle. CherryPy is incredibly light and is considered a minimalist web framework. Despite its light weight, however, CherryPy still manages to cram in a lot of incredibly useful features including authentication, sessions, and caching to name a few. CherryPy also features an interesting and unique plugin system with extremely manipulable... Well..." }, { "code": null, "e": 5197, "s": 5185, "text": "Everything!" }, { "code": null, "e": 5570, "s": 5197, "text": "CherryPy is licensed under the FreeBSD license, BSD licenses are a low restriction type of license for open source software that does not put requirements on redistribution, meaning similarly to most of the other frameworks it is free and open to use. In its similarity to TurboGears, CherryPy takes a very object-oriented approach to web-development. Here is hello world:" }, { "code": null, "e": 5713, "s": 5570, "text": "import cherrypyclass HelloWorld(object): @cherrypy.expose def index(self): return \"Hello World!\"cherrypy.quickstart(HelloWorld())" }, { "code": null, "e": 6202, "s": 5713, "text": "Quixote is another framework that is well intertwined with the object-oriented paradigm. The framework focuses primarily on speed and flexibility, but can certainly be a difficult one to get into. Separation of presentation logic and “back-end” logic is not enforced by Quixote. This can be seen as both an advantage and a disadvantage. I would say that this framework is highly manipulable but definitely a lot harder to use compared to the other options available to Python programmers." }, { "code": null, "e": 6287, "s": 6202, "text": "Another issue you’re going to run into with this framework is the severe, crippling," }, { "code": null, "e": 6310, "s": 6287, "text": "lack of documentation." }, { "code": null, "e": 6632, "s": 6310, "text": "Given these shortcomings, I would say that this framework is only recommended for an application that needs to be built from scratch. Though it might not be great for a lot of applications because of how long it will take to build, it certainly has its place and can get the job done in a way that other frameworks can’t." } ]
Python | Pandas Series.drop() - GeeksforGeeks
15 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.drop() function return Series with specified index labels removed. It remove elements of a Series based on specifying the index labels. Syntax: Series.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’) Parameter :labels : Index labels to drop.axis : Redundant for application on Series.index, columns : Redundant for application on Series, but index can be used instead of labels.level : For MultiIndex, level for which the labels will be removed.inplace : If True, do operation inplace and return None.errors : If ‘ignore’, suppress error and only existing labels are dropped. Returns : dropped : pandas.Series Example #1: Use Series.drop() function to drop the values corresponding to the passed index labels in the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([80, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.drop() function to drop the values corresponding to the passed index labels in the given series object. # drop the passed labelsresult = sr.drop(labels = ['Sprite', 'Dew']) # Print the resultprint(result) Output : As we can see in the output, the Series.drop() function has successfully dropped the entries corresponding to the passed index labels. Example #2 : Use Series.drop() function to drop the values corresponding to the passed index labels in the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 11, 8, 18, 65, 18, 32, 10, 5, 32, 32]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr) Output : Now we will use Series.drop() function to drop the values corresponding to the passed index labels in the given series object. # drop the passed labelsresult = sr.drop(labels = [pd.Timestamp('2010-12-31'), pd.Timestamp('2011-04-30'), pd.Timestamp('2011-08-31')]) # Print the resultprint(result) Output : As we can see in the output, the Series.drop() function has successfully dropped the entries corresponding to the passed index labels. Python pandas-series Python pandas-series-methods Python-pandas 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? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n15 Feb, 2019" }, { "code": null, "e": 25794, "s": 25537, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 25944, "s": 25794, "text": "Pandas Series.drop() function return Series with specified index labels removed. It remove elements of a Series based on specifying the index labels." }, { "code": null, "e": 26054, "s": 25944, "text": "Syntax: Series.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’)" }, { "code": null, "e": 26430, "s": 26054, "text": "Parameter :labels : Index labels to drop.axis : Redundant for application on Series.index, columns : Redundant for application on Series, but index can be used instead of labels.level : For MultiIndex, level for which the labels will be removed.inplace : If True, do operation inplace and return None.errors : If ‘ignore’, suppress error and only existing labels are dropped." }, { "code": null, "e": 26464, "s": 26430, "text": "Returns : dropped : pandas.Series" }, { "code": null, "e": 26591, "s": 26464, "text": "Example #1: Use Series.drop() function to drop the values corresponding to the passed index labels in the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([80, 25, 3, 25, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 26847, "s": 26591, "text": null }, { "code": null, "e": 26856, "s": 26847, "text": "Output :" }, { "code": null, "e": 26983, "s": 26856, "text": "Now we will use Series.drop() function to drop the values corresponding to the passed index labels in the given series object." }, { "code": "# drop the passed labelsresult = sr.drop(labels = ['Sprite', 'Dew']) # Print the resultprint(result)", "e": 27086, "s": 26983, "text": null }, { "code": null, "e": 27095, "s": 27086, "text": "Output :" }, { "code": null, "e": 27358, "s": 27095, "text": "As we can see in the output, the Series.drop() function has successfully dropped the entries corresponding to the passed index labels. Example #2 : Use Series.drop() function to drop the values corresponding to the passed index labels in the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 11, 8, 18, 65, 18, 32, 10, 5, 32, 32]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 27627, "s": 27358, "text": null }, { "code": null, "e": 27636, "s": 27627, "text": "Output :" }, { "code": null, "e": 27763, "s": 27636, "text": "Now we will use Series.drop() function to drop the values corresponding to the passed index labels in the given series object." }, { "code": "# drop the passed labelsresult = sr.drop(labels = [pd.Timestamp('2010-12-31'), pd.Timestamp('2011-04-30'), pd.Timestamp('2011-08-31')]) # Print the resultprint(result)", "e": 27958, "s": 27763, "text": null }, { "code": null, "e": 27967, "s": 27958, "text": "Output :" }, { "code": null, "e": 28102, "s": 27967, "text": "As we can see in the output, the Series.drop() function has successfully dropped the entries corresponding to the passed index labels." }, { "code": null, "e": 28123, "s": 28102, "text": "Python pandas-series" }, { "code": null, "e": 28152, "s": 28123, "text": "Python pandas-series-methods" }, { "code": null, "e": 28166, "s": 28152, "text": "Python-pandas" }, { "code": null, "e": 28173, "s": 28166, "text": "Python" }, { "code": null, "e": 28271, "s": 28173, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28303, "s": 28271, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28345, "s": 28303, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28387, "s": 28345, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28414, "s": 28387, "text": "Python Classes and Objects" }, { "code": null, "e": 28470, "s": 28414, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28492, "s": 28470, "text": "Defaultdict in Python" }, { "code": null, "e": 28531, "s": 28492, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28562, "s": 28531, "text": "Python | os.path.join() method" }, { "code": null, "e": 28591, "s": 28562, "text": "Create a directory in Python" } ]
Difference between std::set::lower_bound and std::lower_bound in C++ - GeeksforGeeks
07 May, 2020 Prerequisite: Random-access Iterators in C++, Bidirectional Iterators in C++. std::lower_bound in C++:The lower_bound() method in C++ is used to return an iterator pointing to the first element in the range [first, last) which has a value not less than the given value. This means that the function returns the index of the next smallest number just greater than that number. std::set::lower_bound in C++:The set::lower_bound() is a built-in function in C++ STL which returns an iterator pointing to the element in the container which is equivalent to K passed in the parameter. In case K is not present in the set container, the function returns an iterator pointing to the immediate next element which is just greater than K. If the key passed in the parameter exceeds the maximum value in the container, then the iterator returned points to the last element in the set container. Below is the difference between std::lower_bound and std::set::lower_bound: Below is the program with CPU execution time which will illustrate the running time of both functions. Program to illustrate of std::lower_bound(): // C++ program to illustrate// std::set::lower_bound#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // Function whose time is to// be measuredvoid fun(){ // Initialise the set set<int> s; // Insert element in the set for (int i = 0; i < 10; i++) { s.insert(i); } // Use lower_bound() function // to find 5 set<int>::iterator it; it = lower_bound(s.begin(), s.end(), 5);} // Driver Codeint main(){ // Use function gettimeofday() // can get the time struct timeval start, end; // Start timer gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); // Function Call fun(); // Stop timer gettimeofday(&end, NULL); // Calculating total time taken // by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << "Time taken by program is : " << fixed << time_taken << setprecision(6); cout << " sec" << endl; return 0;} Time taken by program is : 0.000046 sec Program to illustrate of std::set::lower_bound(): // C++ program to illustrate// std::lower_bound#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // Function whose time is to// be measuredvoid fun(){ // Initialise the set set<int> s; // Insert element in the set for (int i = 0; i < 10; i++) { s.insert(i); } // Use set::lower_bound() function // to find 5 set<int>::iterator it; it = s.lower_bound(5);} // Driver Codeint main(){ // Use function gettimeofday() // can get the time struct timeval start, end; // Start timer gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // Stop timer gettimeofday(&end, NULL); // Calculating total time taken // by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << "Time taken by program is : " << fixed << time_taken << setprecision(6); cout << " sec" << endl; return 0;} Time taken by program is : 0.000039 sec STL C++ Programming Language STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Modulo Operator (%) in C/C++ with Examples JLabel | Java Swing Arrow operator -> in C/C++ with Examples Top 10 Programming Languages to Learn in 2022 Difference between Compile Time Errors and Runtime Errors
[ { "code": null, "e": 25369, "s": 25341, "text": "\n07 May, 2020" }, { "code": null, "e": 25447, "s": 25369, "text": "Prerequisite: Random-access Iterators in C++, Bidirectional Iterators in C++." }, { "code": null, "e": 25745, "s": 25447, "text": "std::lower_bound in C++:The lower_bound() method in C++ is used to return an iterator pointing to the first element in the range [first, last) which has a value not less than the given value. This means that the function returns the index of the next smallest number just greater than that number." }, { "code": null, "e": 26252, "s": 25745, "text": "std::set::lower_bound in C++:The set::lower_bound() is a built-in function in C++ STL which returns an iterator pointing to the element in the container which is equivalent to K passed in the parameter. In case K is not present in the set container, the function returns an iterator pointing to the immediate next element which is just greater than K. If the key passed in the parameter exceeds the maximum value in the container, then the iterator returned points to the last element in the set container." }, { "code": null, "e": 26328, "s": 26252, "text": "Below is the difference between std::lower_bound and std::set::lower_bound:" }, { "code": null, "e": 26431, "s": 26328, "text": "Below is the program with CPU execution time which will illustrate the running time of both functions." }, { "code": null, "e": 26476, "s": 26431, "text": "Program to illustrate of std::lower_bound():" }, { "code": "// C++ program to illustrate// std::set::lower_bound#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // Function whose time is to// be measuredvoid fun(){ // Initialise the set set<int> s; // Insert element in the set for (int i = 0; i < 10; i++) { s.insert(i); } // Use lower_bound() function // to find 5 set<int>::iterator it; it = lower_bound(s.begin(), s.end(), 5);} // Driver Codeint main(){ // Use function gettimeofday() // can get the time struct timeval start, end; // Start timer gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); // Function Call fun(); // Stop timer gettimeofday(&end, NULL); // Calculating total time taken // by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(6); cout << \" sec\" << endl; return 0;}", "e": 27657, "s": 26476, "text": null }, { "code": null, "e": 27698, "s": 27657, "text": "Time taken by program is : 0.000046 sec\n" }, { "code": null, "e": 27748, "s": 27698, "text": "Program to illustrate of std::set::lower_bound():" }, { "code": "// C++ program to illustrate// std::lower_bound#include <bits/stdc++.h>#include <sys/time.h>using namespace std; // Function whose time is to// be measuredvoid fun(){ // Initialise the set set<int> s; // Insert element in the set for (int i = 0; i < 10; i++) { s.insert(i); } // Use set::lower_bound() function // to find 5 set<int>::iterator it; it = s.lower_bound(5);} // Driver Codeint main(){ // Use function gettimeofday() // can get the time struct timeval start, end; // Start timer gettimeofday(&start, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); fun(); // Stop timer gettimeofday(&end, NULL); // Calculating total time taken // by the program. double time_taken; time_taken = (end.tv_sec - start.tv_sec) * 1e6; time_taken = (time_taken + (end.tv_usec - start.tv_usec)) * 1e-6; cout << \"Time taken by program is : \" << fixed << time_taken << setprecision(6); cout << \" sec\" << endl; return 0;}", "e": 28891, "s": 27748, "text": null }, { "code": null, "e": 28932, "s": 28891, "text": "Time taken by program is : 0.000039 sec\n" }, { "code": null, "e": 28936, "s": 28932, "text": "STL" }, { "code": null, "e": 28940, "s": 28936, "text": "C++" }, { "code": null, "e": 28961, "s": 28940, "text": "Programming Language" }, { "code": null, "e": 28965, "s": 28961, "text": "STL" }, { "code": null, "e": 28969, "s": 28965, "text": "CPP" }, { "code": null, "e": 29067, "s": 28969, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29095, "s": 29067, "text": "Operator Overloading in C++" }, { "code": null, "e": 29115, "s": 29095, "text": "Polymorphism in C++" }, { "code": null, "e": 29139, "s": 29115, "text": "Sorting a vector in C++" }, { "code": null, "e": 29172, "s": 29139, "text": "Friend class and function in C++" }, { "code": null, "e": 29216, "s": 29172, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 29259, "s": 29216, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 29279, "s": 29259, "text": "JLabel | Java Swing" }, { "code": null, "e": 29320, "s": 29279, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 29366, "s": 29320, "text": "Top 10 Programming Languages to Learn in 2022" } ]
How to negate a predicate function in JavaScript ? - GeeksforGeeks
22 Apr, 2021 In this article, we will see how to negate a predicate function in JavaScript. Predicate functions are the ones that check the condition and return true and false based on argument. Our task is to get the opposite of the predicate function. We follow the following method to get the desired result. Method 1: Our Predicate function is checking for odd and even numbers. If the number is a module with 2, it returns 1 then it is odd, else it is even. Negate the logic while checking conditions for argument. Example : Javascript <script> // Predicate function check odd function isOdd(number) { return number % 2 == 1; } // negation of isOdd function function isNotOdd(number) { return number % 2 !== 1; } // Predicate function check Even function isEven(number) { return number % 2 == 0; } // negation of isEven function function isNotEven(number) { return number % 2 !== 0; } // Outputs: true console.log(isOdd(5)); // Outputs: true console.log(isNotOdd(2)); // Output: false console.log(isEven(3)); // Output> false console.log(isNotEven(4));</script> Output: true true false false Method 2: The problem with the above method is to we are hard-coding our logic at each negation. We probably have more chance to make mistake in negation condition. More effective is to negate predicate function by checking condition. Example : Javascript <script> // Predicate function check odd function isOdd(number) { return number % 2 == 1; } // negation of isOdd function function isNotOdd(number) { return !isOdd(number); } // Predicate function check Even function isEven(number) { return number % 2 == 0; } // negation of isEven function function isNotEven(number) { return !isEven(number); } // Outputs: true console.log(isOdd(5)); // Outputs: true console.log(isNotOdd(10)); // Output: false console.log(isEven(3)); // Output> false console.log(isNotEven(4));</script> Output : true true false false Method 3: In the previous method, we are negating the function for all the predicate functions. But our solution can be more effective if we create one function that negates all the predicate functions. We make predicate function and bind negate function with all predicate functions. Example : Javascript <script> // Predicate function check odd function isOdd(number) { return number % 2 == 1; } // Predicate function check Even function isEven(number) { return number % 2 == 0; } // function that negate all function function negate(pre) { return function (number) { return !pre(number); }; } // Wrapping predicate function to negate function var isNotOdd = negate(isOdd); var isNotEven = negate(isEven); // Outputs: true console.log(isOdd(5)); // Outputs: true console.log(isNotOdd(10)); // Output: false console.log(isEven(3)); // Output: false console.log(isNotEven(4));</script> Output : true true false false javascript-functions JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 39215, "s": 39187, "text": "\n22 Apr, 2021" }, { "code": null, "e": 39457, "s": 39215, "text": "In this article, we will see how to negate a predicate function in JavaScript. Predicate functions are the ones that check the condition and return true and false based on argument. Our task is to get the opposite of the predicate function. " }, { "code": null, "e": 39515, "s": 39457, "text": "We follow the following method to get the desired result." }, { "code": null, "e": 39723, "s": 39515, "text": "Method 1: Our Predicate function is checking for odd and even numbers. If the number is a module with 2, it returns 1 then it is odd, else it is even. Negate the logic while checking conditions for argument." }, { "code": null, "e": 39734, "s": 39723, "text": "Example : " }, { "code": null, "e": 39745, "s": 39734, "text": "Javascript" }, { "code": "<script> // Predicate function check odd function isOdd(number) { return number % 2 == 1; } // negation of isOdd function function isNotOdd(number) { return number % 2 !== 1; } // Predicate function check Even function isEven(number) { return number % 2 == 0; } // negation of isEven function function isNotEven(number) { return number % 2 !== 0; } // Outputs: true console.log(isOdd(5)); // Outputs: true console.log(isNotOdd(2)); // Output: false console.log(isEven(3)); // Output> false console.log(isNotEven(4));</script>", "e": 40311, "s": 39745, "text": null }, { "code": null, "e": 40320, "s": 40311, "text": "Output: " }, { "code": null, "e": 40343, "s": 40320, "text": "true\ntrue \nfalse\nfalse" }, { "code": null, "e": 40578, "s": 40343, "text": "Method 2: The problem with the above method is to we are hard-coding our logic at each negation. We probably have more chance to make mistake in negation condition. More effective is to negate predicate function by checking condition." }, { "code": null, "e": 40588, "s": 40578, "text": "Example :" }, { "code": null, "e": 40599, "s": 40588, "text": "Javascript" }, { "code": "<script> // Predicate function check odd function isOdd(number) { return number % 2 == 1; } // negation of isOdd function function isNotOdd(number) { return !isOdd(number); } // Predicate function check Even function isEven(number) { return number % 2 == 0; } // negation of isEven function function isNotEven(number) { return !isEven(number); } // Outputs: true console.log(isOdd(5)); // Outputs: true console.log(isNotOdd(10)); // Output: false console.log(isEven(3)); // Output> false console.log(isNotEven(4));</script>", "e": 41163, "s": 40599, "text": null }, { "code": null, "e": 41173, "s": 41163, "text": "Output : " }, { "code": null, "e": 41197, "s": 41173, "text": "true \ntrue \nfalse\nfalse" }, { "code": null, "e": 41483, "s": 41197, "text": "Method 3: In the previous method, we are negating the function for all the predicate functions. But our solution can be more effective if we create one function that negates all the predicate functions. We make predicate function and bind negate function with all predicate functions. " }, { "code": null, "e": 41493, "s": 41483, "text": "Example :" }, { "code": null, "e": 41504, "s": 41493, "text": "Javascript" }, { "code": "<script> // Predicate function check odd function isOdd(number) { return number % 2 == 1; } // Predicate function check Even function isEven(number) { return number % 2 == 0; } // function that negate all function function negate(pre) { return function (number) { return !pre(number); }; } // Wrapping predicate function to negate function var isNotOdd = negate(isOdd); var isNotEven = negate(isEven); // Outputs: true console.log(isOdd(5)); // Outputs: true console.log(isNotOdd(10)); // Output: false console.log(isEven(3)); // Output: false console.log(isNotEven(4));</script>", "e": 42133, "s": 41504, "text": null }, { "code": null, "e": 42143, "s": 42133, "text": "Output : " }, { "code": null, "e": 42168, "s": 42143, "text": "true \ntrue \nfalse \nfalse" }, { "code": null, "e": 42189, "s": 42168, "text": "javascript-functions" }, { "code": null, "e": 42210, "s": 42189, "text": "JavaScript-Questions" }, { "code": null, "e": 42217, "s": 42210, "text": "Picked" }, { "code": null, "e": 42228, "s": 42217, "text": "JavaScript" }, { "code": null, "e": 42245, "s": 42228, "text": "Web Technologies" }, { "code": null, "e": 42343, "s": 42245, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42383, "s": 42343, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 42428, "s": 42383, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42489, "s": 42428, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 42561, "s": 42489, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 42630, "s": 42561, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 42670, "s": 42630, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 42703, "s": 42670, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 42748, "s": 42703, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 42791, "s": 42748, "text": "How to fetch data from an API in ReactJS ?" } ]
Minimum number of adjacent swaps required to convert a permutation to another permutation by given condition - GeeksforGeeks
02 Mar, 2022 Given a permutation P of size N, having values from 1 to N. the task is to find the minimum number of adjacent swaps required such that for all i in the range [1, N], P[i] does not equal i.Examples: Input: P = [1, 4, 3, 5, 2] Output: 2 Explanation: Here P = [1, 4, 3, 5, 2] at index 1, 2, 3, 4, 5. As we can see, P[1] = 1 and P[3] = 3. Hence, we need to get rid of this invariant. Swap 1: Swap index 1 and index 2 => [4, 1, 3, 5, 2] Swap 2: Swap index 2 and index 3 => [4, 3, 1, 5, 2] The final array has no i where P[i] = i. Hence, a minimum of 2 swaps is required.Input: P = [1, 2, 4, 9, 5, 8, 7, 3, 6] Output: 3 Explanation: Swap 1: Swap index 1 and index 2 => [2, 1, 4, 9, 5, 8, 7, 3, 6] Swap 2: Swap index 5 and index 6 => [2, 1, 4, 9, 8, 5, 7, 3, 6] Swap 2: Swap index 7 and index 8 => [2, 1, 4, 9, 8, 5, 3, 7, 6] Hence, a minimum of 3 swaps is required. Approach: Let us consider the positions where P[i] = i be denoted by X and the other positions by O. Below are three basic observation for the question: If values at any two adjacent index of the permutation is of the form XO, we can simply swap the 2 indexes to get ‘OO’. If values at any two adjacent index of the permutation is of the form XX, we can simply swap the 2 indexes to get ‘OO’. If values at any two adjacent index of the permutation is of the form OX, it is simply ‘XO’ or ‘XX’ once the pointer reaches index at X. Below are the steps: Iterate from 1 to N – 1 and check if P[i] = i then we simply swap(P[i], P[i + 1]), otherwise continue the process for the next adjacent pairs.The Corner Case for the given question is when i = N, if P[i] = i, then we swap(P[i], P[i – 1]). Iterate from 1 to N – 1 and check if P[i] = i then we simply swap(P[i], P[i + 1]), otherwise continue the process for the next adjacent pairs. The Corner Case for the given question is when i = N, if P[i] = i, then we swap(P[i], P[i – 1]). Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum// number of swapsvoid solve(vector<int>& P, int n){ // New array to convert // to 1-based indexing vector<int> arr; arr.push_back(0); for (auto x : P) arr.push_back(x); // Keeps count of swaps int cnt = 0; for (int i = 1; i < n; i++) { // Check if it is an 'X' position if (arr[i] == i) { swap(arr[i], arr[i + 1]); cnt++; } } // Corner Case if (arr[n] == n) { swap(arr[n - 1], arr[n]); cnt++; } // Print the minimum swaps cout << cnt << endl;} // Driver Codesigned main(){ // Given Number N int N = 9; // Given Permutation of N numbers vector<int> P = { 1, 2, 4, 9, 5, 8, 7, 3, 6 }; // Function Call solve(P, N); return 0;} // Java program for the above approachimport java.io.*; class GFG{ // Function to find the minimum// number of swapsstatic void solve(int P[], int n){ // New array to convert // to 1-based indexing int arr[] = new int[n + 1]; arr[0] = 0; for(int i = 0; i < n; i++) arr[i + 1] = P[i]; // Keeps count of swaps int cnt = 0; for(int i = 1; i < n; i++) { // Check if it is an 'X' position if (arr[i] == i) { int t = arr[i + 1]; arr[i + 1] = arr[i]; arr[i] = t; cnt++; } } // Corner Case if (arr[n] == n) { // Swap int t = arr[n - 1]; arr[n - 1] = arr[n]; arr[n] = t; cnt++; } // Print the minimum swaps System.out.println(cnt);} // Driver codepublic static void main(String[] args){ // Given Number N int N = 9; // Given Permutation of N numbers int P[] = new int[]{ 1, 2, 4, 9, 5, 8, 7, 3, 6 }; // Function Call solve(P, N);}} // This code is contributed by Pratima Pandey # Python3 program for the above approach # Function to find the minimum# number of swapsdef solve(P, n): # New array to convert # to 1-based indexing arr = [] arr.append(0) for x in P: arr.append(x) # Keeps count of swaps cnt = 0 for i in range(1, n): # Check if it is an 'X' position if (arr[i] == i): arr[i], arr[i + 1] = arr[i + 1], arr[i] cnt += 1 # Corner Case if (arr[n] == n): arr[n - 1], arr[n] = arr[n] , arr[n - 1] cnt += 1 # Print the minimum swaps print(cnt) # Driver Code # Given number NN = 9 # Given permutation of N numbersP = [ 1, 2, 4, 9, 5, 8, 7, 3, 6 ] # Function callsolve(P, N) # This code is contributed by chitranayal // C# program for the above approachusing System; class GFG{ // Function to find the minimum// number of swapsstatic void solve(int []P, int n){ // New array to convert // to 1-based indexing int []arr = new int[n + 1]; arr[0] = 0; for(int i = 0; i < n; i++) arr[i + 1] = P[i]; // Keeps count of swaps int cnt = 0; for(int i = 1; i < n; i++) { // Check if it is an 'X' position if (arr[i] == i) { int t = arr[i + 1]; arr[i + 1] = arr[i]; arr[i] = t; cnt++; } } // Corner Case if (arr[n] == n) { // Swap int t = arr[n - 1]; arr[n - 1] = arr[n]; arr[n] = t; cnt++; } // Print the minimum swaps Console.WriteLine(cnt);} // Driver codepublic static void Main(String[] args){ // Given Number N int N = 9; // Given Permutation of N numbers int []P = { 1, 2, 4, 9, 5, 8, 7, 3, 6 }; // Function Call solve(P, N);}} // This code is contributed by Princi Singh <script> // JavaScript program for the above approach // Function to find the minimum// number of swapsfunction solve(P, n){ // New array to convert // to 1-based indexing let arr = Array.from({length: n+1}, (_, i) => 0); arr[0] = 0; for(let i = 0; i < n; i++) arr[i + 1] = P[i]; // Keeps count of swaps let cnt = 0; for(let i = 1; i < n; i++) { // Check if it is an 'X' position if (arr[i] == i) { let t = arr[i + 1]; arr[i + 1] = arr[i]; arr[i] = t; cnt++; } } // Corner Case if (arr[n] == n) { // Swap let t = arr[n - 1]; arr[n - 1] = arr[n]; arr[n] = t; cnt++; } // Print the minimum swaps document.write(cnt);} // Driver Code // Given Number N let N = 9; // Given Permutation of N numbers let P = [ 1, 2, 4, 9, 5, 8, 7, 3, 6 ]; // Function Call solve(P, N); </script> 3 Time Complexity: O(N) Auxiliary Space: O(N) dewantipandeydp princi singh ukasp susmitakundugoaldanga pankajsharmagfg simranarora5sos Natural Numbers permutation Swap-Program Algorithms Arrays Competitive Programming Greedy Arrays Greedy permutation Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 25941, "s": 25913, "text": "\n02 Mar, 2022" }, { "code": null, "e": 26142, "s": 25941, "text": "Given a permutation P of size N, having values from 1 to N. the task is to find the minimum number of adjacent swaps required such that for all i in the range [1, N], P[i] does not equal i.Examples: " }, { "code": null, "e": 26806, "s": 26142, "text": "Input: P = [1, 4, 3, 5, 2] Output: 2 Explanation: Here P = [1, 4, 3, 5, 2] at index 1, 2, 3, 4, 5. As we can see, P[1] = 1 and P[3] = 3. Hence, we need to get rid of this invariant. Swap 1: Swap index 1 and index 2 => [4, 1, 3, 5, 2] Swap 2: Swap index 2 and index 3 => [4, 3, 1, 5, 2] The final array has no i where P[i] = i. Hence, a minimum of 2 swaps is required.Input: P = [1, 2, 4, 9, 5, 8, 7, 3, 6] Output: 3 Explanation: Swap 1: Swap index 1 and index 2 => [2, 1, 4, 9, 5, 8, 7, 3, 6] Swap 2: Swap index 5 and index 6 => [2, 1, 4, 9, 8, 5, 7, 3, 6] Swap 2: Swap index 7 and index 8 => [2, 1, 4, 9, 8, 5, 3, 7, 6] Hence, a minimum of 3 swaps is required. " }, { "code": null, "e": 26961, "s": 26806, "text": "Approach: Let us consider the positions where P[i] = i be denoted by X and the other positions by O. Below are three basic observation for the question: " }, { "code": null, "e": 27081, "s": 26961, "text": "If values at any two adjacent index of the permutation is of the form XO, we can simply swap the 2 indexes to get ‘OO’." }, { "code": null, "e": 27201, "s": 27081, "text": "If values at any two adjacent index of the permutation is of the form XX, we can simply swap the 2 indexes to get ‘OO’." }, { "code": null, "e": 27338, "s": 27201, "text": "If values at any two adjacent index of the permutation is of the form OX, it is simply ‘XO’ or ‘XX’ once the pointer reaches index at X." }, { "code": null, "e": 27361, "s": 27338, "text": "Below are the steps: " }, { "code": null, "e": 27600, "s": 27361, "text": "Iterate from 1 to N – 1 and check if P[i] = i then we simply swap(P[i], P[i + 1]), otherwise continue the process for the next adjacent pairs.The Corner Case for the given question is when i = N, if P[i] = i, then we swap(P[i], P[i – 1])." }, { "code": null, "e": 27743, "s": 27600, "text": "Iterate from 1 to N – 1 and check if P[i] = i then we simply swap(P[i], P[i + 1]), otherwise continue the process for the next adjacent pairs." }, { "code": null, "e": 27840, "s": 27743, "text": "The Corner Case for the given question is when i = N, if P[i] = i, then we swap(P[i], P[i – 1])." }, { "code": null, "e": 27889, "s": 27840, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27893, "s": 27889, "text": "C++" }, { "code": null, "e": 27898, "s": 27893, "text": "Java" }, { "code": null, "e": 27906, "s": 27898, "text": "Python3" }, { "code": null, "e": 27909, "s": 27906, "text": "C#" }, { "code": null, "e": 27920, "s": 27909, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the minimum// number of swapsvoid solve(vector<int>& P, int n){ // New array to convert // to 1-based indexing vector<int> arr; arr.push_back(0); for (auto x : P) arr.push_back(x); // Keeps count of swaps int cnt = 0; for (int i = 1; i < n; i++) { // Check if it is an 'X' position if (arr[i] == i) { swap(arr[i], arr[i + 1]); cnt++; } } // Corner Case if (arr[n] == n) { swap(arr[n - 1], arr[n]); cnt++; } // Print the minimum swaps cout << cnt << endl;} // Driver Codesigned main(){ // Given Number N int N = 9; // Given Permutation of N numbers vector<int> P = { 1, 2, 4, 9, 5, 8, 7, 3, 6 }; // Function Call solve(P, N); return 0;}", "e": 28818, "s": 27920, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to find the minimum// number of swapsstatic void solve(int P[], int n){ // New array to convert // to 1-based indexing int arr[] = new int[n + 1]; arr[0] = 0; for(int i = 0; i < n; i++) arr[i + 1] = P[i]; // Keeps count of swaps int cnt = 0; for(int i = 1; i < n; i++) { // Check if it is an 'X' position if (arr[i] == i) { int t = arr[i + 1]; arr[i + 1] = arr[i]; arr[i] = t; cnt++; } } // Corner Case if (arr[n] == n) { // Swap int t = arr[n - 1]; arr[n - 1] = arr[n]; arr[n] = t; cnt++; } // Print the minimum swaps System.out.println(cnt);} // Driver codepublic static void main(String[] args){ // Given Number N int N = 9; // Given Permutation of N numbers int P[] = new int[]{ 1, 2, 4, 9, 5, 8, 7, 3, 6 }; // Function Call solve(P, N);}} // This code is contributed by Pratima Pandey", "e": 29913, "s": 28818, "text": null }, { "code": "# Python3 program for the above approach # Function to find the minimum# number of swapsdef solve(P, n): # New array to convert # to 1-based indexing arr = [] arr.append(0) for x in P: arr.append(x) # Keeps count of swaps cnt = 0 for i in range(1, n): # Check if it is an 'X' position if (arr[i] == i): arr[i], arr[i + 1] = arr[i + 1], arr[i] cnt += 1 # Corner Case if (arr[n] == n): arr[n - 1], arr[n] = arr[n] , arr[n - 1] cnt += 1 # Print the minimum swaps print(cnt) # Driver Code # Given number NN = 9 # Given permutation of N numbersP = [ 1, 2, 4, 9, 5, 8, 7, 3, 6 ] # Function callsolve(P, N) # This code is contributed by chitranayal", "e": 30661, "s": 29913, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find the minimum// number of swapsstatic void solve(int []P, int n){ // New array to convert // to 1-based indexing int []arr = new int[n + 1]; arr[0] = 0; for(int i = 0; i < n; i++) arr[i + 1] = P[i]; // Keeps count of swaps int cnt = 0; for(int i = 1; i < n; i++) { // Check if it is an 'X' position if (arr[i] == i) { int t = arr[i + 1]; arr[i + 1] = arr[i]; arr[i] = t; cnt++; } } // Corner Case if (arr[n] == n) { // Swap int t = arr[n - 1]; arr[n - 1] = arr[n]; arr[n] = t; cnt++; } // Print the minimum swaps Console.WriteLine(cnt);} // Driver codepublic static void Main(String[] args){ // Given Number N int N = 9; // Given Permutation of N numbers int []P = { 1, 2, 4, 9, 5, 8, 7, 3, 6 }; // Function Call solve(P, N);}} // This code is contributed by Princi Singh", "e": 31743, "s": 30661, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the minimum// number of swapsfunction solve(P, n){ // New array to convert // to 1-based indexing let arr = Array.from({length: n+1}, (_, i) => 0); arr[0] = 0; for(let i = 0; i < n; i++) arr[i + 1] = P[i]; // Keeps count of swaps let cnt = 0; for(let i = 1; i < n; i++) { // Check if it is an 'X' position if (arr[i] == i) { let t = arr[i + 1]; arr[i + 1] = arr[i]; arr[i] = t; cnt++; } } // Corner Case if (arr[n] == n) { // Swap let t = arr[n - 1]; arr[n - 1] = arr[n]; arr[n] = t; cnt++; } // Print the minimum swaps document.write(cnt);} // Driver Code // Given Number N let N = 9; // Given Permutation of N numbers let P = [ 1, 2, 4, 9, 5, 8, 7, 3, 6 ]; // Function Call solve(P, N); </script>", "e": 32738, "s": 31743, "text": null }, { "code": null, "e": 32740, "s": 32738, "text": "3" }, { "code": null, "e": 32785, "s": 32740, "text": "Time Complexity: O(N) Auxiliary Space: O(N)" }, { "code": null, "e": 32801, "s": 32785, "text": "dewantipandeydp" }, { "code": null, "e": 32814, "s": 32801, "text": "princi singh" }, { "code": null, "e": 32820, "s": 32814, "text": "ukasp" }, { "code": null, "e": 32842, "s": 32820, "text": "susmitakundugoaldanga" }, { "code": null, "e": 32858, "s": 32842, "text": "pankajsharmagfg" }, { "code": null, "e": 32874, "s": 32858, "text": "simranarora5sos" }, { "code": null, "e": 32890, "s": 32874, "text": "Natural Numbers" }, { "code": null, "e": 32902, "s": 32890, "text": "permutation" }, { "code": null, "e": 32915, "s": 32902, "text": "Swap-Program" }, { "code": null, "e": 32926, "s": 32915, "text": "Algorithms" }, { "code": null, "e": 32933, "s": 32926, "text": "Arrays" }, { "code": null, "e": 32957, "s": 32933, "text": "Competitive Programming" }, { "code": null, "e": 32964, "s": 32957, "text": "Greedy" }, { "code": null, "e": 32971, "s": 32964, "text": "Arrays" }, { "code": null, "e": 32978, "s": 32971, "text": "Greedy" }, { "code": null, "e": 32990, "s": 32978, "text": "permutation" }, { "code": null, "e": 33001, "s": 32990, "text": "Algorithms" }, { "code": null, "e": 33099, "s": 33001, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33124, "s": 33099, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33151, "s": 33124, "text": "How to Start Learning DSA?" }, { "code": null, "e": 33204, "s": 33151, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 33238, "s": 33204, "text": "K means Clustering - Introduction" }, { "code": null, "e": 33305, "s": 33238, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 33320, "s": 33305, "text": "Arrays in Java" }, { "code": null, "e": 33336, "s": 33320, "text": "Arrays in C/C++" }, { "code": null, "e": 33404, "s": 33336, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33450, "s": 33404, "text": "Write a program to reverse an array or string" } ]
Integer lowestOneBit() Method in Java - GeeksforGeeks
13 Dec, 2021 The Integer.lowestOneBit() method of java.lang is an inbuilt function that returns an int value with at most a single one-bit, in the position of the lowest-order (ie.rightmost) one-bit in the specified int value. This method will return zero if the specified value has no one-bits in its two’s complement binary representation, ie. if the binary representation of the number is equal to zero.Syntax: public static int lowestOneBit(int a) Parameters: The method takes one parameter a of integer type that refers to the value whose lowest order bit is to be returned or on which the operation is to be performed.Returns : The method can return two types of values: Returns an integer value with a single 1-bit, in the position of the lowest-order one-bit in the specified value Returns zero if the specified value is equal to zero. Examples: Input: 157 Output: Lowest one bit = 1 Input: 0 Output: Lowest one bit = 0 Explanation: Consider any integer a = 10 Binary Representation = 0000 1010 Lowest bit(at 1) i.e.0000 0010 so result = 2^1=2 Below programs illustrate the java.lang.Integer.lowestOneBit() method:Program 1: For a positive number. java // Java program to illustrate the// java.lang.Integer.lowestOneBit() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = 157; System.out.println("Given Number = " + a); // Returns an int value with at most a single one-bit System.out.print("Lowest one bit = "); System.out.println(Integer.lowestOneBit(a)); a = 64; System.out.println("Given Number = " + a); System.out.print("Lowest one bit = "); System.out.println(Integer.lowestOneBit(a)); // Here it will return 0 since the number is itself zero a = 0; System.out.println("Given Number = " + a); System.out.print("Lowest one bit = "); System.out.println(Integer.lowestOneBit(a)); }} Given Number = 157 Lowest one bit = 1 Given Number = 64 Lowest one bit = 64 Given Number = 0 Lowest one bit = 0 Program 2: For a negative number. java // Java program to illustrate the// java.lang.Integer.lowestOneBit() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = -157; System.out.println("Given Number = " + a); // It will return an int value with at most a single one-bit System.out.print("Lowest one bit = "); System.out.println(Integer.lowestOneBit(a)); a = -17; System.out.println("Given Number = " + a); System.out.print("Lowest one bit = "); System.out.println(Integer.lowestOneBit(a)); }} Given Number = -157 Lowest one bit = 1 Given Number = -17 Lowest one bit = 1 Program 3: For a decimal value and String. Note:It returns a compile time error message when a decimal value and a string is passed as an argument. java // Java program to illustrate the// java.lang.Integer.lowestOneBit() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { // Decimal value is given int a = 71.57; System.out.println("Given Number = " + a); System.out.print("Lowest one bit = "); System.out.println(Integer.lowestOneBit(a)); // String is passed a = "12"; System.out.println("Given Number = " + a); System.out.print("Lowest one bit = "); System.out.println(Integer.lowestOneBit(a)); }} Output: prog.java:10: error: incompatible types: possible lossy conversion from double to int int a = 71.57; ^ prog.java:17: error: incompatible types: String cannot be converted to int a = "12"; ^ 2 errors adnanirshad158 Java-Functions Java-Integer Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n13 Dec, 2021" }, { "code": null, "e": 25627, "s": 25225, "text": "The Integer.lowestOneBit() method of java.lang is an inbuilt function that returns an int value with at most a single one-bit, in the position of the lowest-order (ie.rightmost) one-bit in the specified int value. This method will return zero if the specified value has no one-bits in its two’s complement binary representation, ie. if the binary representation of the number is equal to zero.Syntax: " }, { "code": null, "e": 25665, "s": 25627, "text": "public static int lowestOneBit(int a)" }, { "code": null, "e": 25890, "s": 25665, "text": "Parameters: The method takes one parameter a of integer type that refers to the value whose lowest order bit is to be returned or on which the operation is to be performed.Returns : The method can return two types of values:" }, { "code": null, "e": 26003, "s": 25890, "text": "Returns an integer value with a single 1-bit, in the position of the lowest-order one-bit in the specified value" }, { "code": null, "e": 26057, "s": 26003, "text": "Returns zero if the specified value is equal to zero." }, { "code": null, "e": 26068, "s": 26057, "text": "Examples: " }, { "code": null, "e": 26268, "s": 26068, "text": "Input: 157\nOutput: Lowest one bit = 1\n\nInput: 0\nOutput: Lowest one bit = 0\n\nExplanation:\nConsider any integer a = 10\nBinary Representation = 0000 1010\nLowest bit(at 1) i.e.0000 0010\nso result = 2^1=2" }, { "code": null, "e": 26373, "s": 26268, "text": "Below programs illustrate the java.lang.Integer.lowestOneBit() method:Program 1: For a positive number. " }, { "code": null, "e": 26378, "s": 26373, "text": "java" }, { "code": "// Java program to illustrate the// java.lang.Integer.lowestOneBit() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = 157; System.out.println(\"Given Number = \" + a); // Returns an int value with at most a single one-bit System.out.print(\"Lowest one bit = \"); System.out.println(Integer.lowestOneBit(a)); a = 64; System.out.println(\"Given Number = \" + a); System.out.print(\"Lowest one bit = \"); System.out.println(Integer.lowestOneBit(a)); // Here it will return 0 since the number is itself zero a = 0; System.out.println(\"Given Number = \" + a); System.out.print(\"Lowest one bit = \"); System.out.println(Integer.lowestOneBit(a)); }}", "e": 27172, "s": 26378, "text": null }, { "code": null, "e": 27284, "s": 27172, "text": "Given Number = 157\nLowest one bit = 1\nGiven Number = 64\nLowest one bit = 64\nGiven Number = 0\nLowest one bit = 0" }, { "code": null, "e": 27321, "s": 27286, "text": "Program 2: For a negative number. " }, { "code": null, "e": 27326, "s": 27321, "text": "java" }, { "code": "// Java program to illustrate the// java.lang.Integer.lowestOneBit() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { int a = -157; System.out.println(\"Given Number = \" + a); // It will return an int value with at most a single one-bit System.out.print(\"Lowest one bit = \"); System.out.println(Integer.lowestOneBit(a)); a = -17; System.out.println(\"Given Number = \" + a); System.out.print(\"Lowest one bit = \"); System.out.println(Integer.lowestOneBit(a)); }}", "e": 27900, "s": 27326, "text": null }, { "code": null, "e": 27977, "s": 27900, "text": "Given Number = -157\nLowest one bit = 1\nGiven Number = -17\nLowest one bit = 1" }, { "code": null, "e": 28128, "s": 27979, "text": "Program 3: For a decimal value and String. Note:It returns a compile time error message when a decimal value and a string is passed as an argument. " }, { "code": null, "e": 28133, "s": 28128, "text": "java" }, { "code": "// Java program to illustrate the// java.lang.Integer.lowestOneBit() methodimport java.lang.*; public class Geeks { public static void main(String[] args) { // Decimal value is given int a = 71.57; System.out.println(\"Given Number = \" + a); System.out.print(\"Lowest one bit = \"); System.out.println(Integer.lowestOneBit(a)); // String is passed a = \"12\"; System.out.println(\"Given Number = \" + a); System.out.print(\"Lowest one bit = \"); System.out.println(Integer.lowestOneBit(a)); }}", "e": 28702, "s": 28133, "text": null }, { "code": null, "e": 28711, "s": 28702, "text": "Output: " }, { "code": null, "e": 28938, "s": 28711, "text": "prog.java:10: error: incompatible types: possible lossy conversion from double to int\n int a = 71.57;\n ^\nprog.java:17: error: incompatible types: String cannot be converted to int\n a = \"12\";\n ^\n2 errors" }, { "code": null, "e": 28953, "s": 28938, "text": "adnanirshad158" }, { "code": null, "e": 28968, "s": 28953, "text": "Java-Functions" }, { "code": null, "e": 28981, "s": 28968, "text": "Java-Integer" }, { "code": null, "e": 28999, "s": 28981, "text": "Java-lang package" }, { "code": null, "e": 29004, "s": 28999, "text": "Java" }, { "code": null, "e": 29009, "s": 29004, "text": "Java" }, { "code": null, "e": 29107, "s": 29009, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29122, "s": 29107, "text": "Stream In Java" }, { "code": null, "e": 29143, "s": 29122, "text": "Constructors in Java" }, { "code": null, "e": 29162, "s": 29143, "text": "Exceptions in Java" }, { "code": null, "e": 29192, "s": 29162, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29238, "s": 29192, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29255, "s": 29238, "text": "Generics in Java" }, { "code": null, "e": 29276, "s": 29255, "text": "Introduction to Java" }, { "code": null, "e": 29319, "s": 29276, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29355, "s": 29319, "text": "Internal Working of HashMap in Java" } ]
Difference between promise and async await in Node.js - GeeksforGeeks
18 Apr, 2022 There are different ways to handle operations in NodeJS or in JavaScript. For asynchronous execution, different processes run simultaneously and are handled once the result of each process is available. There are different ways to handle the asynchronous code in NodeJS or in JavaScript which are: Callbacks Promises Async/Await 1. Promises: A Promise in NodeJS is similar to a promise in real life. It is an assurance that something will be done. Promise is used to keep track of whether the asynchronous event has been executed or not and determines what happens after the event has occurred. It is an object having 3 states namely: Pending: Initial State, before the event has happened. Resolved: After the operation completed successfully. Rejected: If the operation had error during execution, the promise fails. Example: While requesting data from a database server, the Promise is in a pending state until the data is received. If the data is received successfully, then the Promise is in resolved state and if the data could not be received successfully, the Promise is in the rejected state. Error Handling of Promises: For a successfully resolved promise, we use .then() method and for rejected promise, we use .catch() method. To run a code after the promise has been handled using .then() or .catch() method, we can .finally() method. The code inside .finally() method runs once regardless of the state of the promise. Example: Javascript <script> const promise = new Promise(function (resolve, reject) { const string1 = "geeksforgeeks"; const string2 = "geeksforgeeks"; if (string1 === string2) { resolve(); } else { reject(); } }); promise .then(function () { console.log("Promise resolved successfully"); }) .catch(function () { console.log("Promise is rejected"); });</script> Output: Promise resolved successfully 2. Async/Await: Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand. await can only be used in async functions. It is used for calling an async function and waits for it to resolve or reject. await blocks the execution of the code within the async function in which it is located. Error Handling in Async/Await: For a successfully resolved promise, we use try and for rejected promise, we use catch. To run a code after the promise has been handled using try or catch, we can .finally() method. The code inside .finally() method runs once regardless of the state of the promise. Example: Javascript <script> const helperPromise = function () { const promise = new Promise(function (resolve, reject) { const x = "geeksforgeeks"; const y = "geeksforgeeks"; if (x === y) { resolve("Strings are same"); } else { reject("Strings are not same"); } }); return promise; }; async function demoPromise() { try { let message = await helperPromise(); console.log(message); } catch (error) { console.log("Error: " + error); } } demoPromise();</script> Output: Strings are same Difference Between Promise and Async/Await: Promise Async/Await sumitgumber28 NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method Node.js fs.readFile() Method How to install the previous version of node.js and npm ? How to use an ES6 import in Node.js? How to read and write Excel file in Node.js ? 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": 25818, "s": 25790, "text": "\n18 Apr, 2022" }, { "code": null, "e": 26116, "s": 25818, "text": "There are different ways to handle operations in NodeJS or in JavaScript. For asynchronous execution, different processes run simultaneously and are handled once the result of each process is available. There are different ways to handle the asynchronous code in NodeJS or in JavaScript which are:" }, { "code": null, "e": 26126, "s": 26116, "text": "Callbacks" }, { "code": null, "e": 26135, "s": 26126, "text": "Promises" }, { "code": null, "e": 26147, "s": 26135, "text": "Async/Await" }, { "code": null, "e": 26160, "s": 26147, "text": "1. Promises:" }, { "code": null, "e": 26453, "s": 26160, "text": "A Promise in NodeJS is similar to a promise in real life. It is an assurance that something will be done. Promise is used to keep track of whether the asynchronous event has been executed or not and determines what happens after the event has occurred. It is an object having 3 states namely:" }, { "code": null, "e": 26508, "s": 26453, "text": "Pending: Initial State, before the event has happened." }, { "code": null, "e": 26562, "s": 26508, "text": "Resolved: After the operation completed successfully." }, { "code": null, "e": 26636, "s": 26562, "text": "Rejected: If the operation had error during execution, the promise fails." }, { "code": null, "e": 26920, "s": 26636, "text": "Example: While requesting data from a database server, the Promise is in a pending state until the data is received. If the data is received successfully, then the Promise is in resolved state and if the data could not be received successfully, the Promise is in the rejected state. " }, { "code": null, "e": 27250, "s": 26920, "text": "Error Handling of Promises: For a successfully resolved promise, we use .then() method and for rejected promise, we use .catch() method. To run a code after the promise has been handled using .then() or .catch() method, we can .finally() method. The code inside .finally() method runs once regardless of the state of the promise." }, { "code": null, "e": 27259, "s": 27250, "text": "Example:" }, { "code": null, "e": 27270, "s": 27259, "text": "Javascript" }, { "code": "<script> const promise = new Promise(function (resolve, reject) { const string1 = \"geeksforgeeks\"; const string2 = \"geeksforgeeks\"; if (string1 === string2) { resolve(); } else { reject(); } }); promise .then(function () { console.log(\"Promise resolved successfully\"); }) .catch(function () { console.log(\"Promise is rejected\"); });</script>", "e": 27663, "s": 27270, "text": null }, { "code": null, "e": 27671, "s": 27663, "text": "Output:" }, { "code": null, "e": 27701, "s": 27671, "text": "Promise resolved successfully" }, { "code": null, "e": 27717, "s": 27701, "text": "2. Async/Await:" }, { "code": null, "e": 28013, "s": 27717, "text": "Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand." }, { "code": null, "e": 28226, "s": 28013, "text": "await can only be used in async functions. It is used for calling an async function and waits for it to resolve or reject. await blocks the execution of the code within the async function in which it is located. " }, { "code": null, "e": 28524, "s": 28226, "text": "Error Handling in Async/Await: For a successfully resolved promise, we use try and for rejected promise, we use catch. To run a code after the promise has been handled using try or catch, we can .finally() method. The code inside .finally() method runs once regardless of the state of the promise." }, { "code": null, "e": 28533, "s": 28524, "text": "Example:" }, { "code": null, "e": 28544, "s": 28533, "text": "Javascript" }, { "code": "<script> const helperPromise = function () { const promise = new Promise(function (resolve, reject) { const x = \"geeksforgeeks\"; const y = \"geeksforgeeks\"; if (x === y) { resolve(\"Strings are same\"); } else { reject(\"Strings are not same\"); } }); return promise; }; async function demoPromise() { try { let message = await helperPromise(); console.log(message); } catch (error) { console.log(\"Error: \" + error); } } demoPromise();</script>", "e": 29064, "s": 28544, "text": null }, { "code": null, "e": 29072, "s": 29064, "text": "Output:" }, { "code": null, "e": 29089, "s": 29072, "text": "Strings are same" }, { "code": null, "e": 29133, "s": 29089, "text": "Difference Between Promise and Async/Await:" }, { "code": null, "e": 29141, "s": 29133, "text": "Promise" }, { "code": null, "e": 29153, "s": 29141, "text": "Async/Await" }, { "code": null, "e": 29167, "s": 29153, "text": "sumitgumber28" }, { "code": null, "e": 29184, "s": 29167, "text": "NodeJS-Questions" }, { "code": null, "e": 29191, "s": 29184, "text": "Picked" }, { "code": null, "e": 29199, "s": 29191, "text": "Node.js" }, { "code": null, "e": 29216, "s": 29199, "text": "Web Technologies" }, { "code": null, "e": 29314, "s": 29216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29344, "s": 29314, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 29373, "s": 29344, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 29430, "s": 29373, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 29467, "s": 29430, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 29513, "s": 29467, "text": "How to read and write Excel file in Node.js ?" }, { "code": null, "e": 29553, "s": 29513, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29598, "s": 29553, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29641, "s": 29598, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29691, "s": 29641, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Maximize element at index K in an array with at most sum M and difference between adjacent elements at most 1 - GeeksforGeeks
28 Feb, 2022 Given a positive integer N, the task is to construct an array of length N and find the maximize the value at index K such that the sum of all the array elements is at most M and the absolute difference between any two consecutive array elements is at most 1. Examples: Input: N = 3, M = 7, K = 1Output: 3Explanation: According to the given constraints, the array with values {2, 3, 2}maximizes the value at index 1. Therefore, the required output is 3. Input: N = 3, M = 8, K = 1Output: 3 Approach: The idea is to achieve the maximum value at index K and to decrease the sum of other elements to meet the criteria of the sum of the array to be at most M. Follow the steps below: Let the value at index K be X. So the element at K – 1 is X – 1, at K – 2 is X – 2 and so on. At index 0 the value is X – K. Similarly, at index K + 1 the value is X – 1 and so on upto X – (N – K – 1) at index N – 1. So to achieve the maximum value at index K, the array structure would be X – K, X – (K – 1), ...., X – 2, X – 1, X, X – 1, X – 2, ....., X – (N – K – 1). So after arranging the equation, it becomes K * X – (1 + 2 + .... + K) + X + (N – K – 1) * X – (1 + 2 + .... + (N – K – 1)) ≤ M. Follow the steps to solve the above equation: Calculate (1 + 2 + .... + K) using K * (K + 1) / 2 and (1 + 2 + ..... + (N – K – 1)) using (N – K – 1) * (N – K) / 2 and store in S1 and S2 respectively. This reduces the equation to X * (K + 1 + N – K – 1) ≤ M + S1 + S2. Now, the maximum value of X can be obtained by calculating (M + S1 + S2) / N. 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 calculate the maximum// possible value at index Kvoid maxValueAtIndexK(int N, int K, int M){ // Stores the sum of elements // in the left and right of index K int S1 = 0, S2 = 0; S1 = K * (K + 1) / 2; S2 = (N - K - 1) * (N - K) / 2; // Stores the maximum // possible value at index K int X = (M + S1 + S2) / N; // Print the answer cout << X;} // Driver Codeint main(){ // Given N, K & M int N = 3, K = 1, M = 7; maxValueAtIndexK(N, K, M); return 0;} // Java program for the above approachimport java.io.*; class GFG{ // Function to calculate the maximum// possible value at index Kstatic void maxValueAtIndexK(int N, int K, int M){ // Stores the sum of elements // in the left and right of index K int S1 = 0, S2 = 0; S1 = K * (K + 1) / 2; S2 = (N - K - 1) * (N - K) / 2; // Stores the maximum // possible value at index K int X = (M + S1 + S2) / N; // Print the answer System.out.println(X);} // Driver Codepublic static void main(String[] args){ // Given N, K & M int N = 3, K = 1, M = 7; maxValueAtIndexK(N, K, M);}} // This code is contributed by Dharanendra L V # Python program for the above approach # Function to calculate the maximum# possible value at index Kdef maxValueAtIndexK(N, K, M): # Stores the sum of elements # in the left and right of index K S1 = 0; S2 = 0; S1 = K * (K + 1) // 2; S2 = (N - K - 1) * (N - K) // 2; # Stores the maximum # possible value at index K X = (M + S1 + S2) // N; # Print the answer print(X); # Driver Codeif __name__ == '__main__': # Given N, K & M N = 3; K = 1; M = 7; maxValueAtIndexK(N, K, M); # This code is contributed by 29AjayKumar // C# program for the above approachusing System; class GFG{ // Function to calculate the maximum// possible value at index Kstatic void maxValueAtIndexK(int N, int K, int M){ // Stores the sum of elements // in the left and right of index K int S1 = 0, S2 = 0; S1 = K * (K + 1) / 2; S2 = (N - K - 1) * (N - K) / 2; // Stores the maximum // possible value at index K int X = (M + S1 + S2) / N; // Print the answer Console.WriteLine(X);} // Driver Codestatic public void Main(){ // Given N, K & M int N = 3, K = 1, M = 7; maxValueAtIndexK(N, K, M);}} // This code is contributed by Dharanendra L V <script>// JavaScript program for// the above approach // Function to calculate the maximum// possible value at index Kfunction maxValueAtIndexK(N, K, M){ // Stores the sum of elements // in the left and right of index K let S1 = 0, S2 = 0; S1 = K * (K + 1) / 2; S2 = (N - K - 1) * (N - K) / 2; // Stores the maximum // possible value at index K let X = (M + S1 + S2) / N; // Print the answer document.write(X);} // Driver Code // Given N, K & M let N = 3, K = 1, M = 7; maxValueAtIndexK(N, K, M); </script> 3 Time Complexity: O(1)Auxiliary Space: O(1) dharanendralv23 29AjayKumar avijitmondal1998 simranarora5sos array-rearrange Arrays Greedy Mathematical Arrays Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3 Coin Change | DP-7
[ { "code": null, "e": 26221, "s": 26193, "text": "\n28 Feb, 2022" }, { "code": null, "e": 26480, "s": 26221, "text": "Given a positive integer N, the task is to construct an array of length N and find the maximize the value at index K such that the sum of all the array elements is at most M and the absolute difference between any two consecutive array elements is at most 1." }, { "code": null, "e": 26490, "s": 26480, "text": "Examples:" }, { "code": null, "e": 26674, "s": 26490, "text": "Input: N = 3, M = 7, K = 1Output: 3Explanation: According to the given constraints, the array with values {2, 3, 2}maximizes the value at index 1. Therefore, the required output is 3." }, { "code": null, "e": 26710, "s": 26674, "text": "Input: N = 3, M = 8, K = 1Output: 3" }, { "code": null, "e": 26900, "s": 26710, "text": "Approach: The idea is to achieve the maximum value at index K and to decrease the sum of other elements to meet the criteria of the sum of the array to be at most M. Follow the steps below:" }, { "code": null, "e": 26994, "s": 26900, "text": "Let the value at index K be X. So the element at K – 1 is X – 1, at K – 2 is X – 2 and so on." }, { "code": null, "e": 27117, "s": 26994, "text": "At index 0 the value is X – K. Similarly, at index K + 1 the value is X – 1 and so on upto X – (N – K – 1) at index N – 1." }, { "code": null, "e": 27271, "s": 27117, "text": "So to achieve the maximum value at index K, the array structure would be X – K, X – (K – 1), ...., X – 2, X – 1, X, X – 1, X – 2, ....., X – (N – K – 1)." }, { "code": null, "e": 27400, "s": 27271, "text": "So after arranging the equation, it becomes K * X – (1 + 2 + .... + K) + X + (N – K – 1) * X – (1 + 2 + .... + (N – K – 1)) ≤ M." }, { "code": null, "e": 27446, "s": 27400, "text": "Follow the steps to solve the above equation:" }, { "code": null, "e": 27600, "s": 27446, "text": "Calculate (1 + 2 + .... + K) using K * (K + 1) / 2 and (1 + 2 + ..... + (N – K – 1)) using (N – K – 1) * (N – K) / 2 and store in S1 and S2 respectively." }, { "code": null, "e": 27668, "s": 27600, "text": "This reduces the equation to X * (K + 1 + N – K – 1) ≤ M + S1 + S2." }, { "code": null, "e": 27746, "s": 27668, "text": "Now, the maximum value of X can be obtained by calculating (M + S1 + S2) / N." }, { "code": null, "e": 27797, "s": 27746, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27801, "s": 27797, "text": "C++" }, { "code": null, "e": 27806, "s": 27801, "text": "Java" }, { "code": null, "e": 27814, "s": 27806, "text": "Python3" }, { "code": null, "e": 27817, "s": 27814, "text": "C#" }, { "code": null, "e": 27828, "s": 27817, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate the maximum// possible value at index Kvoid maxValueAtIndexK(int N, int K, int M){ // Stores the sum of elements // in the left and right of index K int S1 = 0, S2 = 0; S1 = K * (K + 1) / 2; S2 = (N - K - 1) * (N - K) / 2; // Stores the maximum // possible value at index K int X = (M + S1 + S2) / N; // Print the answer cout << X;} // Driver Codeint main(){ // Given N, K & M int N = 3, K = 1, M = 7; maxValueAtIndexK(N, K, M); return 0;}", "e": 28422, "s": 27828, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to calculate the maximum// possible value at index Kstatic void maxValueAtIndexK(int N, int K, int M){ // Stores the sum of elements // in the left and right of index K int S1 = 0, S2 = 0; S1 = K * (K + 1) / 2; S2 = (N - K - 1) * (N - K) / 2; // Stores the maximum // possible value at index K int X = (M + S1 + S2) / N; // Print the answer System.out.println(X);} // Driver Codepublic static void main(String[] args){ // Given N, K & M int N = 3, K = 1, M = 7; maxValueAtIndexK(N, K, M);}} // This code is contributed by Dharanendra L V", "e": 29124, "s": 28422, "text": null }, { "code": "# Python program for the above approach # Function to calculate the maximum# possible value at index Kdef maxValueAtIndexK(N, K, M): # Stores the sum of elements # in the left and right of index K S1 = 0; S2 = 0; S1 = K * (K + 1) // 2; S2 = (N - K - 1) * (N - K) // 2; # Stores the maximum # possible value at index K X = (M + S1 + S2) // N; # Print the answer print(X); # Driver Codeif __name__ == '__main__': # Given N, K & M N = 3; K = 1; M = 7; maxValueAtIndexK(N, K, M); # This code is contributed by 29AjayKumar", "e": 29685, "s": 29124, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to calculate the maximum// possible value at index Kstatic void maxValueAtIndexK(int N, int K, int M){ // Stores the sum of elements // in the left and right of index K int S1 = 0, S2 = 0; S1 = K * (K + 1) / 2; S2 = (N - K - 1) * (N - K) / 2; // Stores the maximum // possible value at index K int X = (M + S1 + S2) / N; // Print the answer Console.WriteLine(X);} // Driver Codestatic public void Main(){ // Given N, K & M int N = 3, K = 1, M = 7; maxValueAtIndexK(N, K, M);}} // This code is contributed by Dharanendra L V", "e": 30367, "s": 29685, "text": null }, { "code": "<script>// JavaScript program for// the above approach // Function to calculate the maximum// possible value at index Kfunction maxValueAtIndexK(N, K, M){ // Stores the sum of elements // in the left and right of index K let S1 = 0, S2 = 0; S1 = K * (K + 1) / 2; S2 = (N - K - 1) * (N - K) / 2; // Stores the maximum // possible value at index K let X = (M + S1 + S2) / N; // Print the answer document.write(X);} // Driver Code // Given N, K & M let N = 3, K = 1, M = 7; maxValueAtIndexK(N, K, M); </script>", "e": 30922, "s": 30367, "text": null }, { "code": null, "e": 30924, "s": 30922, "text": "3" }, { "code": null, "e": 30969, "s": 30926, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 30987, "s": 30971, "text": "dharanendralv23" }, { "code": null, "e": 30999, "s": 30987, "text": "29AjayKumar" }, { "code": null, "e": 31016, "s": 30999, "text": "avijitmondal1998" }, { "code": null, "e": 31032, "s": 31016, "text": "simranarora5sos" }, { "code": null, "e": 31048, "s": 31032, "text": "array-rearrange" }, { "code": null, "e": 31055, "s": 31048, "text": "Arrays" }, { "code": null, "e": 31062, "s": 31055, "text": "Greedy" }, { "code": null, "e": 31075, "s": 31062, "text": "Mathematical" }, { "code": null, "e": 31082, "s": 31075, "text": "Arrays" }, { "code": null, "e": 31089, "s": 31082, "text": "Greedy" }, { "code": null, "e": 31102, "s": 31089, "text": "Mathematical" }, { "code": null, "e": 31200, "s": 31102, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31268, "s": 31200, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 31312, "s": 31268, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 31360, "s": 31312, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 31383, "s": 31360, "text": "Introduction to Arrays" }, { "code": null, "e": 31415, "s": 31383, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31466, "s": 31415, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 31517, "s": 31466, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 31575, "s": 31517, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 31606, "s": 31575, "text": "Huffman Coding | Greedy Algo-3" } ]
How to generate QR Codes with a custom logo using Python ? - GeeksforGeeks
23 Jan, 2022 In this article, we will discuss how to generate a QR code with an image at its center. We are going to generate a QR code of any text, link, etc., and put an image in the center of that QR code such that it represents a branded QR code Pillow: It is a lightweight image processing tool that aid in editing, creating, and saving images. Pillow supports many image file formats including BMP, PNG, JPEG, and TIFF. It can be installed using the below command: pip install Pillow QRcode: It is an external python library used to generate QR codes. It can be installed using the below command: pip install qrcode Python3 # import modulesimport qrcodefrom PIL import Image # taking image which user wants# in the QR code centerLogo_link = 'g4g.jpg' logo = Image.open(Logo_link) # taking base widthbasewidth = 100 # adjust image sizewpercent = (basewidth/float(logo.size[0]))hsize = int((float(logo.size[1])*float(wpercent)))logo = logo.resize((basewidth, hsize), Image.ANTIALIAS)QRcode = qrcode.QRCode( error_correction=qrcode.constants.ERROR_CORRECT_H) # taking url or texturl = 'https://www.geeksforgeeks.org/' # adding URL or text to QRcodeQRcode.add_data(url) # generating QR codeQRcode.make() # taking color name from userQRcolor = 'Green' # adding color to QR codeQRimg = QRcode.make_image( fill_color=QRcolor, back_color="white").convert('RGB') # set size of QR codepos = ((QRimg.size[0] - logo.size[0]) // 2, (QRimg.size[1] - logo.size[1]) // 2)QRimg.paste(logo, pos) # save the QR code generatedQRimg.save('gfg_QR.png') print('QR code generated!') Output: QR code generated! QR code: When you run the program then it will take the input image and the base width. After that, the image will be reshaped and a QRcode object will be created. Using the QRcode object various attributes will be assigned such as data or URL will be linked to the QR code using add_data() method, color of the QR code will be assigned using the make_image() method and the reshaped image will be placed in the QR code using the paste() method. Finally, the generated QR code will be saved in a given location using the save() method. sagar0719kumar python-modules python-utility 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": 25562, "s": 25534, "text": "\n23 Jan, 2022" }, { "code": null, "e": 25799, "s": 25562, "text": "In this article, we will discuss how to generate a QR code with an image at its center. We are going to generate a QR code of any text, link, etc., and put an image in the center of that QR code such that it represents a branded QR code" }, { "code": null, "e": 26020, "s": 25799, "text": "Pillow: It is a lightweight image processing tool that aid in editing, creating, and saving images. Pillow supports many image file formats including BMP, PNG, JPEG, and TIFF. It can be installed using the below command:" }, { "code": null, "e": 26039, "s": 26020, "text": "pip install Pillow" }, { "code": null, "e": 26152, "s": 26039, "text": "QRcode: It is an external python library used to generate QR codes. It can be installed using the below command:" }, { "code": null, "e": 26171, "s": 26152, "text": "pip install qrcode" }, { "code": null, "e": 26179, "s": 26171, "text": "Python3" }, { "code": "# import modulesimport qrcodefrom PIL import Image # taking image which user wants# in the QR code centerLogo_link = 'g4g.jpg' logo = Image.open(Logo_link) # taking base widthbasewidth = 100 # adjust image sizewpercent = (basewidth/float(logo.size[0]))hsize = int((float(logo.size[1])*float(wpercent)))logo = logo.resize((basewidth, hsize), Image.ANTIALIAS)QRcode = qrcode.QRCode( error_correction=qrcode.constants.ERROR_CORRECT_H) # taking url or texturl = 'https://www.geeksforgeeks.org/' # adding URL or text to QRcodeQRcode.add_data(url) # generating QR codeQRcode.make() # taking color name from userQRcolor = 'Green' # adding color to QR codeQRimg = QRcode.make_image( fill_color=QRcolor, back_color=\"white\").convert('RGB') # set size of QR codepos = ((QRimg.size[0] - logo.size[0]) // 2, (QRimg.size[1] - logo.size[1]) // 2)QRimg.paste(logo, pos) # save the QR code generatedQRimg.save('gfg_QR.png') print('QR code generated!')", "e": 27126, "s": 26179, "text": null }, { "code": null, "e": 27134, "s": 27126, "text": "Output:" }, { "code": null, "e": 27153, "s": 27134, "text": "QR code generated!" }, { "code": null, "e": 27162, "s": 27153, "text": "QR code:" }, { "code": null, "e": 27317, "s": 27162, "text": "When you run the program then it will take the input image and the base width. After that, the image will be reshaped and a QRcode object will be created." }, { "code": null, "e": 27599, "s": 27317, "text": "Using the QRcode object various attributes will be assigned such as data or URL will be linked to the QR code using add_data() method, color of the QR code will be assigned using the make_image() method and the reshaped image will be placed in the QR code using the paste() method." }, { "code": null, "e": 27689, "s": 27599, "text": "Finally, the generated QR code will be saved in a given location using the save() method." }, { "code": null, "e": 27704, "s": 27689, "text": "sagar0719kumar" }, { "code": null, "e": 27719, "s": 27704, "text": "python-modules" }, { "code": null, "e": 27734, "s": 27719, "text": "python-utility" }, { "code": null, "e": 27741, "s": 27734, "text": "Python" }, { "code": null, "e": 27839, "s": 27741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27871, "s": 27839, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27913, "s": 27871, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27955, "s": 27913, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28011, "s": 27955, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28038, "s": 28011, "text": "Python Classes and Objects" }, { "code": null, "e": 28077, "s": 28038, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28108, "s": 28077, "text": "Python | os.path.join() method" }, { "code": null, "e": 28137, "s": 28108, "text": "Create a directory in Python" }, { "code": null, "e": 28159, "s": 28137, "text": "Defaultdict in Python" } ]
Compressing a File in Golang - GeeksforGeeks
07 Apr, 2022 As per Wikipedia, data compression or file compression can be understood as a process of reducing the size of a particular file/folder/whatever data while still preserving the original data. Lesser file size has a lot of benefits as it will then occupy lesser storage area giving you more space for other data to occupy, transfer the file faster as the size is lesser and various other perks unlock upon file compression. The compressed files are stored in the form of compressed file extension folders such as “.zip“,”.rar“,”.tar.gz“, “.arj” and “.tgz“. Compression reduces the file size to maximum compression size. If it cannot be compressed further then the size shall remain the same and not lesser. Below are some following examples to see how compression works in Golang. What are the in-built methods we can use? How a file can be traced using its path? How can we open the file? How does compression work? Let us see the first example To compress a File in Golang, we use the gzip command. Then create a path to trace our file. Then leave the command to read our file. Below program reads in a file. It uses ioutil.ReadAll to get all the bytes from the file. After it will create a new file i.e. compressed file by replacing the extension with “gz“. Note: To cross-check you can open the compressed file using WinRar or 7-ZIp etc. Go package main // Declare all the libraries neededimport ( "bufio" "compress/gzip" "fmt" "io/ioutil" "os" "strings") func main() { // Compressing a file takes many steps // In this example we will see how to open // a file // Then read all its components // Create out own file with a gz extension // Read all bytes and copy it into our new file // Close our new file // Let us start now by checking and verifying // each step in detail // Open file on disk. // Mention the name of the text file in quoted marks // Here we have mentioned the name of the variable // which checks the file name as "name_of_file" name_of_file := "Gfg.txt" // After checking this, we would now trace the file path. // Now we would use os.Open command // This command would help us to open the file // This command takes in the path of the file as input. f, _ := os.Open("C://ProgramData//" + name_of_file) // Now let use read the bytes of the document we opened. // Create a Reader to get all the bytes from the file. read := bufio.NewReader(f) // Now we would use the variable Read All to get all the bytes // So we just used variable data which will read all the bytes data, _ := ioutil.ReadAll(read) // Now we would use the extension method // Now with the help of replace command we can // Replace txt file with gz extension // So we would now use the file name to give // this command a boost name_of_file = strings.Replace(name_of_file, ".txt", ".gz", -1) // Open file for writing // Now using the Os.create method we would use the // To store thr information of the file gz extension f, _ = os.Create("C://ProgramData//" + name_of_file) // Write compresses Data // We would use NewWriter to basically // copy all the compressed data w := gzip.NewWriter(f) // With the help of the Writer method, we would // write all the bytes in the data variable // copied from the original file w.Write(data) // We would now close the file. w.Close() // Now we would see a file with gz extension in the below path // This gz extension file we have to open using 7zip tool } Output: Executing the Program Output file having gz extension Opening the compressed file using 7-Zip Content of Compressed File – Opening in notepad Directly Here we have a random string. Basically, here the user wants to write a compressed version of this string to a file on the disk. So first he has to create a file with os.Create. Now use NewWriter to create a gzip writer targeting that file we created. Now call Write() to write bytes. Convert the string into a byte value using cast expression. Go package main // Declare all the libraries which are needed.import ( "compress/gzip" "fmt" "os") func main() { // Here we use random text // We would now put that random text into a file we created. // Once we create a random file we created, we would use // that for compression // And then we would check its output. // Now first let us create a random string variable named text // This random text will store some characters. text := "Geeks for geeks" // With the help of os.Create command let us // first open a file named "file.gz" // Open a file for writing f, _ := os.Create("C:\\ProgramData\\file.gz") // Create a gzip writer // Now we the help of the NewWriter command we simply try // to copy all the files into variable "f" // Let us name this variable p p := gzip.NewWriter(f) // Now with the help of the Write command we will // use all the bytes to write it in the file // named text. p.Write([]byte(text)) // Once we are done copying all the files // we would leave the command "close". // Close the file p.Close() // Now once we are done. To,notify our work // We would print the statement "Done" fmt.Println("Done")} Output: Executing the code File Taken Output of compressed file using 7 Zip Tool Opening the compressed file in Notepad rajeev0719singh simmytarika5 Golang-File-Handling Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language How to Parse JSON in Golang? Strings in Golang Time Durations in Golang Structures in Golang How to iterate over an Array using for loop in Golang? Rune in Golang Defer Keyword in Golang Loops in Go Language Class and Object in Golang
[ { "code": null, "e": 25729, "s": 25701, "text": "\n07 Apr, 2022" }, { "code": null, "e": 26434, "s": 25729, "text": "As per Wikipedia, data compression or file compression can be understood as a process of reducing the size of a particular file/folder/whatever data while still preserving the original data. Lesser file size has a lot of benefits as it will then occupy lesser storage area giving you more space for other data to occupy, transfer the file faster as the size is lesser and various other perks unlock upon file compression. The compressed files are stored in the form of compressed file extension folders such as “.zip“,”.rar“,”.tar.gz“, “.arj” and “.tgz“. Compression reduces the file size to maximum compression size. If it cannot be compressed further then the size shall remain the same and not lesser." }, { "code": null, "e": 26673, "s": 26434, "text": "Below are some following examples to see how compression works in Golang. What are the in-built methods we can use? How a file can be traced using its path? How can we open the file? How does compression work? Let us see the first example" }, { "code": null, "e": 26728, "s": 26673, "text": "To compress a File in Golang, we use the gzip command." }, { "code": null, "e": 26766, "s": 26728, "text": "Then create a path to trace our file." }, { "code": null, "e": 26807, "s": 26766, "text": "Then leave the command to read our file." }, { "code": null, "e": 26989, "s": 26807, "text": "Below program reads in a file. It uses ioutil.ReadAll to get all the bytes from the file. After it will create a new file i.e. compressed file by replacing the extension with “gz“. " }, { "code": null, "e": 27070, "s": 26989, "text": "Note: To cross-check you can open the compressed file using WinRar or 7-ZIp etc." }, { "code": null, "e": 27073, "s": 27070, "text": "Go" }, { "code": "package main // Declare all the libraries neededimport ( \"bufio\" \"compress/gzip\" \"fmt\" \"io/ioutil\" \"os\" \"strings\") func main() { // Compressing a file takes many steps // In this example we will see how to open // a file // Then read all its components // Create out own file with a gz extension // Read all bytes and copy it into our new file // Close our new file // Let us start now by checking and verifying // each step in detail // Open file on disk. // Mention the name of the text file in quoted marks // Here we have mentioned the name of the variable // which checks the file name as \"name_of_file\" name_of_file := \"Gfg.txt\" // After checking this, we would now trace the file path. // Now we would use os.Open command // This command would help us to open the file // This command takes in the path of the file as input. f, _ := os.Open(\"C://ProgramData//\" + name_of_file) // Now let use read the bytes of the document we opened. // Create a Reader to get all the bytes from the file. read := bufio.NewReader(f) // Now we would use the variable Read All to get all the bytes // So we just used variable data which will read all the bytes data, _ := ioutil.ReadAll(read) // Now we would use the extension method // Now with the help of replace command we can // Replace txt file with gz extension // So we would now use the file name to give // this command a boost name_of_file = strings.Replace(name_of_file, \".txt\", \".gz\", -1) // Open file for writing // Now using the Os.create method we would use the // To store thr information of the file gz extension f, _ = os.Create(\"C://ProgramData//\" + name_of_file) // Write compresses Data // We would use NewWriter to basically // copy all the compressed data w := gzip.NewWriter(f) // With the help of the Writer method, we would // write all the bytes in the data variable // copied from the original file w.Write(data) // We would now close the file. w.Close() // Now we would see a file with gz extension in the below path // This gz extension file we have to open using 7zip tool }", "e": 29310, "s": 27073, "text": null }, { "code": null, "e": 29322, "s": 29313, "text": "Output: " }, { "code": null, "e": 29346, "s": 29324, "text": "Executing the Program" }, { "code": null, "e": 29378, "s": 29346, "text": "Output file having gz extension" }, { "code": null, "e": 29422, "s": 29382, "text": "Opening the compressed file using 7-Zip" }, { "code": null, "e": 29479, "s": 29422, "text": "Content of Compressed File – Opening in notepad Directly" }, { "code": null, "e": 29826, "s": 29479, "text": "Here we have a random string. Basically, here the user wants to write a compressed version of this string to a file on the disk. So first he has to create a file with os.Create. Now use NewWriter to create a gzip writer targeting that file we created. Now call Write() to write bytes. Convert the string into a byte value using cast expression. " }, { "code": null, "e": 29831, "s": 29828, "text": "Go" }, { "code": "package main // Declare all the libraries which are needed.import ( \"compress/gzip\" \"fmt\" \"os\") func main() { // Here we use random text // We would now put that random text into a file we created. // Once we create a random file we created, we would use // that for compression // And then we would check its output. // Now first let us create a random string variable named text // This random text will store some characters. text := \"Geeks for geeks\" // With the help of os.Create command let us // first open a file named \"file.gz\" // Open a file for writing f, _ := os.Create(\"C:\\\\ProgramData\\\\file.gz\") // Create a gzip writer // Now we the help of the NewWriter command we simply try // to copy all the files into variable \"f\" // Let us name this variable p p := gzip.NewWriter(f) // Now with the help of the Write command we will // use all the bytes to write it in the file // named text. p.Write([]byte(text)) // Once we are done copying all the files // we would leave the command \"close\". // Close the file p.Close() // Now once we are done. To,notify our work // We would print the statement \"Done\" fmt.Println(\"Done\")}", "e": 31068, "s": 29831, "text": null }, { "code": null, "e": 31076, "s": 31068, "text": "Output:" }, { "code": null, "e": 31095, "s": 31076, "text": "Executing the code" }, { "code": null, "e": 31106, "s": 31095, "text": "File Taken" }, { "code": null, "e": 31153, "s": 31110, "text": "Output of compressed file using 7 Zip Tool" }, { "code": null, "e": 31192, "s": 31153, "text": "Opening the compressed file in Notepad" }, { "code": null, "e": 31210, "s": 31194, "text": "rajeev0719singh" }, { "code": null, "e": 31223, "s": 31210, "text": "simmytarika5" }, { "code": null, "e": 31244, "s": 31223, "text": "Golang-File-Handling" }, { "code": null, "e": 31251, "s": 31244, "text": "Picked" }, { "code": null, "e": 31263, "s": 31251, "text": "Go Language" }, { "code": null, "e": 31361, "s": 31263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31407, "s": 31361, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 31436, "s": 31407, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 31454, "s": 31436, "text": "Strings in Golang" }, { "code": null, "e": 31479, "s": 31454, "text": "Time Durations in Golang" }, { "code": null, "e": 31500, "s": 31479, "text": "Structures in Golang" }, { "code": null, "e": 31555, "s": 31500, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 31570, "s": 31555, "text": "Rune in Golang" }, { "code": null, "e": 31594, "s": 31570, "text": "Defer Keyword in Golang" }, { "code": null, "e": 31615, "s": 31594, "text": "Loops in Go Language" } ]
How to Calculate Correlation Between Two Columns in Pandas? - GeeksforGeeks
30 Nov, 2021 In this article, we will discuss how to calculate the correlation between two columns in pandas Correlation is used to summarize the strength and direction of the linear association between two quantitative variables. It is denoted by r and values between -1 and +1. A positive value for r indicates a positive association, and a negative value for r indicates a negative association. By using corr() function we can get the correlation between two columns in the dataframe. Syntax: dataframe[‘first_column’].corr(dataframe[‘second_column’]) where, dataframe is the input dataframe first_column is correlated with second_column of the dataframe Python3 # import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "column1": [12, 23, 45, 67], "column2": [67, 54, 32, 1], "column3": [34, 23, 56, 23]})# display dataframeprint(data) # correlation between column 1 and column2print(data['column1'].corr(data['column2'])) # correlation between column 2 and column3print(data['column2'].corr(data['column3'])) # correlation between column 1 and column3print(data['column1'].corr(data['column3'])) Output: column1 column2 column3 0 12 67 34 1 23 54 23 2 45 32 56 3 67 1 23 -0.9970476685163736 0.07346999975265099 0.0 It is also possible to get element-wise correlation for numeric valued columns using just corr() function. Syntax: dataset.corr() Python3 # import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ "column1": [12, 23, 45, 67], "column2": [67, 54, 32, 1], "column3": [34, 23, 56, 23]})# get correlation between element wiseprint(data.corr()) Output: column1 column2 column3 column1 1.000000 -0.997048 0.00000 column2 -0.997048 1.000000 0.07347 column3 0.000000 0.073470 1.00000 rkbhola5 Picked Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas 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": 25555, "s": 25527, "text": "\n30 Nov, 2021" }, { "code": null, "e": 25651, "s": 25555, "text": "In this article, we will discuss how to calculate the correlation between two columns in pandas" }, { "code": null, "e": 25940, "s": 25651, "text": "Correlation is used to summarize the strength and direction of the linear association between two quantitative variables. It is denoted by r and values between -1 and +1. A positive value for r indicates a positive association, and a negative value for r indicates a negative association." }, { "code": null, "e": 26030, "s": 25940, "text": "By using corr() function we can get the correlation between two columns in the dataframe." }, { "code": null, "e": 26038, "s": 26030, "text": "Syntax:" }, { "code": null, "e": 26097, "s": 26038, "text": "dataframe[‘first_column’].corr(dataframe[‘second_column’])" }, { "code": null, "e": 26104, "s": 26097, "text": "where," }, { "code": null, "e": 26137, "s": 26104, "text": "dataframe is the input dataframe" }, { "code": null, "e": 26200, "s": 26137, "text": "first_column is correlated with second_column of the dataframe" }, { "code": null, "e": 26208, "s": 26200, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ \"column1\": [12, 23, 45, 67], \"column2\": [67, 54, 32, 1], \"column3\": [34, 23, 56, 23]})# display dataframeprint(data) # correlation between column 1 and column2print(data['column1'].corr(data['column2'])) # correlation between column 2 and column3print(data['column2'].corr(data['column3'])) # correlation between column 1 and column3print(data['column1'].corr(data['column3']))", "e": 26692, "s": 26208, "text": null }, { "code": null, "e": 26700, "s": 26692, "text": "Output:" }, { "code": null, "e": 26887, "s": 26700, "text": " column1 column2 column3\n0 12 67 34\n1 23 54 23\n2 45 32 56\n3 67 1 23\n-0.9970476685163736\n0.07346999975265099\n0.0" }, { "code": null, "e": 26994, "s": 26887, "text": "It is also possible to get element-wise correlation for numeric valued columns using just corr() function." }, { "code": null, "e": 27002, "s": 26994, "text": "Syntax:" }, { "code": null, "e": 27017, "s": 27002, "text": "dataset.corr()" }, { "code": null, "e": 27025, "s": 27017, "text": "Python3" }, { "code": "# import pandas moduleimport pandas as pd # create dataframe with 3 columnsdata = pd.DataFrame({ \"column1\": [12, 23, 45, 67], \"column2\": [67, 54, 32, 1], \"column3\": [34, 23, 56, 23]})# get correlation between element wiseprint(data.corr())", "e": 27274, "s": 27025, "text": null }, { "code": null, "e": 27282, "s": 27274, "text": "Output:" }, { "code": null, "e": 27430, "s": 27282, "text": " column1 column2 column3\ncolumn1 1.000000 -0.997048 0.00000\ncolumn2 -0.997048 1.000000 0.07347\ncolumn3 0.000000 0.073470 1.00000" }, { "code": null, "e": 27439, "s": 27430, "text": "rkbhola5" }, { "code": null, "e": 27446, "s": 27439, "text": "Picked" }, { "code": null, "e": 27470, "s": 27446, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27502, "s": 27470, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 27516, "s": 27502, "text": "Python-pandas" }, { "code": null, "e": 27523, "s": 27516, "text": "Python" }, { "code": null, "e": 27621, "s": 27523, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27653, "s": 27621, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27695, "s": 27653, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27737, "s": 27695, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27793, "s": 27737, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27820, "s": 27793, "text": "Python Classes and Objects" }, { "code": null, "e": 27851, "s": 27820, "text": "Python | os.path.join() method" }, { "code": null, "e": 27890, "s": 27851, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27919, "s": 27890, "text": "Create a directory in Python" }, { "code": null, "e": 27941, "s": 27919, "text": "Defaultdict in Python" } ]
Sets in JavaScript - GeeksforGeeks
28 Apr, 2022 In this article, we would be discussing the Set object provided by ES6. A set is a collection of items which are unique i.e no element can be repeated. Set in ES6 are ordered: elements of the set can be iterated in the insertion order. Set can store any types of values whether primitive or objects.Syntax: new Set([it]); Parameter: it - It is an iterable object whose all elements are added to the new set created, If the parameter is not specified or null is passed then a new set created is empty. Returns: A new set object Now lets create some sets: Example: Javascript // it contains// ["sumit","amit","anil","anish"]var set1 = new Set(["sumit","sumit","amit","anil","anish"]); // it contains 'f', 'o', 'd'var set2 = new Set("fooooooood"); // it contains [10, 20, 30, 40]var set3 = new Set([10, 20, 30, 30, 40, 40]); // it is an empty setvar set4 = new Set(); Properties: Set.prototype.size – It returns the number of elements in the Set.Methods: Set.prototype.add() – It adds the new element with a specified value at the end of the Set object.Syntax: set1.add(val); Parameter: val - It is a value to be added to the set. Returns: The set object Example: Javascript // using Set.prototype.add(value)// creating an empty setvar set1 = new Set(); // set contains 10, 20set1.add(10);set1.add(20); // As this method returns// the set object hence chaining// of add method can be done.set1.add(30).add(40).add(50); // prints 10, 20, 30, 40, 50console.log(set1); Set.prototype.delete() – It deletes an element with the specified value from the Set object. Syntax: set1.delete(val); Parameter: val - It is a value to be deleted from the set. Returns: true if the value is successfully deleted from the set else returns false. Example: Javascript // using Set.prototype.delete(value)// creating set it contains// f, o , d, i, evar set1 = new Set("foooodiiiieee"); // deleting e from the set// it prints trueconsole.log(set1.delete('e')); // set contains f, o, d, iconsole.log(set1); // deleting an element which is// not in the set// prints falseconsole.log(set1.delete('g')); Set.prototype.clear() – It removes all the element from the set. Syntax: set1.clear(); Parameter: No parameters Returns: undefined Example: Javascript // Using Set.prototype.clear()// creating a setvar set2 = new Set([10, 20, 30, 40, 50]); // prints {10, 20, 30, 40, 50}console.log(set2); // clearing set2set2.clear() // prints {}console.log(set2); Set.prototype.entries() – It returns an iterator object which contains an array having the entries of the set, in the insertion order. Syntax: set1.entries(); Parameter: No parameters Returns: It returns an iterator object that contains an array of [value, value] for every element of the set, in the insertion order. Example Javascript // Using Set.prototype.entries()// creating setvar set1 = new Set(); // adding element to the setset1.add(50);set1.add(30);set1.add(40);set1.add(20);set1.add(10); // using entries to get iteratorvar getEntriesArry = set1.entries(); // each iterator is array of [value, value]// prints [50, 50]console.log(getEntriesArry.next().value); // prints [30, 30]console.log(getEntriesArry.next().value); // prints [40, 40]console.log(getEntriesArry.next().value); Set.prototype.has() – It returns true if the specified value is present in the Set object. Syntax: set1.has(val); Parameter: val - The value to be searched in the Set Returns: True if the value is present else it returns false. Example: Javascript // Using Set.prototype.has()// creating setvar set1 = new Set(); // adding element to the setset1.add(50);set1.add(30); // prints trueconsole.log(set1.has(50)); // prints falseconsole.log(set1.has(10)); Set.prototype.values() – It returns all the values from the Set in the same insertion order. Syntax: set1.values(); Parameter: No parameters Returns: An iterator object that contains all the values of the set in the same order as they are inserted. Set.prototype.keys() – It also returns all the values from the Set in the insertion order. Note: – It is similar to the values() in case of Sets Syntax: set1.keys(); Parameter: No parameters Returns: An iterator object that contains all the values of the set in the same order as they are inserted. Example: Javascript // Using Set.prototype.values()// Using Set.prototype.keys()// creating setvar set1 = new Set(); // adding element to the setset1.add(50);set1.add(30);set1.add(40);set1.add("Geeks");set1.add("GFG"); // getting all the valuesvar getValues = set1.values(); // prints a SetIterator// that contains {50, 30, 40, "Geeks", "GFG"}console.log(getValues); // getting all the valuesvar getKeys = set1.keys(); // prints a SetIterator// that contains {50, 30, 40, "Geeks", "GFG"}console.log(getKeys); Set.prototype.forEach() – It executes the given function once for every element in the Set, in the insertion order. Syntax: set1.forEach(callback[,thisargument]); Parameter: callback - It is a function which is to be executed for each element of the Set. thisargument - Value to be used as this when executing the callback. Returns: Undefined The callback function is provided with three parameters as follows: the element keythe element valuethe Set object to be traversed The callback function is provided with three parameters as follows: the element keythe element valuethe Set object to be traversed the element key the element value the Set object to be traversed Set.prototype[@@iterator]() – It returns a Set iterator function which is values() function by default. Syntax: set1[Symbol.iterator](); Parameter: No parameters Returns: A Set iterator function and it is values() by default. Example: Javascript // using Set.prototype[@@Iterator]()var set1 = new Set(["sumit","sumit","amit","anish"]); var getit = set1[Symbol.iterator](); // Printing the values in the// iterator "getit" // prints {value: "sumit", done: false}console.log(getit.next()); // prints {value: "amit", done: false}console.log(getit.next()); // prints {value: "anish", done: false}console.log(getit.next()); // prints {value: undefined, done: true}console.log(getit.next()); Set Operations: subSet() – It returns true if Set A is a subset of Set B. A Set A is said to be a subset of Set B, if all the elements of Set A is also present in Set B. Now lets implement and use the subset function. Example: Javascript // check whether the set on which the// method is invoked is the subset of// otherset or notSet.prototype.subSet = function(otherSet){ // if size of this set is greater // than otherSet then it can't be // a subset if(this.size > otherSet.size) return false; else { for(var elem of this) { // if any of the element of // this is not present in the // otherset then return false if(!otherSet.has(elem)) return false; } return true; }} // using the subSet function // Declaring different setsvar setA = new Set([10, 20, 30]);var setB = new Set([50, 60, 10, 20, 30, 40]);var setC = new Set([10, 30, 40, 50]); // prints trueconsole.log(setA.subSet(setB)); // prints falseconsole.log(setA.subSet(setC)); // prints trueconsole.log(setC.subSet(setB)); union() – It returns a Set which consists of union of Set A and Set B A Set is said to be a union of two set, if it contains all element of Set A as well as all elements of Set B, but it does’nt contains duplicate elements. For Example: If an element is present in both Set A and Set B then union of Set A and B will contain the single copy of the element. Let implement and use the union function Example: Javascript // Perform union operation between// called set and otherSetSet.prototype.union = function(otherSet){ // creating new set to store union var unionSet = new Set(); // iterate over the values and add // it to unionSet for (var elem of this) { unionSet.add(elem); } // iterate over the values and add it to // the unionSet for(var elem of otherSet) unionSet.add(elem); // return the values of unionSet return unionSet;} // using the union function// Declaring values for set1 and set2var set1 = new Set([10, 20, 30, 40, 50]);var set2 = new Set([40, 50, 60, 70, 80]); // performing union operation// and storing the resultant set in// unionSetvar unionSet = set1.union(set2); // prints [10, 20, 30, 40, 50, 60, 70, 80]console.log(unionSet.values()); intersection() – It returns the intersection of Set A and Set B. A Set is said to be the intersection of Set A and B if contains element which is present both in Set A and Set B. Let implement and use the intersection function Example: Javascript // Performs intersection operation between// called set and otherSetSet.prototype.intersection = function(otherSet){ // creating new set to store intersection var intersectionSet = new Set(); // Iterate over the values for(var elem of otherSet) { // if the other set contains a // similar value as of value[i] // then add it to intersectionSet if(this.has(elem)) intersectionSet.add(elem); } // return values of intersectionSetreturn intersectionSet; }// using intersection function// Declaring values for set1 and set2var set1 = new Set([10, 20, 30, 40, 50]);var set2 = new Set([40, 50, 60, 70, 80]); // performing union operation// and storing the resultant set in// intersectionsetvar intersectionSet = set1.intersection(set2); // prints {40, 50}console.log(intersectionSet.values()); difference() – It returns the Set which contains difference of Set A and Set B. A Set is said to be a difference of Set A and B if it contains set of element e which are present in Set A but not in Set B. Let’s implement and use the difference function Example: Javascript // Performs difference operation between// called set and otherSetSet.prototype.difference = function(otherSet){ // creating new set to store difference var differenceSet = new Set(); // iterate over the values for(var elem of this) { // if the value[i] is not present // in otherSet add to the differenceSet if(!otherSet.has(elem)) differenceSet.add(elem); } // returns values of differenceSet return differenceSet;} // using difference function// Declaring values for set1 and set2var set1 = new Set([10, 20, 30, 40, 50]);var set2 = new Set([40, 50, 60, 70, 80]); // performing union operation// and storing the resultant set in// intersectionsetvar differenceSet = set1.difference(set2); // prints {10, 20, 30}console.log(differenceSet); Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/SetThis article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. Akanksha_Rai nidhi_biet clintra simmytarika5 jochenhansoul surinderdawra388 JavaScript-ES JavaScript-Misc JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request JavaScript | console.log() with Examples How to read a local text file using JavaScript? Node.js | fs.writeFileSync() Method
[ { "code": null, "e": 25691, "s": 25663, "text": "\n28 Apr, 2022" }, { "code": null, "e": 26000, "s": 25691, "text": "In this article, we would be discussing the Set object provided by ES6. A set is a collection of items which are unique i.e no element can be repeated. Set in ES6 are ordered: elements of the set can be iterated in the insertion order. Set can store any types of values whether primitive or objects.Syntax: " }, { "code": null, "e": 26226, "s": 26000, "text": "new Set([it]);\n\nParameter: \nit - It is an iterable object whose all elements are \nadded to the new set created, \nIf the parameter is not specified or null is passed \nthen a new set created is empty.\n\nReturns:\nA new set object" }, { "code": null, "e": 26264, "s": 26226, "text": "Now lets create some sets: Example: " }, { "code": null, "e": 26275, "s": 26264, "text": "Javascript" }, { "code": "// it contains// [\"sumit\",\"amit\",\"anil\",\"anish\"]var set1 = new Set([\"sumit\",\"sumit\",\"amit\",\"anil\",\"anish\"]); // it contains 'f', 'o', 'd'var set2 = new Set(\"fooooooood\"); // it contains [10, 20, 30, 40]var set3 = new Set([10, 20, 30, 30, 40, 40]); // it is an empty setvar set4 = new Set();", "e": 26568, "s": 26275, "text": null }, { "code": null, "e": 26657, "s": 26568, "text": "Properties: Set.prototype.size – It returns the number of elements in the Set.Methods: " }, { "code": null, "e": 26765, "s": 26657, "text": "Set.prototype.add() – It adds the new element with a specified value at the end of the Set object.Syntax: " }, { "code": null, "e": 26862, "s": 26765, "text": "set1.add(val);\n\nParameter:\nval - It is a value to be added to the set.\n\nReturns: \nThe set object" }, { "code": null, "e": 26872, "s": 26862, "text": "Example: " }, { "code": null, "e": 26883, "s": 26872, "text": "Javascript" }, { "code": "// using Set.prototype.add(value)// creating an empty setvar set1 = new Set(); // set contains 10, 20set1.add(10);set1.add(20); // As this method returns// the set object hence chaining// of add method can be done.set1.add(30).add(40).add(50); // prints 10, 20, 30, 40, 50console.log(set1);", "e": 27174, "s": 26883, "text": null }, { "code": null, "e": 27277, "s": 27174, "text": "Set.prototype.delete() – It deletes an element with the specified value from the Set object. Syntax: " }, { "code": null, "e": 27441, "s": 27277, "text": "set1.delete(val);\n\nParameter:\nval - It is a value to be deleted from the set.\n\nReturns: \ntrue if the value is successfully deleted from the set else returns false." }, { "code": null, "e": 27451, "s": 27441, "text": "Example: " }, { "code": null, "e": 27462, "s": 27451, "text": "Javascript" }, { "code": "// using Set.prototype.delete(value)// creating set it contains// f, o , d, i, evar set1 = new Set(\"foooodiiiieee\"); // deleting e from the set// it prints trueconsole.log(set1.delete('e')); // set contains f, o, d, iconsole.log(set1); // deleting an element which is// not in the set// prints falseconsole.log(set1.delete('g'));", "e": 27792, "s": 27462, "text": null }, { "code": null, "e": 27867, "s": 27792, "text": "Set.prototype.clear() – It removes all the element from the set. Syntax: " }, { "code": null, "e": 27928, "s": 27867, "text": "set1.clear();\n\nParameter:\nNo parameters\n\nReturns: \nundefined" }, { "code": null, "e": 27938, "s": 27928, "text": "Example: " }, { "code": null, "e": 27949, "s": 27938, "text": "Javascript" }, { "code": "// Using Set.prototype.clear()// creating a setvar set2 = new Set([10, 20, 30, 40, 50]); // prints {10, 20, 30, 40, 50}console.log(set2); // clearing set2set2.clear() // prints {}console.log(set2);", "e": 28147, "s": 27949, "text": null }, { "code": null, "e": 28290, "s": 28147, "text": "Set.prototype.entries() – It returns an iterator object which contains an array having the entries of the set, in the insertion order. Syntax:" }, { "code": null, "e": 28470, "s": 28290, "text": "set1.entries();\n\nParameter:\nNo parameters\n\nReturns: \nIt returns an iterator object that contains an\narray of [value, value] for every \nelement of the set, in the insertion order. " }, { "code": null, "e": 28479, "s": 28470, "text": "Example " }, { "code": null, "e": 28490, "s": 28479, "text": "Javascript" }, { "code": "// Using Set.prototype.entries()// creating setvar set1 = new Set(); // adding element to the setset1.add(50);set1.add(30);set1.add(40);set1.add(20);set1.add(10); // using entries to get iteratorvar getEntriesArry = set1.entries(); // each iterator is array of [value, value]// prints [50, 50]console.log(getEntriesArry.next().value); // prints [30, 30]console.log(getEntriesArry.next().value); // prints [40, 40]console.log(getEntriesArry.next().value);", "e": 28945, "s": 28490, "text": null }, { "code": null, "e": 29046, "s": 28945, "text": "Set.prototype.has() – It returns true if the specified value is present in the Set object. Syntax: " }, { "code": null, "e": 29178, "s": 29046, "text": "set1.has(val);\n\nParameter:\nval - The value to be searched in the Set\n\nReturns: \nTrue if the value is present else it returns false." }, { "code": null, "e": 29188, "s": 29178, "text": "Example: " }, { "code": null, "e": 29199, "s": 29188, "text": "Javascript" }, { "code": "// Using Set.prototype.has()// creating setvar set1 = new Set(); // adding element to the setset1.add(50);set1.add(30); // prints trueconsole.log(set1.has(50)); // prints falseconsole.log(set1.has(10));", "e": 29414, "s": 29199, "text": null }, { "code": null, "e": 29517, "s": 29414, "text": "Set.prototype.values() – It returns all the values from the Set in the same insertion order. Syntax: " }, { "code": null, "e": 29670, "s": 29517, "text": "set1.values();\n\nParameter:\nNo parameters\n\nReturns: \nAn iterator object that contains all the values of the set in the same order \nas they are inserted. " }, { "code": null, "e": 29825, "s": 29670, "text": "Set.prototype.keys() – It also returns all the values from the Set in the insertion order. Note: – It is similar to the values() in case of Sets Syntax: " }, { "code": null, "e": 29976, "s": 29825, "text": "set1.keys();\n\nParameter:\nNo parameters\n\nReturns: \nAn iterator object that contains all the \nvalues of the set in the same order\nas they are inserted. " }, { "code": null, "e": 29986, "s": 29976, "text": "Example: " }, { "code": null, "e": 29997, "s": 29986, "text": "Javascript" }, { "code": "// Using Set.prototype.values()// Using Set.prototype.keys()// creating setvar set1 = new Set(); // adding element to the setset1.add(50);set1.add(30);set1.add(40);set1.add(\"Geeks\");set1.add(\"GFG\"); // getting all the valuesvar getValues = set1.values(); // prints a SetIterator// that contains {50, 30, 40, \"Geeks\", \"GFG\"}console.log(getValues); // getting all the valuesvar getKeys = set1.keys(); // prints a SetIterator// that contains {50, 30, 40, \"Geeks\", \"GFG\"}console.log(getKeys);", "e": 30486, "s": 29997, "text": null }, { "code": null, "e": 30612, "s": 30486, "text": "Set.prototype.forEach() – It executes the given function once for every element in the Set, in the insertion order. Syntax: " }, { "code": null, "e": 30834, "s": 30612, "text": "set1.forEach(callback[,thisargument]);\n\nParameter:\ncallback - It is a function which is to be executed for each element of the Set.\nthisargument - Value to be used as this when executing the callback.\n\nReturns: \nUndefined" }, { "code": null, "e": 30965, "s": 30834, "text": "The callback function is provided with three parameters as follows: the element keythe element valuethe Set object to be traversed" }, { "code": null, "e": 31096, "s": 30965, "text": "The callback function is provided with three parameters as follows: the element keythe element valuethe Set object to be traversed" }, { "code": null, "e": 31112, "s": 31096, "text": "the element key" }, { "code": null, "e": 31130, "s": 31112, "text": "the element value" }, { "code": null, "e": 31161, "s": 31130, "text": "the Set object to be traversed" }, { "code": null, "e": 31275, "s": 31161, "text": "Set.prototype[@@iterator]() – It returns a Set iterator function which is values() function by default. Syntax: " }, { "code": null, "e": 31392, "s": 31275, "text": "set1[Symbol.iterator]();\n\nParameter:\nNo parameters\n\nReturns: \nA Set iterator function and it is values() by default." }, { "code": null, "e": 31402, "s": 31392, "text": "Example: " }, { "code": null, "e": 31413, "s": 31402, "text": "Javascript" }, { "code": "// using Set.prototype[@@Iterator]()var set1 = new Set([\"sumit\",\"sumit\",\"amit\",\"anish\"]); var getit = set1[Symbol.iterator](); // Printing the values in the// iterator \"getit\" // prints {value: \"sumit\", done: false}console.log(getit.next()); // prints {value: \"amit\", done: false}console.log(getit.next()); // prints {value: \"anish\", done: false}console.log(getit.next()); // prints {value: undefined, done: true}console.log(getit.next());", "e": 31853, "s": 31413, "text": null }, { "code": null, "e": 31871, "s": 31853, "text": "Set Operations: " }, { "code": null, "e": 32084, "s": 31871, "text": "subSet() – It returns true if Set A is a subset of Set B. A Set A is said to be a subset of Set B, if all the elements of Set A is also present in Set B. Now lets implement and use the subset function. Example: " }, { "code": null, "e": 32095, "s": 32084, "text": "Javascript" }, { "code": "// check whether the set on which the// method is invoked is the subset of// otherset or notSet.prototype.subSet = function(otherSet){ // if size of this set is greater // than otherSet then it can't be // a subset if(this.size > otherSet.size) return false; else { for(var elem of this) { // if any of the element of // this is not present in the // otherset then return false if(!otherSet.has(elem)) return false; } return true; }} // using the subSet function // Declaring different setsvar setA = new Set([10, 20, 30]);var setB = new Set([50, 60, 10, 20, 30, 40]);var setC = new Set([10, 30, 40, 50]); // prints trueconsole.log(setA.subSet(setB)); // prints falseconsole.log(setA.subSet(setC)); // prints trueconsole.log(setC.subSet(setB));", "e": 32956, "s": 32095, "text": null }, { "code": null, "e": 33365, "s": 32956, "text": "union() – It returns a Set which consists of union of Set A and Set B A Set is said to be a union of two set, if it contains all element of Set A as well as all elements of Set B, but it does’nt contains duplicate elements. For Example: If an element is present in both Set A and Set B then union of Set A and B will contain the single copy of the element. Let implement and use the union function Example: " }, { "code": null, "e": 33376, "s": 33365, "text": "Javascript" }, { "code": "// Perform union operation between// called set and otherSetSet.prototype.union = function(otherSet){ // creating new set to store union var unionSet = new Set(); // iterate over the values and add // it to unionSet for (var elem of this) { unionSet.add(elem); } // iterate over the values and add it to // the unionSet for(var elem of otherSet) unionSet.add(elem); // return the values of unionSet return unionSet;} // using the union function// Declaring values for set1 and set2var set1 = new Set([10, 20, 30, 40, 50]);var set2 = new Set([40, 50, 60, 70, 80]); // performing union operation// and storing the resultant set in// unionSetvar unionSet = set1.union(set2); // prints [10, 20, 30, 40, 50, 60, 70, 80]console.log(unionSet.values());", "e": 34176, "s": 33376, "text": null }, { "code": null, "e": 34414, "s": 34176, "text": "intersection() – It returns the intersection of Set A and Set B. A Set is said to be the intersection of Set A and B if contains element which is present both in Set A and Set B. Let implement and use the intersection function Example: " }, { "code": null, "e": 34425, "s": 34414, "text": "Javascript" }, { "code": "// Performs intersection operation between// called set and otherSetSet.prototype.intersection = function(otherSet){ // creating new set to store intersection var intersectionSet = new Set(); // Iterate over the values for(var elem of otherSet) { // if the other set contains a // similar value as of value[i] // then add it to intersectionSet if(this.has(elem)) intersectionSet.add(elem); } // return values of intersectionSetreturn intersectionSet; }// using intersection function// Declaring values for set1 and set2var set1 = new Set([10, 20, 30, 40, 50]);var set2 = new Set([40, 50, 60, 70, 80]); // performing union operation// and storing the resultant set in// intersectionsetvar intersectionSet = set1.intersection(set2); // prints {40, 50}console.log(intersectionSet.values());", "e": 35286, "s": 34425, "text": null }, { "code": null, "e": 35550, "s": 35286, "text": "difference() – It returns the Set which contains difference of Set A and Set B. A Set is said to be a difference of Set A and B if it contains set of element e which are present in Set A but not in Set B. Let’s implement and use the difference function Example: " }, { "code": null, "e": 35561, "s": 35550, "text": "Javascript" }, { "code": "// Performs difference operation between// called set and otherSetSet.prototype.difference = function(otherSet){ // creating new set to store difference var differenceSet = new Set(); // iterate over the values for(var elem of this) { // if the value[i] is not present // in otherSet add to the differenceSet if(!otherSet.has(elem)) differenceSet.add(elem); } // returns values of differenceSet return differenceSet;} // using difference function// Declaring values for set1 and set2var set1 = new Set([10, 20, 30, 40, 50]);var set2 = new Set([40, 50, 60, 70, 80]); // performing union operation// and storing the resultant set in// intersectionsetvar differenceSet = set1.difference(set2); // prints {10, 20, 30}console.log(differenceSet);", "e": 36362, "s": 35561, "text": null }, { "code": null, "e": 36874, "s": 36362, "text": "Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/SetThis article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 37093, "s": 36874, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 37106, "s": 37093, "text": "Akanksha_Rai" }, { "code": null, "e": 37117, "s": 37106, "text": "nidhi_biet" }, { "code": null, "e": 37125, "s": 37117, "text": "clintra" }, { "code": null, "e": 37138, "s": 37125, "text": "simmytarika5" }, { "code": null, "e": 37152, "s": 37138, "text": "jochenhansoul" }, { "code": null, "e": 37169, "s": 37152, "text": "surinderdawra388" }, { "code": null, "e": 37183, "s": 37169, "text": "JavaScript-ES" }, { "code": null, "e": 37199, "s": 37183, "text": "JavaScript-Misc" }, { "code": null, "e": 37210, "s": 37199, "text": "JavaScript" }, { "code": null, "e": 37308, "s": 37210, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37348, "s": 37308, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 37393, "s": 37348, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 37454, "s": 37393, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 37526, "s": 37454, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 37578, "s": 37526, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 37624, "s": 37578, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 37665, "s": 37624, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 37706, "s": 37665, "text": "JavaScript | console.log() with Examples" }, { "code": null, "e": 37754, "s": 37706, "text": "How to read a local text file using JavaScript?" } ]
XOR of pairwise sum of every unordered pairs in an array - GeeksforGeeks
24 Nov, 2021 Given an array arr[] of length N, the task is to find the XOR of pairwise sum of every possible unordered pairs of the array. The unordered pairs sum is defined as follows – XOR of pairwise sum = (A[0] + A[1]) ^ (A[0] + A[2]) ^ ...(A[0] + A[N]) ^ (A[1] + A[2]) ^ ...(A[1] + A[N]) ^ ....... (A[N-1] + A[N]) Notice that after including A[0] and A[1] as pairs, then A[1] and A[0] are not included. Examples: Input: arr[] = {1, 2} Output: 3 Explanation: There is only one unordered pair. That is (1, 2)Input: arr[] = {1, 2, 3} Output: 2 Explanation: Unordered pairs of the numbers – {(1, 2), (1, 3), (2, 3)} XOR of unordered pairswise sum – => (1 + 2) ^ (1 + 3) ^ (2 + 3) => 3 ^ 4 ^ 5 => 2 Naive Approach: The idea is to find every possible unordered pair with the help of the two loops and find the XOR of these pairs.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find XOR of// pairwise sum of every unordered// pairs in an array #include <bits/stdc++.h> using namespace std; // Function to find XOR of pairwise// sum of every unordered pairsint xorOfSum(int a[], int n){ int answer = 0; // Loop to choose every possible // pairs in the array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) answer ^= (a[i] + a[j]); } return answer;} // Driver Codeint main(){ int n = 3; int A[n] = { 1, 2, 3 }; cout << xorOfSum(A, n); return 0;} // Java implementation to find XOR of// pairwise sum of every unordered// pairs in an arrayclass GFG{ // Function to find XOR of pairwise// sum of every unordered pairsstatic int xorOfSum(int a[], int n){ int answer = 0; // Loop to choose every possible // pairs in the array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) answer ^= (a[i] + a[j]); } return answer;} // Driver Codepublic static void main(String[] args){ int n = 3; int A[] = { 1, 2, 3 }; System.out.print(xorOfSum(A, n));}} // This code is contributed by PrinciRaj1992 # Python3 implementation to find XOR of# pairwise sum of every unordered# pairs in an array # Function to find XOR of pairwise# sum of every unordered pairsdef xorOfSum(a, n): answer = 0 # Loop to choose every possible # pairs in the array for i in range(n): for j in range(i + 1, n): answer ^= (a[i] + a[j]) return answer # Driver Codeif __name__ == '__main__': n = 3 A=[1, 2, 3] print(xorOfSum(A, n)) # This code is contributed by mohit kumar 29 // C# implementation to find XOR of// pairwise sum of every unordered// pairs in an arrayusing System;using System.Collections.Generic; class GFG{ // Function to find XOR of pairwise// sum of every unordered pairsstatic int xorOfSum(int []a, int n){ int answer = 0; // Loop to choose every possible // pairs in the array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) answer ^= (a[i] + a[j]); } return answer;} // Driver Codepublic static void Main(String[] args){ int n = 3; int []A = { 1, 2, 3 }; Console.Write(xorOfSum(A, n));}} // This code is contributed by PrinciRaj1992 <script>// JavaScript implementation to find XOR of// pairwise sum of every unordered// pairs in an array // Function to find XOR of pairwise// sum of every unordered pairsfunction xorOfSum(a, n){ let answer = 0; // Loop to choose every possible // pairs in the array for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) answer ^= (a[i] + a[j]); } return answer;} // Driver Code let n = 3; let A = [ 1, 2, 3 ]; document.write(xorOfSum(A, n)); // This code is contributed by Surbhi Tyagi </script> 2 Efficient Approach: For obtaining Kth bit of the final xor value we see in all the pair-sums, that kth bit of them is set or not. If there are even a number of pairs that have the Kth bit set, then for the Kth bit, their xor is zero else one. For finding count of pair sums having Kth bit set, we notice that we can mod all array elements by 2(K+1). This is because X and Y belong to input array and Sum = X + Y. Then X + Y can add up to have their Kth bit set which means Sum >= 2K. It can also be observed that they can have a carryover from addition which makes numbers in the range [2(K+1), 2(K+1) + 2K) have their Kth bit not set. So we only care about the Kth and (K+1)th bit of all the numbers to check the XOR of Kth bit. After the mod operation is performed, for sum to have kth bit set, its value will be in range – [2K, 2(K+1) ) U [2(K+1) + 2K, Max-Value-Sum-Can-Take ]. To find the numbers in the said range, make another array B containing modded array elements of arr[], and sort them. Then Sum can be assumed as Sum = Bi + Bj. Finally, find the maximum bound of j using binary search (built-in lower_bound in C++). Fix i and since the array is sorted find the last j that satisfies the given condition and all the numbers in the range of indices can be added to the count to check the xor. Auxiliary Space: O(1)Below is the implementation of the above approach: C++ // C++ implementation to find XOR of// pairwise sum of every unordered// pairs in an array #include <bits/stdc++.h> using namespace std; // Function to find XOR of pairwise// sum of every unordered pairsint xorOfSum(int a[], int n){ int i, j, k; // Sort the array sort(a, a + n); int ans = 0; // Array elements are not greater // than 1e7 so 27 bits are suffice for (k = 0; k < 27; ++k) { // Modded elements of array vector<int> b(n); // Loop to find the modded // elements of array for (i = 0; i < n; i++) b[i] = a[i] % (1 << (k + 1)); // Sort the modded array sort(b.begin(), b.end()); int cnt = 0; for (i = 0; i < n; i++) { // finding the bound for j // for given i using binary search int l = lower_bound(b.begin() + i + 1, b.end(), (1 << k) - b[i]) - b.begin(); int r = lower_bound(b.begin() + i + 1, b.end(), (1 << (k + 1)) - b[i]) - b.begin(); // All the numbers in the range // of indices can be added to the // count to check the xor. cnt += r - l; l = lower_bound(b.begin() + i + 1, b.end(), (1 << (k + 1)) + (1 << k) - b[i]) - b.begin(); cnt += n - l; } // Remainder of cnt * kth power // of 2 added to the xor value ans += (cnt % 2) * 1LL * (1 << k); } return ans;} // Driver Codeint main(){ int n = 3; int A[n] = { 1, 2, 3 }; cout << xorOfSum(A, n); return 0;} 2 Performance Analysis: Time complexity : O(N * log(max(A))*log(N) Auxiliary Space: O(N) Outermost loop runs for log(max(A)) times and for each loop we create and sort array b ,which consists of N elements ,hence complexity is O(N*log(N)*log(max(A))) mohit kumar 29 princiraj1992 coder72 surbhityagi15 subham348 Bitwise-XOR Algorithms Bit Magic Competitive Programming Greedy Mathematical Searching Searching Greedy Mathematical Bit Magic Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 25943, "s": 25915, "text": "\n24 Nov, 2021" }, { "code": null, "e": 26119, "s": 25943, "text": "Given an array arr[] of length N, the task is to find the XOR of pairwise sum of every possible unordered pairs of the array. The unordered pairs sum is defined as follows – " }, { "code": null, "e": 26359, "s": 26119, "text": "XOR of pairwise sum = (A[0] + A[1]) ^\n (A[0] + A[2]) ^ ...(A[0] + A[N]) ^\n (A[1] + A[2]) ^ ...(A[1] + A[N]) ^\n .......\n (A[N-1] + A[N])\n\nNotice that after including A[0] and A[1] \nas pairs, then A[1] and A[0] are not included." }, { "code": null, "e": 26371, "s": 26359, "text": "Examples: " }, { "code": null, "e": 26654, "s": 26371, "text": "Input: arr[] = {1, 2} Output: 3 Explanation: There is only one unordered pair. That is (1, 2)Input: arr[] = {1, 2, 3} Output: 2 Explanation: Unordered pairs of the numbers – {(1, 2), (1, 3), (2, 3)} XOR of unordered pairswise sum – => (1 + 2) ^ (1 + 3) ^ (2 + 3) => 3 ^ 4 ^ 5 => 2 " }, { "code": null, "e": 26837, "s": 26656, "text": "Naive Approach: The idea is to find every possible unordered pair with the help of the two loops and find the XOR of these pairs.Below is the implementation of the above approach: " }, { "code": null, "e": 26841, "s": 26837, "text": "C++" }, { "code": null, "e": 26846, "s": 26841, "text": "Java" }, { "code": null, "e": 26854, "s": 26846, "text": "Python3" }, { "code": null, "e": 26857, "s": 26854, "text": "C#" }, { "code": null, "e": 26868, "s": 26857, "text": "Javascript" }, { "code": "// C++ implementation to find XOR of// pairwise sum of every unordered// pairs in an array #include <bits/stdc++.h> using namespace std; // Function to find XOR of pairwise// sum of every unordered pairsint xorOfSum(int a[], int n){ int answer = 0; // Loop to choose every possible // pairs in the array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) answer ^= (a[i] + a[j]); } return answer;} // Driver Codeint main(){ int n = 3; int A[n] = { 1, 2, 3 }; cout << xorOfSum(A, n); return 0;}", "e": 27428, "s": 26868, "text": null }, { "code": "// Java implementation to find XOR of// pairwise sum of every unordered// pairs in an arrayclass GFG{ // Function to find XOR of pairwise// sum of every unordered pairsstatic int xorOfSum(int a[], int n){ int answer = 0; // Loop to choose every possible // pairs in the array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) answer ^= (a[i] + a[j]); } return answer;} // Driver Codepublic static void main(String[] args){ int n = 3; int A[] = { 1, 2, 3 }; System.out.print(xorOfSum(A, n));}} // This code is contributed by PrinciRaj1992", "e": 28035, "s": 27428, "text": null }, { "code": "# Python3 implementation to find XOR of# pairwise sum of every unordered# pairs in an array # Function to find XOR of pairwise# sum of every unordered pairsdef xorOfSum(a, n): answer = 0 # Loop to choose every possible # pairs in the array for i in range(n): for j in range(i + 1, n): answer ^= (a[i] + a[j]) return answer # Driver Codeif __name__ == '__main__': n = 3 A=[1, 2, 3] print(xorOfSum(A, n)) # This code is contributed by mohit kumar 29", "e": 28528, "s": 28035, "text": null }, { "code": "// C# implementation to find XOR of// pairwise sum of every unordered// pairs in an arrayusing System;using System.Collections.Generic; class GFG{ // Function to find XOR of pairwise// sum of every unordered pairsstatic int xorOfSum(int []a, int n){ int answer = 0; // Loop to choose every possible // pairs in the array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) answer ^= (a[i] + a[j]); } return answer;} // Driver Codepublic static void Main(String[] args){ int n = 3; int []A = { 1, 2, 3 }; Console.Write(xorOfSum(A, n));}} // This code is contributed by PrinciRaj1992", "e": 29183, "s": 28528, "text": null }, { "code": "<script>// JavaScript implementation to find XOR of// pairwise sum of every unordered// pairs in an array // Function to find XOR of pairwise// sum of every unordered pairsfunction xorOfSum(a, n){ let answer = 0; // Loop to choose every possible // pairs in the array for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) answer ^= (a[i] + a[j]); } return answer;} // Driver Code let n = 3; let A = [ 1, 2, 3 ]; document.write(xorOfSum(A, n)); // This code is contributed by Surbhi Tyagi </script>", "e": 29741, "s": 29183, "text": null }, { "code": null, "e": 29743, "s": 29741, "text": "2" }, { "code": null, "e": 29767, "s": 29745, "text": "Efficient Approach: " }, { "code": null, "e": 29992, "s": 29767, "text": "For obtaining Kth bit of the final xor value we see in all the pair-sums, that kth bit of them is set or not. If there are even a number of pairs that have the Kth bit set, then for the Kth bit, their xor is zero else one. " }, { "code": null, "e": 30481, "s": 29992, "text": "For finding count of pair sums having Kth bit set, we notice that we can mod all array elements by 2(K+1). This is because X and Y belong to input array and Sum = X + Y. Then X + Y can add up to have their Kth bit set which means Sum >= 2K. It can also be observed that they can have a carryover from addition which makes numbers in the range [2(K+1), 2(K+1) + 2K) have their Kth bit not set. So we only care about the Kth and (K+1)th bit of all the numbers to check the XOR of Kth bit. " }, { "code": null, "e": 30635, "s": 30481, "text": "After the mod operation is performed, for sum to have kth bit set, its value will be in range – [2K, 2(K+1) ) U [2(K+1) + 2K, Max-Value-Sum-Can-Take ]. " }, { "code": null, "e": 31060, "s": 30635, "text": "To find the numbers in the said range, make another array B containing modded array elements of arr[], and sort them. Then Sum can be assumed as Sum = Bi + Bj. Finally, find the maximum bound of j using binary search (built-in lower_bound in C++). Fix i and since the array is sorted find the last j that satisfies the given condition and all the numbers in the range of indices can be added to the count to check the xor. " }, { "code": null, "e": 31133, "s": 31060, "text": "Auxiliary Space: O(1)Below is the implementation of the above approach: " }, { "code": null, "e": 31137, "s": 31133, "text": "C++" }, { "code": "// C++ implementation to find XOR of// pairwise sum of every unordered// pairs in an array #include <bits/stdc++.h> using namespace std; // Function to find XOR of pairwise// sum of every unordered pairsint xorOfSum(int a[], int n){ int i, j, k; // Sort the array sort(a, a + n); int ans = 0; // Array elements are not greater // than 1e7 so 27 bits are suffice for (k = 0; k < 27; ++k) { // Modded elements of array vector<int> b(n); // Loop to find the modded // elements of array for (i = 0; i < n; i++) b[i] = a[i] % (1 << (k + 1)); // Sort the modded array sort(b.begin(), b.end()); int cnt = 0; for (i = 0; i < n; i++) { // finding the bound for j // for given i using binary search int l = lower_bound(b.begin() + i + 1, b.end(), (1 << k) - b[i]) - b.begin(); int r = lower_bound(b.begin() + i + 1, b.end(), (1 << (k + 1)) - b[i]) - b.begin(); // All the numbers in the range // of indices can be added to the // count to check the xor. cnt += r - l; l = lower_bound(b.begin() + i + 1, b.end(), (1 << (k + 1)) + (1 << k) - b[i]) - b.begin(); cnt += n - l; } // Remainder of cnt * kth power // of 2 added to the xor value ans += (cnt % 2) * 1LL * (1 << k); } return ans;} // Driver Codeint main(){ int n = 3; int A[n] = { 1, 2, 3 }; cout << xorOfSum(A, n); return 0;}", "e": 32810, "s": 31137, "text": null }, { "code": null, "e": 32812, "s": 32810, "text": "2" }, { "code": null, "e": 32838, "s": 32814, "text": "Performance Analysis: " }, { "code": null, "e": 32881, "s": 32838, "text": "Time complexity : O(N * log(max(A))*log(N)" }, { "code": null, "e": 32903, "s": 32881, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 33066, "s": 32903, "text": "Outermost loop runs for log(max(A)) times and for each loop we create and sort array b ,which consists of N elements ,hence complexity is O(N*log(N)*log(max(A))) " }, { "code": null, "e": 33081, "s": 33066, "text": "mohit kumar 29" }, { "code": null, "e": 33095, "s": 33081, "text": "princiraj1992" }, { "code": null, "e": 33103, "s": 33095, "text": "coder72" }, { "code": null, "e": 33117, "s": 33103, "text": "surbhityagi15" }, { "code": null, "e": 33127, "s": 33117, "text": "subham348" }, { "code": null, "e": 33139, "s": 33127, "text": "Bitwise-XOR" }, { "code": null, "e": 33150, "s": 33139, "text": "Algorithms" }, { "code": null, "e": 33160, "s": 33150, "text": "Bit Magic" }, { "code": null, "e": 33184, "s": 33160, "text": "Competitive Programming" }, { "code": null, "e": 33191, "s": 33184, "text": "Greedy" }, { "code": null, "e": 33204, "s": 33191, "text": "Mathematical" }, { "code": null, "e": 33214, "s": 33204, "text": "Searching" }, { "code": null, "e": 33224, "s": 33214, "text": "Searching" }, { "code": null, "e": 33231, "s": 33224, "text": "Greedy" }, { "code": null, "e": 33244, "s": 33231, "text": "Mathematical" }, { "code": null, "e": 33254, "s": 33244, "text": "Bit Magic" }, { "code": null, "e": 33265, "s": 33254, "text": "Algorithms" }, { "code": null, "e": 33363, "s": 33265, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33388, "s": 33363, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33415, "s": 33388, "text": "How to Start Learning DSA?" }, { "code": null, "e": 33468, "s": 33415, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 33502, "s": 33468, "text": "K means Clustering - Introduction" }, { "code": null, "e": 33569, "s": 33502, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 33596, "s": 33569, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 33642, "s": 33596, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 33710, "s": 33642, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 33739, "s": 33710, "text": "Count set bits in an integer" } ]
Express.js res.download() Function - GeeksforGeeks
07 Jul, 2020 The res.download() function transfers the file at path as an ‘attachment’. Typically, browsers will prompt the user to download. Syntax: res.download(path [, filename] [, options] [, fn]) Parameters: The filename is the name of the file which is to be downloaded as attachment and fn is a callback function. Return Value: It does not return anything. Installation of express module: You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install express module. You can install this package by using this command.npm install express npm install express After installing the express module, you can check your express version in command prompt using the command.npm version express npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Example 1: Filename: index.js var express = require('express');var app = express();var PORT = 3000; app.get('/', function(req, res){ res.download('Hello.txt');}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Place any file in root directory of the project which can be downloaded, like here we have used Hello.txt. Steps to run the program: Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000 Open your browser and go to http://localhost:3000/, now you can see the “Hello.txt” file being downloaded on your screen. Make sure you have installed express module using the following command:npm install express npm install express Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000 node index.js Output: Server listening on PORT 3000 Open your browser and go to http://localhost:3000/, now you can see the “Hello.txt” file being downloaded on your screen. Example 2: Filename: index.js var express = require('express');var app = express();var PORT = 3000; app.get('/', function(req, res){ res.download('Unknown_file.txt', function(error){ console.log("Error : ", error) });}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Run index.js file using below command: node index.js Open your browser and go to http://localhost:3000/, then you will see the following output on your console: Error : [Error: ENOENT: no such file or directory, stat 'C:\\Users\\Unknown_file.txt'] { errno: -4058, code: 'ENOENT', syscall: 'stat', path: 'C:\\Users\\Unknown_file.txt', expose: false, statusCode: 404, status: 404 } Reference: https://expressjs.com/en/4x/api.html#res.download Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method 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": 30835, "s": 30807, "text": "\n07 Jul, 2020" }, { "code": null, "e": 30964, "s": 30835, "text": "The res.download() function transfers the file at path as an ‘attachment’. Typically, browsers will prompt the user to download." }, { "code": null, "e": 30972, "s": 30964, "text": "Syntax:" }, { "code": null, "e": 31023, "s": 30972, "text": "res.download(path [, filename] [, options] [, fn])" }, { "code": null, "e": 31143, "s": 31023, "text": "Parameters: The filename is the name of the file which is to be downloaded as attachment and fn is a callback function." }, { "code": null, "e": 31186, "s": 31143, "text": "Return Value: It does not return anything." }, { "code": null, "e": 31218, "s": 31186, "text": "Installation of express module:" }, { "code": null, "e": 31613, "s": 31218, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 31734, "s": 31613, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install express" }, { "code": null, "e": 31754, "s": 31734, "text": "npm install express" }, { "code": null, "e": 31882, "s": 31754, "text": "After installing the express module, you can check your express version in command prompt using the command.npm version express" }, { "code": null, "e": 31902, "s": 31882, "text": "npm version express" }, { "code": null, "e": 32050, "s": 31902, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 32064, "s": 32050, "text": "node index.js" }, { "code": null, "e": 32094, "s": 32064, "text": "Example 1: Filename: index.js" }, { "code": "var express = require('express');var app = express();var PORT = 3000; app.get('/', function(req, res){ res.download('Hello.txt');}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 32347, "s": 32094, "text": null }, { "code": null, "e": 32454, "s": 32347, "text": "Place any file in root directory of the project which can be downloaded, like here we have used Hello.txt." }, { "code": null, "e": 32480, "s": 32454, "text": "Steps to run the program:" }, { "code": null, "e": 32781, "s": 32480, "text": "Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nOpen your browser and go to http://localhost:3000/, now you can see the “Hello.txt” file being downloaded on your screen." }, { "code": null, "e": 32873, "s": 32781, "text": "Make sure you have installed express module using the following command:npm install express" }, { "code": null, "e": 32893, "s": 32873, "text": "npm install express" }, { "code": null, "e": 32982, "s": 32893, "text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n" }, { "code": null, "e": 32996, "s": 32982, "text": "node index.js" }, { "code": null, "e": 33004, "s": 32996, "text": "Output:" }, { "code": null, "e": 33035, "s": 33004, "text": "Server listening on PORT 3000\n" }, { "code": null, "e": 33157, "s": 33035, "text": "Open your browser and go to http://localhost:3000/, now you can see the “Hello.txt” file being downloaded on your screen." }, { "code": null, "e": 33187, "s": 33157, "text": "Example 2: Filename: index.js" }, { "code": "var express = require('express');var app = express();var PORT = 3000; app.get('/', function(req, res){ res.download('Unknown_file.txt', function(error){ console.log(\"Error : \", error) });}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 33510, "s": 33187, "text": null }, { "code": null, "e": 33549, "s": 33510, "text": "Run index.js file using below command:" }, { "code": null, "e": 33563, "s": 33549, "text": "node index.js" }, { "code": null, "e": 33671, "s": 33563, "text": "Open your browser and go to http://localhost:3000/, then you will see the following output on your console:" }, { "code": null, "e": 33909, "s": 33671, "text": "Error : [Error: ENOENT: no such file or directory, \n stat 'C:\\\\Users\\\\Unknown_file.txt'] {\n errno: -4058,\n code: 'ENOENT',\n syscall: 'stat',\n path: 'C:\\\\Users\\\\Unknown_file.txt',\n expose: false,\n statusCode: 404,\n status: 404\n}\n" }, { "code": null, "e": 33970, "s": 33909, "text": "Reference: https://expressjs.com/en/4x/api.html#res.download" }, { "code": null, "e": 33981, "s": 33970, "text": "Express.js" }, { "code": null, "e": 33989, "s": 33981, "text": "Node.js" }, { "code": null, "e": 34006, "s": 33989, "text": "Web Technologies" }, { "code": null, "e": 34104, "s": 34006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34137, "s": 34104, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34185, "s": 34137, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34218, "s": 34185, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 34248, "s": 34218, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 34277, "s": 34248, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 34317, "s": 34277, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34350, "s": 34317, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34395, "s": 34350, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34438, "s": 34395, "text": "How to fetch data from an API in ReactJS ?" } ]
PHP | MySQL Select Query - GeeksforGeeks
03 Mar, 2018 The SQL SELECT statement is used to select the records from database tables. Syntax :The basic syntax of the select clause is – To select all columns from the table, the character is used. Implementation of the Select Query :Let us consider the following table ‘ Data ‘ with three columns ‘ FirstName ‘, ‘ LastName ‘ and ‘ Age ‘. To select all the data stored in the ‘ Data ‘ table, we will use the code mentioned below. SELECT Query using Procedural Method : <?php $link = mysqli_connect("localhost", "root", "", "Mydb"); if ($link == = false) { die("ERROR: Could not connect. " .mysqli_connect_error());} $sql = "SELECT * FROM Data";if ($res = mysqli_query($link, $sql)) { if (mysqli_num_rows($res) > 0) { echo "<table>"; echo "<tr>"; echo "<th>Firstname</th>"; echo "<th>Lastname</th>"; echo "<th>age</th>"; echo "</tr>"; while ($row = mysqli_fetch_array($res)) { echo "<tr>"; echo "<td>".$row['Firstname']."</td>"; echo "<td>".$row['Lastname']."</td>"; echo "<td>".$row['Age']."</td>"; echo "</tr>"; } echo "</table>"; mysqli_free_res($res); } else { echo "No matching records are found."; }}else { echo "ERROR: Could not able to execute $sql. " .mysqli_error($link);}mysqli_close($link);?> Output : Code Explanation: The “res” variable stores the data that is returned by the function mysql_query().Everytime mysqli_fetch_array() is invoked, it returns the next row from the res() set.The while loop is used to loop through all the rows of the table “data”. The “res” variable stores the data that is returned by the function mysql_query(). Everytime mysqli_fetch_array() is invoked, it returns the next row from the res() set. The while loop is used to loop through all the rows of the table “data”. SELECT Query using Object Oriented Method : <?php$mysqli = new mysqli("localhost", "root", "", "Mydb"); if ($mysqli == = false) { die("ERROR: Could not connect. " .$mysqli->connect_error);} $sql = "SELECT * FROM Data";if ($res = $mysqli->query($sql)) { if ($res->num_rows > 0) { echo "<table>"; echo "<tr>"; echo "<th>Firstname</th>"; echo "<th>Lastname</th>"; echo "<th>Age</th>"; echo "</tr>"; while ($row = $res->fetch_array()) { echo "<tr>"; echo "<td>".$row['Firstname']."</td>"; echo "<td>".$row['Lastname']."</td>"; echo "<td>".$row['Age']."</td>"; echo "</tr>"; } echo "</table>"; $res->free(); } else { echo "No matching records are found."; }}else { echo "ERROR: Could not able to execute $sql. " .$mysqli->error;}$mysqli->close();?> Output : SELECT Query using PDO Method : <?php try { $pdo = new PDO("mysql:host = localhost; dbname=mydb", "root", ""); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die("ERROR: Could not connect. ".$e->getMessage());}try { $sql = "SELECT * FROM Data"; $res = $pdo->query($sql); if ($res->rowCount() > 0) { echo "<table>"; echo "<tr>"; echo "<th>Firstname</th>"; echo "<th>Lastname</th>"; echo "<th>Age</th>"; echo "</tr>"; while ($row = $res->fetch()) { echo "<tr>"; echo "<td>".$row['Firstname']."</td>"; echo "<td>".$row['Lastname']."</td>"; echo "<td>".$row['Age']."</td>"; echo "</tr>"; } echo "</table>"; unset($res); } else { echo "No matching records are found."; }}catch (PDOException $e) { die("ERROR: Could not able to execute $sql. " .$e->getMessage());}unset($pdo);?> Output : mysql PHP SQL Web Technologies SQL PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? Comparing two dates in PHP SQL | DDL, DQL, DML, DCL and TCL Commands SQL | WITH clause How to find Nth highest salary from a table SQL | ALTER (RENAME) SQL Trigger | Student Database
[ { "code": null, "e": 24320, "s": 24292, "text": "\n03 Mar, 2018" }, { "code": null, "e": 24397, "s": 24320, "text": "The SQL SELECT statement is used to select the records from database tables." }, { "code": null, "e": 24448, "s": 24397, "text": "Syntax :The basic syntax of the select clause is –" }, { "code": null, "e": 24510, "s": 24448, "text": "To select all columns from the table, the character is used." }, { "code": null, "e": 24651, "s": 24510, "text": "Implementation of the Select Query :Let us consider the following table ‘ Data ‘ with three columns ‘ FirstName ‘, ‘ LastName ‘ and ‘ Age ‘." }, { "code": null, "e": 24742, "s": 24651, "text": "To select all the data stored in the ‘ Data ‘ table, we will use the code mentioned below." }, { "code": null, "e": 24781, "s": 24742, "text": "SELECT Query using Procedural Method :" }, { "code": "<?php $link = mysqli_connect(\"localhost\", \"root\", \"\", \"Mydb\"); if ($link == = false) { die(\"ERROR: Could not connect. \" .mysqli_connect_error());} $sql = \"SELECT * FROM Data\";if ($res = mysqli_query($link, $sql)) { if (mysqli_num_rows($res) > 0) { echo \"<table>\"; echo \"<tr>\"; echo \"<th>Firstname</th>\"; echo \"<th>Lastname</th>\"; echo \"<th>age</th>\"; echo \"</tr>\"; while ($row = mysqli_fetch_array($res)) { echo \"<tr>\"; echo \"<td>\".$row['Firstname'].\"</td>\"; echo \"<td>\".$row['Lastname'].\"</td>\"; echo \"<td>\".$row['Age'].\"</td>\"; echo \"</tr>\"; } echo \"</table>\"; mysqli_free_res($res); } else { echo \"No matching records are found.\"; }}else { echo \"ERROR: Could not able to execute $sql. \" .mysqli_error($link);}mysqli_close($link);?>", "e": 25714, "s": 24781, "text": null }, { "code": null, "e": 25723, "s": 25714, "text": "Output :" }, { "code": null, "e": 25741, "s": 25723, "text": "Code Explanation:" }, { "code": null, "e": 25982, "s": 25741, "text": "The “res” variable stores the data that is returned by the function mysql_query().Everytime mysqli_fetch_array() is invoked, it returns the next row from the res() set.The while loop is used to loop through all the rows of the table “data”." }, { "code": null, "e": 26065, "s": 25982, "text": "The “res” variable stores the data that is returned by the function mysql_query()." }, { "code": null, "e": 26152, "s": 26065, "text": "Everytime mysqli_fetch_array() is invoked, it returns the next row from the res() set." }, { "code": null, "e": 26225, "s": 26152, "text": "The while loop is used to loop through all the rows of the table “data”." }, { "code": null, "e": 26269, "s": 26225, "text": "SELECT Query using Object Oriented Method :" }, { "code": "<?php$mysqli = new mysqli(\"localhost\", \"root\", \"\", \"Mydb\"); if ($mysqli == = false) { die(\"ERROR: Could not connect. \" .$mysqli->connect_error);} $sql = \"SELECT * FROM Data\";if ($res = $mysqli->query($sql)) { if ($res->num_rows > 0) { echo \"<table>\"; echo \"<tr>\"; echo \"<th>Firstname</th>\"; echo \"<th>Lastname</th>\"; echo \"<th>Age</th>\"; echo \"</tr>\"; while ($row = $res->fetch_array()) { echo \"<tr>\"; echo \"<td>\".$row['Firstname'].\"</td>\"; echo \"<td>\".$row['Lastname'].\"</td>\"; echo \"<td>\".$row['Age'].\"</td>\"; echo \"</tr>\"; } echo \"</table>\"; $res->free(); } else { echo \"No matching records are found.\"; }}else { echo \"ERROR: Could not able to execute $sql. \" .$mysqli->error;}$mysqli->close();?>", "e": 27198, "s": 26269, "text": null }, { "code": null, "e": 27207, "s": 27198, "text": "Output :" }, { "code": null, "e": 27239, "s": 27207, "text": "SELECT Query using PDO Method :" }, { "code": "<?php try { $pdo = new PDO(\"mysql:host = localhost; dbname=mydb\", \"root\", \"\"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);}catch (PDOException $e) { die(\"ERROR: Could not connect. \".$e->getMessage());}try { $sql = \"SELECT * FROM Data\"; $res = $pdo->query($sql); if ($res->rowCount() > 0) { echo \"<table>\"; echo \"<tr>\"; echo \"<th>Firstname</th>\"; echo \"<th>Lastname</th>\"; echo \"<th>Age</th>\"; echo \"</tr>\"; while ($row = $res->fetch()) { echo \"<tr>\"; echo \"<td>\".$row['Firstname'].\"</td>\"; echo \"<td>\".$row['Lastname'].\"</td>\"; echo \"<td>\".$row['Age'].\"</td>\"; echo \"</tr>\"; } echo \"</table>\"; unset($res); } else { echo \"No matching records are found.\"; }}catch (PDOException $e) { die(\"ERROR: Could not able to execute $sql. \" .$e->getMessage());}unset($pdo);?>", "e": 28260, "s": 27239, "text": null }, { "code": null, "e": 28269, "s": 28260, "text": "Output :" }, { "code": null, "e": 28275, "s": 28269, "text": "mysql" }, { "code": null, "e": 28279, "s": 28275, "text": "PHP" }, { "code": null, "e": 28283, "s": 28279, "text": "SQL" }, { "code": null, "e": 28300, "s": 28283, "text": "Web Technologies" }, { "code": null, "e": 28304, "s": 28300, "text": "SQL" }, { "code": null, "e": 28308, "s": 28304, "text": "PHP" }, { "code": null, "e": 28406, "s": 28308, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28415, "s": 28406, "text": "Comments" }, { "code": null, "e": 28428, "s": 28415, "text": "Old Comments" }, { "code": null, "e": 28478, "s": 28428, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28518, "s": 28478, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28579, "s": 28518, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 28629, "s": 28579, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 28656, "s": 28629, "text": "Comparing two dates in PHP" }, { "code": null, "e": 28698, "s": 28656, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 28716, "s": 28698, "text": "SQL | WITH clause" }, { "code": null, "e": 28760, "s": 28716, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 28781, "s": 28760, "text": "SQL | ALTER (RENAME)" } ]
How to dynamically change color by percentage CSS ? - GeeksforGeeks
16 Apr, 2021 In this article, we will learn How to dynamically change color by percentage CSS. Approach: We can dynamically change the color of any element by percentage using the filter property in CSS. The brightness() function of the filter property is used to dynamically change color by percentage. The brightness function takes a value in percentage to set the brightness of that color. Syntax: filter: brightness(value); Example: In the below example we set the background color of the element white. But when we hover on the paragraph its background color changes 50% because we set a filter that changes the background color of the paragraph by 50%. HTML <!DOCTYPE html><html lang="en"><head> <title>Document</title> <style> .gfg{ font-size: 40px; color: green; border: solid 2px red ; background-color: white; } p:hover{ /* Change brightness */ filter: brightness(50%); } </style></head><body> <p class="gfg">GeeksforGeeks</p> </body></html> Output: CSS-Basics CSS-Properties CSS-Questions Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to position a div at the bottom of its container using CSS? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 25026, "s": 24998, "text": "\n16 Apr, 2021" }, { "code": null, "e": 25108, "s": 25026, "text": "In this article, we will learn How to dynamically change color by percentage CSS." }, { "code": null, "e": 25406, "s": 25108, "text": "Approach: We can dynamically change the color of any element by percentage using the filter property in CSS. The brightness() function of the filter property is used to dynamically change color by percentage. The brightness function takes a value in percentage to set the brightness of that color." }, { "code": null, "e": 25414, "s": 25406, "text": "Syntax:" }, { "code": null, "e": 25441, "s": 25414, "text": "filter: brightness(value);" }, { "code": null, "e": 25672, "s": 25441, "text": "Example: In the below example we set the background color of the element white. But when we hover on the paragraph its background color changes 50% because we set a filter that changes the background color of the paragraph by 50%." }, { "code": null, "e": 25677, "s": 25672, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Document</title> <style> .gfg{ font-size: 40px; color: green; border: solid 2px red ; background-color: white; } p:hover{ /* Change brightness */ filter: brightness(50%); } </style></head><body> <p class=\"gfg\">GeeksforGeeks</p> </body></html>", "e": 26072, "s": 25677, "text": null }, { "code": null, "e": 26080, "s": 26072, "text": "Output:" }, { "code": null, "e": 26091, "s": 26080, "text": "CSS-Basics" }, { "code": null, "e": 26106, "s": 26091, "text": "CSS-Properties" }, { "code": null, "e": 26120, "s": 26106, "text": "CSS-Questions" }, { "code": null, "e": 26127, "s": 26120, "text": "Picked" }, { "code": null, "e": 26131, "s": 26127, "text": "CSS" }, { "code": null, "e": 26148, "s": 26131, "text": "Web Technologies" }, { "code": null, "e": 26246, "s": 26148, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26255, "s": 26246, "text": "Comments" }, { "code": null, "e": 26268, "s": 26255, "text": "Old Comments" }, { "code": null, "e": 26326, "s": 26268, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 26363, "s": 26326, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 26404, "s": 26363, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 26441, "s": 26404, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26505, "s": 26441, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 26547, "s": 26505, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26580, "s": 26547, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26623, "s": 26580, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26668, "s": 26623, "text": "Convert a string to an integer in JavaScript" } ]
Absolute Positioning Using CSS
We can define positioning of an element in CSS as absolute which renders the element relative to the first positioned (except static) parent. Elements with positioning method as absolute are positioned by CSS Positioning properties (left, right, top and bottom). Let’s see an example for CSS Absolute Positioning Method − Live Demo <!DOCTYPE html> <html> <head> <style> p { margin: 0; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } div:first-child { background-color: orange; text-align: center; } div:last-child { width: 250px; height: 100px; margin: auto; background-color: turquoise; position: absolute; z-index: -1; top:0; left: 0; right: 0; bottom: 0; } </style> </head> <body> <div>Demo text</div> <p>ICC is International Cricket Council is the governing body of Cricket founded in 1909........</p> <div> </div> </body> </html> Following is the output for above code − Let’s see another example for positioning methods − Live Demo <!DOCTYPE html> <html> <head> <style> div { border: 2px double #a43356; margin: 5px; padding: 5px; } #d1 { position: relative; height: 10em; } #d2 { position: absolute; width: 20%; bottom: 10px; /*relative to parent d1*/ } #d3 { position: fixed; width: 30%; top:10em; /*relative to viewport*/ } </style> </head> <body> <div id="d1">MySQL is the most popular Open Source Relational SQL Database Management System. MySQL is one of the best RDBMS being used for developing various web-based software applications. <mark>relative</mark> <div id="d2"><mark>absolute</mark></div> <div id="d3"><mark>fixed</mark></div> </div> </body> </html> Following is the output for above code −
[ { "code": null, "e": 1325, "s": 1062, "text": "We can define positioning of an element in CSS as absolute which renders the element relative to the first positioned (except static) parent. Elements with positioning method as absolute are positioned by CSS Positioning properties (left, right, top and bottom)." }, { "code": null, "e": 1384, "s": 1325, "text": "Let’s see an example for CSS Absolute Positioning Method −" }, { "code": null, "e": 1395, "s": 1384, "text": " Live Demo" }, { "code": null, "e": 1978, "s": 1395, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\np {\n margin: 0;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n}\ndiv:first-child {\n background-color: orange;\n text-align: center;\n}\ndiv:last-child {\n width: 250px;\n height: 100px;\n margin: auto;\n background-color: turquoise;\n position: absolute;\n z-index: -1;\n top:0;\n left: 0;\n right: 0;\n bottom: 0;\n}\n</style>\n</head>\n<body>\n<div>Demo text</div>\n<p>ICC is International Cricket Council is the governing body of Cricket founded in 1909........</p>\n<div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 2019, "s": 1978, "text": "Following is the output for above code −" }, { "code": null, "e": 2071, "s": 2019, "text": "Let’s see another example for positioning methods −" }, { "code": null, "e": 2082, "s": 2071, "text": " Live Demo" }, { "code": null, "e": 2751, "s": 2082, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndiv {\n border: 2px double #a43356;\n margin: 5px;\n padding: 5px;\n}\n#d1 {\n position: relative;\n height: 10em;\n}\n#d2 {\n position: absolute;\n width: 20%;\n bottom: 10px; /*relative to parent d1*/\n}\n#d3 {\n position: fixed;\n width: 30%;\n top:10em; /*relative to viewport*/\n}\n</style>\n</head>\n<body>\n<div id=\"d1\">MySQL is the most popular Open Source Relational SQL Database Management System. \nMySQL is one of the best RDBMS being used for developing various web-based software applications. <mark>relative</mark>\n<div id=\"d2\"><mark>absolute</mark></div>\n<div id=\"d3\"><mark>fixed</mark></div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 2792, "s": 2751, "text": "Following is the output for above code −" } ]
How to Calculate the Mode of NumPy Array? - GeeksforGeeks
12 Jan, 2022 In this article, we will discuss how to calculate the mode of the Numpy Array. Mode refers to the most repeating element in the array. We can find the mode from the NumPy array by using the following methods. Let us see the syntax of the mode() function Syntax : variable = stats.mode(array_variable) Note : To apply mode we need to create an array. In python, we can create an array using numpy package. So first we need to create an array using numpy package and apply mode() function on that array. Let us see examples for better understanding. Example 1: Applying on 1-D array Python3 # importing required packagesfrom scipy import stats as stimport numpy as np # creating an array using array() methodabc = np.array([1, 1, 2, 2, 2, 3, 4, 5]) # applying mode operation on array and# printing resultprint(st.mode(abc)) Output : ModeResult(mode=array([2]), count=array([3])) Example 2: Applying on a 2-D array Python3 # importing required modulesimport numpy as npfrom scipy import stats as st # creating a 2-D array using numpy packagearr = np.array([[1, 2, 3, 4, 5], [1, 2, 2, 2, 2], [4, 5, 7, 9, 4], [6, 7, 8, 9, 2], [2, 3, 4, 8, 6]]) # applying mode operation and printing the# resultprint(st.mode(arr)) Output : ModeResult(mode=array([[1, 2, 2, 9, 2]]), count=array([[2, 2, 1, 2, 2]])) Like NumPy module, the statistics module also contains statistical functions like mean , median , mode....etc . So let us see an example of a mode using the statistics module. Example : Python3 import statistics as stimport numpy as np # create an 1 d arrayarr1 = np.array([9, 8, 7, 6, 6, 6, 6, 5, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1]) # display the modeprint(st.mode(arr1)) Output : 1 Here we are not using any predefines functions for getting mode of a series. Let us see an example with demonstrates how to calculate mode without predefined functions. Example : Python3 # creating a listlst = [1, 2, 3, 4, 5, 6, 2, 3, 4, 5, 5, 5, 5] # defining a function to calculate mode. It# takes list variable as argumentdef mode(lst): # creating a dictionary freq = {} for i in lst: # mapping each value of list to a # dictionary freq.setdefault(i, 0) freq[i] += 1 # finding maximum value of dictionary hf = max(freq.values()) # creating an empty list hflst = [] # using for loop we are checking for most # repeated value for i, j in freq.items(): if j == hf: hflst.append(i) # returning the result return hflst # calling mode() function and passing list# as argumentprint(mode(lst)) Output : [5] germanshephered48 simmytarika5 Picked Python numpy-Linear Algebra 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? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n12 Jan, 2022" }, { "code": null, "e": 24371, "s": 24292, "text": "In this article, we will discuss how to calculate the mode of the Numpy Array." }, { "code": null, "e": 24501, "s": 24371, "text": "Mode refers to the most repeating element in the array. We can find the mode from the NumPy array by using the following methods." }, { "code": null, "e": 24547, "s": 24501, "text": "Let us see the syntax of the mode() function " }, { "code": null, "e": 24556, "s": 24547, "text": "Syntax :" }, { "code": null, "e": 24594, "s": 24556, "text": "variable = stats.mode(array_variable)" }, { "code": null, "e": 24841, "s": 24594, "text": "Note : To apply mode we need to create an array. In python, we can create an array using numpy package. So first we need to create an array using numpy package and apply mode() function on that array. Let us see examples for better understanding." }, { "code": null, "e": 24852, "s": 24841, "text": "Example 1:" }, { "code": null, "e": 24874, "s": 24852, "text": "Applying on 1-D array" }, { "code": null, "e": 24882, "s": 24874, "text": "Python3" }, { "code": "# importing required packagesfrom scipy import stats as stimport numpy as np # creating an array using array() methodabc = np.array([1, 1, 2, 2, 2, 3, 4, 5]) # applying mode operation on array and# printing resultprint(st.mode(abc))", "e": 25115, "s": 24882, "text": null }, { "code": null, "e": 25124, "s": 25115, "text": "Output :" }, { "code": null, "e": 25170, "s": 25124, "text": "ModeResult(mode=array([2]), count=array([3]))" }, { "code": null, "e": 25181, "s": 25170, "text": "Example 2:" }, { "code": null, "e": 25205, "s": 25181, "text": "Applying on a 2-D array" }, { "code": null, "e": 25213, "s": 25205, "text": "Python3" }, { "code": "# importing required modulesimport numpy as npfrom scipy import stats as st # creating a 2-D array using numpy packagearr = np.array([[1, 2, 3, 4, 5], [1, 2, 2, 2, 2], [4, 5, 7, 9, 4], [6, 7, 8, 9, 2], [2, 3, 4, 8, 6]]) # applying mode operation and printing the# resultprint(st.mode(arr))", "e": 25563, "s": 25213, "text": null }, { "code": null, "e": 25572, "s": 25563, "text": "Output :" }, { "code": null, "e": 25646, "s": 25572, "text": "ModeResult(mode=array([[1, 2, 2, 9, 2]]), count=array([[2, 2, 1, 2, 2]]))" }, { "code": null, "e": 25822, "s": 25646, "text": "Like NumPy module, the statistics module also contains statistical functions like mean , median , mode....etc . So let us see an example of a mode using the statistics module." }, { "code": null, "e": 25832, "s": 25822, "text": "Example :" }, { "code": null, "e": 25840, "s": 25832, "text": "Python3" }, { "code": "import statistics as stimport numpy as np # create an 1 d arrayarr1 = np.array([9, 8, 7, 6, 6, 6, 6, 5, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1]) # display the modeprint(st.mode(arr1))", "e": 26030, "s": 25840, "text": null }, { "code": null, "e": 26039, "s": 26030, "text": "Output :" }, { "code": null, "e": 26041, "s": 26039, "text": "1" }, { "code": null, "e": 26210, "s": 26041, "text": "Here we are not using any predefines functions for getting mode of a series. Let us see an example with demonstrates how to calculate mode without predefined functions." }, { "code": null, "e": 26220, "s": 26210, "text": "Example :" }, { "code": null, "e": 26228, "s": 26220, "text": "Python3" }, { "code": "# creating a listlst = [1, 2, 3, 4, 5, 6, 2, 3, 4, 5, 5, 5, 5] # defining a function to calculate mode. It# takes list variable as argumentdef mode(lst): # creating a dictionary freq = {} for i in lst: # mapping each value of list to a # dictionary freq.setdefault(i, 0) freq[i] += 1 # finding maximum value of dictionary hf = max(freq.values()) # creating an empty list hflst = [] # using for loop we are checking for most # repeated value for i, j in freq.items(): if j == hf: hflst.append(i) # returning the result return hflst # calling mode() function and passing list# as argumentprint(mode(lst))", "e": 26957, "s": 26228, "text": null }, { "code": null, "e": 26966, "s": 26957, "text": "Output :" }, { "code": null, "e": 26970, "s": 26966, "text": "[5]" }, { "code": null, "e": 26988, "s": 26970, "text": "germanshephered48" }, { "code": null, "e": 27001, "s": 26988, "text": "simmytarika5" }, { "code": null, "e": 27008, "s": 27001, "text": "Picked" }, { "code": null, "e": 27036, "s": 27008, "text": "Python numpy-Linear Algebra" }, { "code": null, "e": 27049, "s": 27036, "text": "Python-numpy" }, { "code": null, "e": 27056, "s": 27049, "text": "Python" }, { "code": null, "e": 27154, "s": 27056, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27186, "s": 27154, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27228, "s": 27186, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27284, "s": 27228, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27326, "s": 27284, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27357, "s": 27326, "text": "Python | os.path.join() method" }, { "code": null, "e": 27412, "s": 27357, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27434, "s": 27412, "text": "Defaultdict in Python" }, { "code": null, "e": 27473, "s": 27434, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27502, "s": 27473, "text": "Create a directory in Python" } ]
Basic Python Programming Challenges
In this tutorial, we are going to write a solution for a challenge. We have to generate a random set of basic arithmetic operations. The user will give the number of questions, and we have to generate questions. After every question, the user will answer it. At the end of the program, we have to give the score. Let's try it. # importing random and operator modules import random import operator # main function # taking number of questions that we have to generate def main(n): print("Welcome to the quiz\nYou should answer floats upto 2 decimals") # initialising score to 0 score = 0 # loop to generate n questions for i in range(n): # getting answer and correctness of a question is_correct, answer = question(i) # checking whether is_correct is True or not if is_correct: # increment score by 1 if correct score += 1 print('Correct Congrats!') else: # printing the correct answer print(f'Incorrect! Answer: {answer}') # displaying the total score print(f'Total score: {score}') # function for the question def question(n): # getting answer from the generate_function answer = generate_question() # taking answer from the user user_answer = float(input("Answer: ")) # returning answer to the main function return user_answer == answer, answer # function to generate a random question def generate_question(): # initialising operators for random generation operators = { '+' : operator.add, '-' : operator.sub, '*' : operator.mul, '/' : operator.truediv, '//' : operator.floordiv, '%' : operator.mod } # initialising numbers for expressions nums = [i for i in range(10)] # getting two random numbers from nums for calculation _1, _2 = nums[random.randint(0, 9)], nums[random.randint(0, 9)] # generating random operator from the list of operators symbol = list(operators.keys())[random.randint(0, 5)] # calculating the answer answer = round(operators.get(symbol)(_1, _2), 2) print(f'{_1} {symbol} {_2}?') return answer if __name__ == '__main__': main(5) If you run the above code, you will get the following results. Welcome to the quiz You should answer floats upto 2 decimals 5 + 7? Answer: 12 Correct Congrats! 9 / 9? Answer: 1 Correct Congrats! 4 + 7? Answer: 11 Correct Congrats! 6 // 6? Answer: 1.0 Correct Congrats! 9 % 3? Answer: 0 Correct Congrats! Total score: 5 You can also improve the question by adding some more features like increasing difficulty, generating easy to hard questions, etc.., Try it yourself. I hope you enjoyed the tutorial. If you have any doubts, mention them in the comment section.
[ { "code": null, "e": 1130, "s": 1062, "text": "In this tutorial, we are going to write a solution for a challenge." }, { "code": null, "e": 1389, "s": 1130, "text": "We have to generate a random set of basic arithmetic operations. The user will give the number of questions, and we have to generate questions. After every question, the user will answer it. At the end of the program, we have to give the score. Let's try it." }, { "code": null, "e": 3210, "s": 1389, "text": "# importing random and operator modules\nimport random\nimport operator\n# main function\n# taking number of questions that we have to generate\ndef main(n):\n print(\"Welcome to the quiz\\nYou should answer floats upto 2 decimals\")\n # initialising score to 0\n score = 0\n # loop to generate n questions\n for i in range(n):\n # getting answer and correctness of a question\n is_correct, answer = question(i)\n # checking whether is_correct is True or not\n if is_correct:\n # increment score by 1 if correct\n score += 1\n print('Correct Congrats!')\n else:\n # printing the correct answer\n print(f'Incorrect! Answer: {answer}')\n # displaying the total score\n print(f'Total score: {score}')\n# function for the question\ndef question(n):\n # getting answer from the generate_function\n answer = generate_question()\n # taking answer from the user\n user_answer = float(input(\"Answer: \"))\n # returning answer to the main function\n return user_answer == answer, answer\n# function to generate a random question\ndef generate_question():\n # initialising operators for random generation\n operators = {\n '+' : operator.add,\n '-' : operator.sub,\n '*' : operator.mul,\n '/' : operator.truediv,\n '//' : operator.floordiv,\n '%' : operator.mod\n }\n # initialising numbers for expressions\n nums = [i for i in range(10)]\n # getting two random numbers from nums for calculation\n _1, _2 = nums[random.randint(0, 9)], nums[random.randint(0, 9)]\n # generating random operator from the list of operators\n symbol = list(operators.keys())[random.randint(0, 5)]\n # calculating the answer\n answer = round(operators.get(symbol)(_1, _2), 2)\n print(f'{_1} {symbol} {_2}?')\n return answer\nif __name__ == '__main__':\n main(5)" }, { "code": null, "e": 3273, "s": 3210, "text": "If you run the above code, you will get the following results." }, { "code": null, "e": 3529, "s": 3273, "text": "Welcome to the quiz\nYou should answer floats upto 2 decimals\n5 + 7?\nAnswer: 12\nCorrect Congrats!\n9 / 9?\nAnswer: 1\nCorrect Congrats!\n4 + 7?\nAnswer: 11\nCorrect Congrats!\n6 // 6?\nAnswer: 1.0\nCorrect Congrats!\n9 % 3?\nAnswer: 0\nCorrect Congrats!\nTotal score: 5" }, { "code": null, "e": 3773, "s": 3529, "text": "You can also improve the question by adding some more features like increasing difficulty, generating easy to hard questions, etc.., Try it yourself. I hope you enjoyed the tutorial. If you have any doubts, mention them in the comment section." } ]
Java Program to illustrate the Usage of HexaDecimal
06 Jun, 2021 A decimal number is the sum of digits multiplied with a power of 10. Decimal numbers are represented with base 10 whereas hexadecimal Number is the sum of digits multiplied with the power of 16, somehow there are similar traits in the internal working of them just they are two different ways to present a number. The hexadecimal system has 16 different digit symbols. Different numbers can be generated using the combination of digits from 0 to 15. The representation in the hexadecimal system is the same as the decimal number system from 0 to 9 but then onwards it changes. Representation: Decimal Number Hexadecimal Number Equivalent 0 —> 0 : : 9 —> 9 10 —> A 11 —> B 12 —> C 13 —> D 14 —> E 15 —> F Illustration: Internal Working A. Decimal to Hexadecimal Number System (1) (13)10 --> (D)16 Directly can be writen 13 as D in hexadecimal system (2) (16)10 ---> (10)16 ( 16 )16 = ( 1 x 161) + ( 0 * 160) (3) (59)10 ---> (3B)16 ( 59 )10 --> ( 3 * 161) + (11 * 160) Conclusion: For a Decimal Number system-> ( 421 )10 = (4 x 102) + (2 x 101) + (1 x 100) B. Similarly ,Hexadecimal to Decimal Number System (8A)16 ---> (138)10 (8A)16 --> (8 x 161) + (10 x 160) Conclusion: In Java programs, hexadecimal numbers are written by placing 0x before numbers. Below are 4 examples been discusses to illustrate the usage of Hexadecimal Number Converting Hex number to Decimal numberConverting Decimal number to Hex numberConverting Hex number to Long numberConverting Long number to Hex number Converting Hex number to Decimal number Converting Decimal number to Hex number Converting Hex number to Long number Converting Long number to Hex number Example 1: Java program to convert Hex number to Decimal number Java // Java program to convert Hex number to Decimal number // Importing input/output java libraryimport java.io.*; class GFG { // Main driver method public static void main(String[] args) { // Hexadecimal number stored in a string String hexNum = "100"; /* Random hexadecimal number */ // Passing hexnum and base as parameters // which is 16 to parseInt function int decimal = Integer.parseInt(hexNum, 16); // Printing the output result as // decimal equivalent of hexa-decimal System.out.println("Decimal value is " + decimal); }} Decimal value is 256 Example 2: Java program to convert Decimal number to Hex number Java // Java Program to Illustrate the Usage of HexaDecimal // Importing input/output java libraryimport java.io.*; class GFG { // Main driver function public static void main(String[] args) { /* Decimal number to be converted */ int i = 257; // Using toHexString() method for getting decNum and // Storing the hexaDecNum in a string String hex = Integer.toHexString(i); // Printing hexaDecNum of decNum System.out.println("Hex value is " + hex); }} Hex value is 101 Example 3: Java program to convert Hex number to Long number Java // Java Program to Illustrate the Usage of HexaDecimal // Importing input/output java libraryimport java.io.*; class GFG { // Main driver method public static void main(String[] args) { // Hexadecimal number stored in a string String hexNum = "10000"; // passing hexnum and base as parameters // which is 16 to parseLong function long num = Long.parseLong(hexNum, 16); // Printing long value of HexaDecNum System.out.println("Long value is " + num); }} Long value is 65536 Example 4: Java program to convert Long number to Hex number Java // Java Program to Illustrate the Usage of HexaDecimal // Importing java input/output libraryimport java.io.*; class GFG { // Main driver function public static void main(String[] args) { /* Long number to be converted */ long i = 1024; // Storing the result in a string String hex = Long.toHexString(i); // Displaying Result System.out.println("Hex value is " + hex); }} Hex value is 400 Note: There are two more conventions for hexadecimal numbers, 400h or $400. They both are the same as 0x400. simranarora5sos Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 605, "s": 28, "text": "A decimal number is the sum of digits multiplied with a power of 10. Decimal numbers are represented with base 10 whereas hexadecimal Number is the sum of digits multiplied with the power of 16, somehow there are similar traits in the internal working of them just they are two different ways to present a number. The hexadecimal system has 16 different digit symbols. Different numbers can be generated using the combination of digits from 0 to 15. The representation in the hexadecimal system is the same as the decimal number system from 0 to 9 but then onwards it changes." }, { "code": null, "e": 621, "s": 605, "text": "Representation:" }, { "code": null, "e": 670, "s": 621, "text": " Decimal Number Hexadecimal Number Equivalent" }, { "code": null, "e": 695, "s": 670, "text": " 0 —> 0" }, { "code": null, "e": 710, "s": 695, "text": " : :" }, { "code": null, "e": 735, "s": 710, "text": " 9 —> 9" }, { "code": null, "e": 760, "s": 735, "text": " 10 —> A" }, { "code": null, "e": 785, "s": 760, "text": " 11 —> B" }, { "code": null, "e": 810, "s": 785, "text": " 12 —> C" }, { "code": null, "e": 835, "s": 810, "text": " 13 —> D" }, { "code": null, "e": 860, "s": 835, "text": " 14 —> E" }, { "code": null, "e": 885, "s": 860, "text": " 15 —> F" }, { "code": null, "e": 916, "s": 885, "text": "Illustration: Internal Working" }, { "code": null, "e": 1169, "s": 916, "text": "A. Decimal to Hexadecimal Number System\n\n(1) (13)10 --> (D)16\n Directly can be writen 13 as D in hexadecimal system\n \n(2) (16)10 ---> (10)16\n ( 16 )16 = ( 1 x 161) + ( 0 * 160)\n \n(3) (59)10 ---> (3B)16\n ( 59 )10 --> ( 3 * 161) + (11 * 160)" }, { "code": null, "e": 1181, "s": 1169, "text": "Conclusion:" }, { "code": null, "e": 1257, "s": 1181, "text": "For a Decimal Number system-> ( 421 )10 = (4 x 102) + (2 x 101) + (1 x 100)" }, { "code": null, "e": 1369, "s": 1257, "text": "B. Similarly ,Hexadecimal to Decimal Number System\n (8A)16 ---> (138)10\n (8A)16 --> (8 x 161) + (10 x 160)" }, { "code": null, "e": 1381, "s": 1369, "text": "Conclusion:" }, { "code": null, "e": 1461, "s": 1381, "text": "In Java programs, hexadecimal numbers are written by placing 0x before numbers." }, { "code": null, "e": 1543, "s": 1461, "text": "Below are 4 examples been discusses to illustrate the usage of Hexadecimal Number" }, { "code": null, "e": 1694, "s": 1543, "text": "Converting Hex number to Decimal numberConverting Decimal number to Hex numberConverting Hex number to Long numberConverting Long number to Hex number" }, { "code": null, "e": 1734, "s": 1694, "text": "Converting Hex number to Decimal number" }, { "code": null, "e": 1774, "s": 1734, "text": "Converting Decimal number to Hex number" }, { "code": null, "e": 1811, "s": 1774, "text": "Converting Hex number to Long number" }, { "code": null, "e": 1848, "s": 1811, "text": "Converting Long number to Hex number" }, { "code": null, "e": 1912, "s": 1848, "text": "Example 1: Java program to convert Hex number to Decimal number" }, { "code": null, "e": 1917, "s": 1912, "text": "Java" }, { "code": "// Java program to convert Hex number to Decimal number // Importing input/output java libraryimport java.io.*; class GFG { // Main driver method public static void main(String[] args) { // Hexadecimal number stored in a string String hexNum = \"100\"; /* Random hexadecimal number */ // Passing hexnum and base as parameters // which is 16 to parseInt function int decimal = Integer.parseInt(hexNum, 16); // Printing the output result as // decimal equivalent of hexa-decimal System.out.println(\"Decimal value is \" + decimal); }}", "e": 2526, "s": 1917, "text": null }, { "code": null, "e": 2550, "s": 2529, "text": "Decimal value is 256" }, { "code": null, "e": 2618, "s": 2552, "text": " Example 2: Java program to convert Decimal number to Hex number " }, { "code": null, "e": 2625, "s": 2620, "text": "Java" }, { "code": "// Java Program to Illustrate the Usage of HexaDecimal // Importing input/output java libraryimport java.io.*; class GFG { // Main driver function public static void main(String[] args) { /* Decimal number to be converted */ int i = 257; // Using toHexString() method for getting decNum and // Storing the hexaDecNum in a string String hex = Integer.toHexString(i); // Printing hexaDecNum of decNum System.out.println(\"Hex value is \" + hex); }}", "e": 3135, "s": 2625, "text": null }, { "code": null, "e": 3155, "s": 3138, "text": "Hex value is 101" }, { "code": null, "e": 3218, "s": 3157, "text": "Example 3: Java program to convert Hex number to Long number" }, { "code": null, "e": 3225, "s": 3220, "text": "Java" }, { "code": "// Java Program to Illustrate the Usage of HexaDecimal // Importing input/output java libraryimport java.io.*; class GFG { // Main driver method public static void main(String[] args) { // Hexadecimal number stored in a string String hexNum = \"10000\"; // passing hexnum and base as parameters // which is 16 to parseLong function long num = Long.parseLong(hexNum, 16); // Printing long value of HexaDecNum System.out.println(\"Long value is \" + num); }}", "e": 3743, "s": 3225, "text": null }, { "code": null, "e": 3766, "s": 3746, "text": "Long value is 65536" }, { "code": null, "e": 3830, "s": 3768, "text": "Example 4: Java program to convert Long number to Hex number " }, { "code": null, "e": 3837, "s": 3832, "text": "Java" }, { "code": "// Java Program to Illustrate the Usage of HexaDecimal // Importing java input/output libraryimport java.io.*; class GFG { // Main driver function public static void main(String[] args) { /* Long number to be converted */ long i = 1024; // Storing the result in a string String hex = Long.toHexString(i); // Displaying Result System.out.println(\"Hex value is \" + hex); }}", "e": 4267, "s": 3837, "text": null }, { "code": null, "e": 4287, "s": 4270, "text": "Hex value is 400" }, { "code": null, "e": 4398, "s": 4289, "text": "Note: There are two more conventions for hexadecimal numbers, 400h or $400. They both are the same as 0x400." }, { "code": null, "e": 4416, "s": 4400, "text": "simranarora5sos" }, { "code": null, "e": 4423, "s": 4416, "text": "Picked" }, { "code": null, "e": 4428, "s": 4423, "text": "Java" }, { "code": null, "e": 4442, "s": 4428, "text": "Java Programs" }, { "code": null, "e": 4447, "s": 4442, "text": "Java" } ]
Understanding Python Dataclasses
06 Aug, 2021 DataClasses has been added in a recent addition in python 3.7 as a utility tool for storing data. DataClasses provides a decorator and functions for automatically adding generated special methods such as __init__() , __repr__() and __eq__() to user-defined classes. DataClasses are like normal classes in Python, but they have some basic functions like instantiation, comparing, and printing the classes already implemented. Installing the DataClasses module: pip install dataclasses The syntax of the dataclass is: Syntax: @dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False) Parameters: init: If true __init__() method will be generated repr: If true __repr__() method will be generated eq: If true __eq__() method will be generated order: If true __lt__(), __le__(), __gt__(), and __ge__() methods will be generated. unsafe_hash: If False __hash__() method is generated according to how eq and frozen are set frozen: If true assigning to fields will generate an exception. DataClass module provides a handy way to make classes less wordy. Let us see the traditional approach without using DataClass. Python3 # creating a employee classclass employee: # init method or constructor def __init__(self, name, emp_id, age, city): # Instance Variable self.name = name self.emp_id = emp_id self.age = age self.city = city # magic function to return class object def __repr__(self): return ("employee (name={}, emp_id={}, age={}, city={} )" .format(self.name, self.emp_id, self.age, self.city)) # magic function to return boolean def __eq__(self, check): return ((self.name, self.emp_id, self.age, self.city) == ((check.name, check.emp_id, check.age, check.city))) # initialization the objectemp1 = employee("Satyam", "ksatyam858", 21, 'Patna')emp2 = employee("Anurag", "au23", 28, 'Delhi')emp3 = employee("Satyam", "ksatyam858", 21, 'Patna') print("employee object are :")print(emp1)print(emp2)print(emp3) # printing new lineprint() # referring two object to check equalityprint("Data in emp1 and emp2 are same? ", emp1 == emp2)print("Data in emp1 and emp3 are same? ", emp1 == emp3) employee object are : employee (name=Satyam, emp_id=ksatyam858, age=21, city=Patna ) employee (name=Anurag, emp_id=au23, age=28, city=Delhi ) employee (name=Satyam, emp_id=ksatyam858, age=21, city=Patna ) Data in emp1 and emp2 are same? False Data in emp1 and emp3 are same? True In the above code the biggest problem in passing the argument in __init__, __repr__, and __eq__. Each time it has to copy its properties and return the object. It is a good way of dealing with a small amount of data but supposes we have work with large data. It makes your code more complicated. So, that why DataClass will implement to make your code easier and handy. Here are the same example, implemented in Python DataClasses. Python3 # A basic Data Class# importing dataclass modulefrom dataclasses import dataclass # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str emp_id: str age: int city: str emp1 = employee("Satyam", "ksatyam858", 21, 'Patna')emp2 = employee("Anurag", "au23", 28, 'Delhi')emp3 = employee("Satyam", "ksatyam858", 21, 'Patna') print("employee object are :")print(emp1)print(emp2)print(emp3) # printing new lineprint() # referring two object to check equalityprint("Data in emp1 and emp2 are same? ", emp1 == emp2)print("Data in emp1 and emp3 are same? ", emp1 == emp3) Output: employee object are : employee(name=’Satyam’, emp_id=’ksatyam858′, age=21, city=’Patna’) employee(name=’Anurag’, emp_id=’au23′, age=28, city=’Delhi’) employee(name=’Satyam’, emp_id=’ksatyam858′, age=21, city=’Patna’)Data in emp1 and emp2 are same? False Data in emp1 and emp3 are same? True In the above code, we don’t need to write a code for __init__, __repr__, and __eq__ function. The field() objects describe each defined field. Syntax: dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None) Parameters: default default_factory init repr hash compare metadata Example: Demonstration of how to view the fields of a dataclass object. Python3 from dataclasses import dataclass # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str emp_id: str age: int city: str # object of the classemp = employee("Satyam", "ksatyam858", 21, 'Patna') emp.__dataclass_fields__ Output: Explanation of the parameters : default: This field is used to specify default values for this field. Python3 # default field examplefrom dataclasses import dataclass, field # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str emp_id: str age: int # default field set # city : str = "patna" city: str = field(default="patna") emp = employee("Satyam", "ksatyam858", 21)print(emp) Output: employee(name=’Satyam’, emp_id=’ksatyam858′, age=21, city=’patna’) default_factory: This field accepts a function and returns the initial value of the field, it must be a zero-argument. Python3 # default factory examplefrom dataclasses import dataclass, field def get_emp_id(): id = 2345 return id # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str age: int # default factory field emp_id: str = field(default_factory=get_emp_id) city: str = field(default="patna") # object of dataclassemp = employee("Satyam", 21)print(emp) Output: employee(name=’Satyam’, age=21, emp_id=2345, city=’patna’) init : If true this field is included as a parameter to the generated __init__() method. Python3 # init field examplefrom dataclasses import dataclass, field # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str age: int # init field emp_id: str city: str = field(init=False, default="patna") # object of dataclassemp = employee("Satyam", "ksatyam858", 21)print(emp) Output: employee(name=’Satyam’, age=’ksatyam858′, emp_id=21, city=’patna’) repr: If true (the default), this field is included in the string returned by the generated __repr__() method. Python3 # repr fieldfrom dataclasses import dataclass, field # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str age: int emp_id: str city: str = field(init=False, default="patna", repr=True) emp = employee("Satyam", 21, "ksatyam858"),print(emp) Output: employee(name=’Satyam’, age=21, emp_id=’ksatyam858′, city=’patna’) If repr is false then: Python3 city: str = field(init=False, default="patna", repr=False) emp = employee("Satyam", 21, "ksatyam858"),emp Output: employee(name='Satyam', age=21, emp_id='ksatyam858') hash: If true, this field is included in the generated __hash__() method. Python3 # hashfrom dataclasses import dataclass, field # A class for holding an employees content@dataclass(unsafe_hash=True)class employee: # Attributes Declaration # using Type Hints name: str age: int emp_id: str = field(default_factory=get_emp_id) city: str = field(init=False, default="patna", repr=True, hash=True) emp = employee("Satyam", "ksatyam858", 21)hash(emp) Output: 28166796391311520 If false then it will not consider these field. Python3 city: str = field(init=False, default="patna", repr=True, hash=False) # object of the classemp = employee("Satyam", "ksatyam858", 21)hash(emp) Output: 6124029366977666702 compare: If true (the default), this field is included in the generated equality and comparison methods (__eq__(), __gt__(). Python3 # hashfrom dataclasses import dataclass, field # A class for holding an employees content@dataclass(unsafe_hash=True)class employee: # Attributes Declaration # using Type Hints name: str age: int emp_id: str city: str = field(init=False, default="patna", repr=True, hash=False, compare=True) emp1 = employee("Satyam", "ksatyam858", 21)emp2 = employee("Kumar", "satyam.10151", 22)emp1 == emp2 Output: False metadata: This can be a mapping or None. None is treated as an empty dict. Python3 # hashfrom dataclasses import dataclass, field # A class for holding an employees content@dataclass(unsafe_hash=True)class employee: # Attributes Declaration # using Type Hints name: str age: int emp_id: str city: str = field(init=False, default="patna", repr=True, metadata={'format': 'State'}) emp = employee("Satyam", "ksatyam858", 21)emp.__dataclass_fields__['city'].metadata['format'] While creating object __post_init__() method call automatically. __init__() code will call a method named __post_init__(). Example: In an employee dataclass, if we want to check employee age, then we can define into the __post_init__() method. Python3 # A basic Data Class# importing dataclass modulefrom dataclasses import dataclass, field # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str emp_id: str age: int city: str # post init function def __post_init__(self): if self.age >= 30: self.check_age = True else: self.check_age = False emp = employee("Satyam", "ksatyam858", 21, 'Patna')emp.check_age Output: False Inheritance enables us to define a class that takes all the functionality from a parent class. Example: Child class inherits the properties of the parent class. Python3 # A basic Data Class# importing dataclass modulefrom dataclasses import dataclass, field # parent class@dataclassclass Staff: name: str emp_id: str age: int # child class@dataclassclass employee(Staff): salary: int emp = employee("Satyam", "ksatyam858", 21, 60000)emp Output: employee(name='Satyam', emp_id='ksatyam858', age=21, salary=60000) saurabh1990aror adnanirshad158 python-oop-concepts 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 Aug, 2021" }, { "code": null, "e": 294, "s": 28, "text": "DataClasses has been added in a recent addition in python 3.7 as a utility tool for storing data. DataClasses provides a decorator and functions for automatically adding generated special methods such as __init__() , __repr__() and __eq__() to user-defined classes." }, { "code": null, "e": 453, "s": 294, "text": "DataClasses are like normal classes in Python, but they have some basic functions like instantiation, comparing, and printing the classes already implemented." }, { "code": null, "e": 488, "s": 453, "text": "Installing the DataClasses module:" }, { "code": null, "e": 512, "s": 488, "text": "pip install dataclasses" }, { "code": null, "e": 544, "s": 512, "text": "The syntax of the dataclass is:" }, { "code": null, "e": 655, "s": 544, "text": "Syntax: @dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)" }, { "code": null, "e": 667, "s": 655, "text": "Parameters:" }, { "code": null, "e": 718, "s": 667, "text": "init: If true __init__() method will be generated" }, { "code": null, "e": 769, "s": 718, "text": "repr: If true __repr__() method will be generated" }, { "code": null, "e": 816, "s": 769, "text": "eq: If true __eq__() method will be generated" }, { "code": null, "e": 902, "s": 816, "text": "order: If true __lt__(), __le__(), __gt__(), and __ge__() methods will be generated." }, { "code": null, "e": 994, "s": 902, "text": "unsafe_hash: If False __hash__() method is generated according to how eq and frozen are set" }, { "code": null, "e": 1058, "s": 994, "text": "frozen: If true assigning to fields will generate an exception." }, { "code": null, "e": 1185, "s": 1058, "text": "DataClass module provides a handy way to make classes less wordy. Let us see the traditional approach without using DataClass." }, { "code": null, "e": 1193, "s": 1185, "text": "Python3" }, { "code": "# creating a employee classclass employee: # init method or constructor def __init__(self, name, emp_id, age, city): # Instance Variable self.name = name self.emp_id = emp_id self.age = age self.city = city # magic function to return class object def __repr__(self): return (\"employee (name={}, emp_id={}, age={}, city={} )\" .format(self.name, self.emp_id, self.age, self.city)) # magic function to return boolean def __eq__(self, check): return ((self.name, self.emp_id, self.age, self.city) == ((check.name, check.emp_id, check.age, check.city))) # initialization the objectemp1 = employee(\"Satyam\", \"ksatyam858\", 21, 'Patna')emp2 = employee(\"Anurag\", \"au23\", 28, 'Delhi')emp3 = employee(\"Satyam\", \"ksatyam858\", 21, 'Patna') print(\"employee object are :\")print(emp1)print(emp2)print(emp3) # printing new lineprint() # referring two object to check equalityprint(\"Data in emp1 and emp2 are same? \", emp1 == emp2)print(\"Data in emp1 and emp3 are same? \", emp1 == emp3)", "e": 2284, "s": 1193, "text": null }, { "code": null, "e": 2567, "s": 2284, "text": "employee object are :\nemployee (name=Satyam, emp_id=ksatyam858, age=21, city=Patna )\nemployee (name=Anurag, emp_id=au23, age=28, city=Delhi )\nemployee (name=Satyam, emp_id=ksatyam858, age=21, city=Patna )\n\nData in emp1 and emp2 are same? False\nData in emp1 and emp3 are same? True" }, { "code": null, "e": 2937, "s": 2567, "text": "In the above code the biggest problem in passing the argument in __init__, __repr__, and __eq__. Each time it has to copy its properties and return the object. It is a good way of dealing with a small amount of data but supposes we have work with large data. It makes your code more complicated. So, that why DataClass will implement to make your code easier and handy." }, { "code": null, "e": 3000, "s": 2937, "text": "Here are the same example, implemented in Python DataClasses. " }, { "code": null, "e": 3008, "s": 3000, "text": "Python3" }, { "code": "# A basic Data Class# importing dataclass modulefrom dataclasses import dataclass # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str emp_id: str age: int city: str emp1 = employee(\"Satyam\", \"ksatyam858\", 21, 'Patna')emp2 = employee(\"Anurag\", \"au23\", 28, 'Delhi')emp3 = employee(\"Satyam\", \"ksatyam858\", 21, 'Patna') print(\"employee object are :\")print(emp1)print(emp2)print(emp3) # printing new lineprint() # referring two object to check equalityprint(\"Data in emp1 and emp2 are same? \", emp1 == emp2)print(\"Data in emp1 and emp3 are same? \", emp1 == emp3)", "e": 3656, "s": 3008, "text": null }, { "code": null, "e": 3665, "s": 3656, "text": "Output: " }, { "code": null, "e": 3960, "s": 3665, "text": "employee object are : employee(name=’Satyam’, emp_id=’ksatyam858′, age=21, city=’Patna’) employee(name=’Anurag’, emp_id=’au23′, age=28, city=’Delhi’) employee(name=’Satyam’, emp_id=’ksatyam858′, age=21, city=’Patna’)Data in emp1 and emp2 are same? False Data in emp1 and emp3 are same? True " }, { "code": null, "e": 4055, "s": 3960, "text": "In the above code, we don’t need to write a code for __init__, __repr__, and __eq__ function. " }, { "code": null, "e": 4106, "s": 4055, "text": "The field() objects describe each defined field. " }, { "code": null, "e": 4239, "s": 4106, "text": "Syntax: dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)" }, { "code": null, "e": 4251, "s": 4239, "text": "Parameters:" }, { "code": null, "e": 4259, "s": 4251, "text": "default" }, { "code": null, "e": 4275, "s": 4259, "text": "default_factory" }, { "code": null, "e": 4280, "s": 4275, "text": "init" }, { "code": null, "e": 4285, "s": 4280, "text": "repr" }, { "code": null, "e": 4290, "s": 4285, "text": "hash" }, { "code": null, "e": 4298, "s": 4290, "text": "compare" }, { "code": null, "e": 4307, "s": 4298, "text": "metadata" }, { "code": null, "e": 4380, "s": 4307, "text": "Example: Demonstration of how to view the fields of a dataclass object. " }, { "code": null, "e": 4388, "s": 4380, "text": "Python3" }, { "code": "from dataclasses import dataclass # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str emp_id: str age: int city: str # object of the classemp = employee(\"Satyam\", \"ksatyam858\", 21, 'Patna') emp.__dataclass_fields__", "e": 4693, "s": 4388, "text": null }, { "code": null, "e": 4701, "s": 4693, "text": "Output:" }, { "code": null, "e": 4733, "s": 4701, "text": "Explanation of the parameters :" }, { "code": null, "e": 4803, "s": 4733, "text": "default: This field is used to specify default values for this field." }, { "code": null, "e": 4811, "s": 4803, "text": "Python3" }, { "code": "# default field examplefrom dataclasses import dataclass, field # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str emp_id: str age: int # default field set # city : str = \"patna\" city: str = field(default=\"patna\") emp = employee(\"Satyam\", \"ksatyam858\", 21)print(emp)", "e": 5183, "s": 4811, "text": null }, { "code": null, "e": 5191, "s": 5183, "text": "Output:" }, { "code": null, "e": 5260, "s": 5191, "text": "employee(name=’Satyam’, emp_id=’ksatyam858′, age=21, city=’patna’) " }, { "code": null, "e": 5379, "s": 5260, "text": "default_factory: This field accepts a function and returns the initial value of the field, it must be a zero-argument." }, { "code": null, "e": 5387, "s": 5379, "text": "Python3" }, { "code": "# default factory examplefrom dataclasses import dataclass, field def get_emp_id(): id = 2345 return id # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str age: int # default factory field emp_id: str = field(default_factory=get_emp_id) city: str = field(default=\"patna\") # object of dataclassemp = employee(\"Satyam\", 21)print(emp)", "e": 5826, "s": 5387, "text": null }, { "code": null, "e": 5834, "s": 5826, "text": "Output:" }, { "code": null, "e": 5895, "s": 5834, "text": "employee(name=’Satyam’, age=21, emp_id=2345, city=’patna’) " }, { "code": null, "e": 5984, "s": 5895, "text": "init : If true this field is included as a parameter to the generated __init__() method." }, { "code": null, "e": 5992, "s": 5984, "text": "Python3" }, { "code": "# init field examplefrom dataclasses import dataclass, field # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str age: int # init field emp_id: str city: str = field(init=False, default=\"patna\") # object of dataclassemp = employee(\"Satyam\", \"ksatyam858\", 21)print(emp)", "e": 6360, "s": 5992, "text": null }, { "code": null, "e": 6368, "s": 6360, "text": "Output:" }, { "code": null, "e": 6437, "s": 6368, "text": "employee(name=’Satyam’, age=’ksatyam858′, emp_id=21, city=’patna’) " }, { "code": null, "e": 6548, "s": 6437, "text": "repr: If true (the default), this field is included in the string returned by the generated __repr__() method." }, { "code": null, "e": 6556, "s": 6548, "text": "Python3" }, { "code": "# repr fieldfrom dataclasses import dataclass, field # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str age: int emp_id: str city: str = field(init=False, default=\"patna\", repr=True) emp = employee(\"Satyam\", 21, \"ksatyam858\"),print(emp)", "e": 6883, "s": 6556, "text": null }, { "code": null, "e": 6892, "s": 6883, "text": "Output: " }, { "code": null, "e": 6961, "s": 6892, "text": "employee(name=’Satyam’, age=21, emp_id=’ksatyam858′, city=’patna’) " }, { "code": null, "e": 6985, "s": 6961, "text": "If repr is false then: " }, { "code": null, "e": 6993, "s": 6985, "text": "Python3" }, { "code": "city: str = field(init=False, default=\"patna\", repr=False) emp = employee(\"Satyam\", 21, \"ksatyam858\"),emp", "e": 7099, "s": 6993, "text": null }, { "code": null, "e": 7107, "s": 7099, "text": "Output:" }, { "code": null, "e": 7160, "s": 7107, "text": "employee(name='Satyam', age=21, emp_id='ksatyam858')" }, { "code": null, "e": 7234, "s": 7160, "text": "hash: If true, this field is included in the generated __hash__() method." }, { "code": null, "e": 7242, "s": 7234, "text": "Python3" }, { "code": "# hashfrom dataclasses import dataclass, field # A class for holding an employees content@dataclass(unsafe_hash=True)class employee: # Attributes Declaration # using Type Hints name: str age: int emp_id: str = field(default_factory=get_emp_id) city: str = field(init=False, default=\"patna\", repr=True, hash=True) emp = employee(\"Satyam\", \"ksatyam858\", 21)hash(emp)", "e": 7626, "s": 7242, "text": null }, { "code": null, "e": 7634, "s": 7626, "text": "Output:" }, { "code": null, "e": 7652, "s": 7634, "text": "28166796391311520" }, { "code": null, "e": 7700, "s": 7652, "text": "If false then it will not consider these field." }, { "code": null, "e": 7708, "s": 7700, "text": "Python3" }, { "code": "city: str = field(init=False, default=\"patna\", repr=True, hash=False) # object of the classemp = employee(\"Satyam\", \"ksatyam858\", 21)hash(emp)", "e": 7851, "s": 7708, "text": null }, { "code": null, "e": 7859, "s": 7851, "text": "Output:" }, { "code": null, "e": 7879, "s": 7859, "text": "6124029366977666702" }, { "code": null, "e": 8004, "s": 7879, "text": "compare: If true (the default), this field is included in the generated equality and comparison methods (__eq__(), __gt__()." }, { "code": null, "e": 8012, "s": 8004, "text": "Python3" }, { "code": "# hashfrom dataclasses import dataclass, field # A class for holding an employees content@dataclass(unsafe_hash=True)class employee: # Attributes Declaration # using Type Hints name: str age: int emp_id: str city: str = field(init=False, default=\"patna\", repr=True, hash=False, compare=True) emp1 = employee(\"Satyam\", \"ksatyam858\", 21)emp2 = employee(\"Kumar\", \"satyam.10151\", 22)emp1 == emp2", "e": 8445, "s": 8012, "text": null }, { "code": null, "e": 8453, "s": 8445, "text": "Output:" }, { "code": null, "e": 8459, "s": 8453, "text": "False" }, { "code": null, "e": 8534, "s": 8459, "text": "metadata: This can be a mapping or None. None is treated as an empty dict." }, { "code": null, "e": 8542, "s": 8534, "text": "Python3" }, { "code": "# hashfrom dataclasses import dataclass, field # A class for holding an employees content@dataclass(unsafe_hash=True)class employee: # Attributes Declaration # using Type Hints name: str age: int emp_id: str city: str = field(init=False, default=\"patna\", repr=True, metadata={'format': 'State'}) emp = employee(\"Satyam\", \"ksatyam858\", 21)emp.__dataclass_fields__['city'].metadata['format']", "e": 8972, "s": 8542, "text": null }, { "code": null, "e": 9096, "s": 8972, "text": " While creating object __post_init__() method call automatically. __init__() code will call a method named __post_init__()." }, { "code": null, "e": 9217, "s": 9096, "text": "Example: In an employee dataclass, if we want to check employee age, then we can define into the __post_init__() method." }, { "code": null, "e": 9225, "s": 9217, "text": "Python3" }, { "code": "# A basic Data Class# importing dataclass modulefrom dataclasses import dataclass, field # A class for holding an employees content@dataclassclass employee: # Attributes Declaration # using Type Hints name: str emp_id: str age: int city: str # post init function def __post_init__(self): if self.age >= 30: self.check_age = True else: self.check_age = False emp = employee(\"Satyam\", \"ksatyam858\", 21, 'Patna')emp.check_age", "e": 9712, "s": 9225, "text": null }, { "code": null, "e": 9720, "s": 9712, "text": "Output:" }, { "code": null, "e": 9726, "s": 9720, "text": "False" }, { "code": null, "e": 9821, "s": 9726, "text": "Inheritance enables us to define a class that takes all the functionality from a parent class." }, { "code": null, "e": 9887, "s": 9821, "text": "Example: Child class inherits the properties of the parent class." }, { "code": null, "e": 9895, "s": 9887, "text": "Python3" }, { "code": "# A basic Data Class# importing dataclass modulefrom dataclasses import dataclass, field # parent class@dataclassclass Staff: name: str emp_id: str age: int # child class@dataclassclass employee(Staff): salary: int emp = employee(\"Satyam\", \"ksatyam858\", 21, 60000)emp", "e": 10177, "s": 9895, "text": null }, { "code": null, "e": 10185, "s": 10177, "text": "Output:" }, { "code": null, "e": 10252, "s": 10185, "text": "employee(name='Satyam', emp_id='ksatyam858', age=21, salary=60000)" }, { "code": null, "e": 10268, "s": 10252, "text": "saurabh1990aror" }, { "code": null, "e": 10283, "s": 10268, "text": "adnanirshad158" }, { "code": null, "e": 10303, "s": 10283, "text": "python-oop-concepts" }, { "code": null, "e": 10310, "s": 10303, "text": "Python" } ]
MySQL query to set values for NULL occurrence
Find NULL values using the IS NULL and update the new values using MySQL UPDATE and SET − update yourTableName set yourColumnName=yourValue where yourColumnName IS NULL; Let us first create a table − mysql> create table DemoTable768 ( Clientid int NOT NULL AUTO_INCREMENT PRIMARY KEY, ClientName varchar(100), ClientAge int ); Query OK, 0 rows affected (0.47 sec) Insert some records in the table using insert command − mysql> insert into DemoTable768(ClientName,ClientAge) values('John',23); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable768(ClientName,ClientAge) values(NULL,26); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable768(ClientName,ClientAge) values('Carol',28); Query OK, 1 row affected (0.53 sec) mysql> insert into DemoTable768(ClientName,ClientAge) values(NULL,24); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement − mysql> select *from DemoTable768; This will produce the following output - +----------+------------+-----------+ | Clientid | ClientName | ClientAge | +----------+------------+-----------+ | 1 | John | 23 | | 2 | NULL | 26 | | 3 | Carol | 28 | | 4 | NULL | 24 | +----------+------------+-----------+ 4 rows in set (0.00 sec) Following is the query to set values for NULL occurrence − mysql> update DemoTable768 set ClientName='Chris' where ClientName IS NULL; Query OK, 2 rows affected (0.41 sec) Rows matched: 2 Changed: 2 Warnings: 0 Let us check the description of the view − mysql> select *from DemoTable768; This will produce the following output - +----------+------------+-----------+ | Clientid | ClientName | ClientAge | +----------+------------+-----------+ | 1 | John | 23 | | 2 | Chris | 26 | | 3 | Carol | 28 | | 4 | Chris | 24 | +----------+------------+-----------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1277, "s": 1187, "text": "Find NULL values using the IS NULL and update the new values using MySQL UPDATE and SET −" }, { "code": null, "e": 1357, "s": 1277, "text": "update yourTableName\nset yourColumnName=yourValue\nwhere yourColumnName IS NULL;" }, { "code": null, "e": 1387, "s": 1357, "text": "Let us first create a table −" }, { "code": null, "e": 1560, "s": 1387, "text": "mysql> create table DemoTable768 (\n Clientid int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n ClientName varchar(100),\n ClientAge int\n);\nQuery OK, 0 rows affected (0.47 sec)" }, { "code": null, "e": 1616, "s": 1560, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2049, "s": 1616, "text": "mysql> insert into DemoTable768(ClientName,ClientAge) values('John',23);\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable768(ClientName,ClientAge) values(NULL,26);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable768(ClientName,ClientAge) values('Carol',28);\nQuery OK, 1 row affected (0.53 sec)\nmysql> insert into DemoTable768(ClientName,ClientAge) values(NULL,24);\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2109, "s": 2049, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2143, "s": 2109, "text": "mysql> select *from DemoTable768;" }, { "code": null, "e": 2184, "s": 2143, "text": "This will produce the following output -" }, { "code": null, "e": 2513, "s": 2184, "text": "+----------+------------+-----------+\n| Clientid | ClientName | ClientAge |\n+----------+------------+-----------+\n| 1 | John | 23 |\n| 2 | NULL | 26 |\n| 3 | Carol | 28 |\n| 4 | NULL | 24 |\n+----------+------------+-----------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2572, "s": 2513, "text": "Following is the query to set values for NULL occurrence −" }, { "code": null, "e": 2731, "s": 2572, "text": "mysql> update DemoTable768\n set ClientName='Chris'\n where ClientName IS NULL;\nQuery OK, 2 rows affected (0.41 sec)\nRows matched: 2 Changed: 2 Warnings: 0" }, { "code": null, "e": 2774, "s": 2731, "text": "Let us check the description of the view −" }, { "code": null, "e": 2808, "s": 2774, "text": "mysql> select *from DemoTable768;" }, { "code": null, "e": 2849, "s": 2808, "text": "This will produce the following output -" }, { "code": null, "e": 3178, "s": 2849, "text": "+----------+------------+-----------+\n| Clientid | ClientName | ClientAge |\n+----------+------------+-----------+\n| 1 | John | 23 |\n| 2 | Chris | 26 |\n| 3 | Carol | 28 |\n| 4 | Chris | 24 |\n+----------+------------+-----------+\n4 rows in set (0.00 sec)" } ]
White and black dot detection using OpenCV | Python
19 Jul, 2019 Image processing using Python is one of the hottest topics in today’s world. But image processing is a bit complex and beginners get bored in their first approach. So in this article, we have a very basic image processing python program to count black dots in white surface and white dots in the black surface using OpenCV functions (cv2.imread, cv2.threshold, cv2.findContours, cv2.contourArea). At first we need to import OpenCV library. All functions regarding image processing reside in this library. In order to store the path of the image we are going to process in a variable path. import cv2 # path ="C:/Users/Personal/Downloads/black dot.jpg"path ="black dot.jpg" Input Image – Loading an image in grayscale mode. By grayscale mode, the image is converted to a black & white image composing by shades of gray. gray = cv2.imread(path, 0) The function cv2.threshold works as, if pixel value is greater than a threshold value, it is assigned one value (may be white), else it is assigned another value (may be black). First argument is the source image, which should be a grayscale image(done previously). Second argument is the threshold value which is used to classify the pixel values. For threshold value, simply pass zero. Then the algorithm finds the optimal threshold value and returns you as the second output, th. If Otsu thresholding is not used, th is same as the threshold value you used. # thresholdth, threshed = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU) Contours can be explained simply as a curve joining all the continuous points (along the boundary), having same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition. Contours give better accuracy for using binary images. There are three arguments in cv2.findContours() function, first one is source image, second is contour retrieval mode, third is contour approximation method. It outputs the contours and hierarchy. Contours is a Python list of all the contours in the image. Each individual contour is a Numpy array of (x, y) coordinates of boundary points of the object. It mainly connects the black dots of the image to count – # findcontourscnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2] cv2.contourArea() can calculate the contour area of the object. Here the object is the black dots. when it gets a black dot it will calculate the area and if it satisfies the condition of minimum area to be count as a dot, then it will push the value of its area to the list xcnts. # filter by areas1 = 3s2 = 20xcnts = []for cnt in cnts: if s1<cv2.contourArea(cnt) <s2: xcnts.append(cnt) At last, we don’t need the areas. If it is considered to be a dot, then its area is included in the list xcnts. So we will get the number of the dots if we calculate the length of the list. print("\nDots number: {}".format(len(xcnts))) Output : 23 Now for counting the white dots we need to change the threshold a little bit. we have to use cv2.THRESH_BINARY instead of cv2.THRESH_BINARY_INV because we are counting white values on the black surface. The other process are the same. We can change the s1 and s2 values to check for the best result. Input Image: import cv2path ="white dot.png" # reading the image in grayscale modegray = cv2.imread(path, 0) # thresholdth, threshed = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU) # findcontourscnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2] # filter by areas1 = 3s2 = 20xcnts = [] for cnt in cnts: if s1<cv2.contourArea(cnt) <s2: xcnts.append(cnt) # printing outputprint("\nDots number: {}".format(len(xcnts))) Output : 583 References:https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_thresholding/py_thresholding.htmlhttps://docs.opencv.org/3.1.0/d4/d73/tutorial_py_contours_begin.html Image-Processing OpenCV 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Jul, 2019" }, { "code": null, "e": 450, "s": 53, "text": "Image processing using Python is one of the hottest topics in today’s world. But image processing is a bit complex and beginners get bored in their first approach. So in this article, we have a very basic image processing python program to count black dots in white surface and white dots in the black surface using OpenCV functions (cv2.imread, cv2.threshold, cv2.findContours, cv2.contourArea)." }, { "code": null, "e": 642, "s": 450, "text": "At first we need to import OpenCV library. All functions regarding image processing reside in this library. In order to store the path of the image we are going to process in a variable path." }, { "code": "import cv2", "e": 653, "s": 642, "text": null }, { "code": "# path =\"C:/Users/Personal/Downloads/black dot.jpg\"path =\"black dot.jpg\"", "e": 726, "s": 653, "text": null }, { "code": null, "e": 740, "s": 726, "text": "Input Image –" }, { "code": null, "e": 872, "s": 740, "text": "Loading an image in grayscale mode. By grayscale mode, the image is converted to a black & white image composing by shades of gray." }, { "code": "gray = cv2.imread(path, 0)", "e": 899, "s": 872, "text": null }, { "code": null, "e": 1460, "s": 899, "text": "The function cv2.threshold works as, if pixel value is greater than a threshold value, it is assigned one value (may be white), else it is assigned another value (may be black). First argument is the source image, which should be a grayscale image(done previously). Second argument is the threshold value which is used to classify the pixel values. For threshold value, simply pass zero. Then the algorithm finds the optimal threshold value and returns you as the second output, th. If Otsu thresholding is not used, th is same as the threshold value you used." }, { "code": "# thresholdth, threshed = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)", "e": 1561, "s": 1460, "text": null }, { "code": null, "e": 2190, "s": 1561, "text": "Contours can be explained simply as a curve joining all the continuous points (along the boundary), having same color or intensity. The contours are a useful tool for shape analysis and object detection and recognition. Contours give better accuracy for using binary images. There are three arguments in cv2.findContours() function, first one is source image, second is contour retrieval mode, third is contour approximation method. It outputs the contours and hierarchy. Contours is a Python list of all the contours in the image. Each individual contour is a Numpy array of (x, y) coordinates of boundary points of the object." }, { "code": null, "e": 2248, "s": 2190, "text": "It mainly connects the black dots of the image to count –" }, { "code": "# findcontourscnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]", "e": 2359, "s": 2248, "text": null }, { "code": null, "e": 2641, "s": 2359, "text": "cv2.contourArea() can calculate the contour area of the object. Here the object is the black dots. when it gets a black dot it will calculate the area and if it satisfies the condition of minimum area to be count as a dot, then it will push the value of its area to the list xcnts." }, { "code": "# filter by areas1 = 3s2 = 20xcnts = []for cnt in cnts: if s1<cv2.contourArea(cnt) <s2: xcnts.append(cnt)", "e": 2757, "s": 2641, "text": null }, { "code": null, "e": 2947, "s": 2757, "text": "At last, we don’t need the areas. If it is considered to be a dot, then its area is included in the list xcnts. So we will get the number of the dots if we calculate the length of the list." }, { "code": "print(\"\\nDots number: {}\".format(len(xcnts)))", "e": 2993, "s": 2947, "text": null }, { "code": null, "e": 3002, "s": 2993, "text": "Output :" }, { "code": null, "e": 3005, "s": 3002, "text": "23" }, { "code": null, "e": 3305, "s": 3005, "text": "Now for counting the white dots we need to change the threshold a little bit. we have to use cv2.THRESH_BINARY instead of cv2.THRESH_BINARY_INV because we are counting white values on the black surface. The other process are the same. We can change the s1 and s2 values to check for the best result." }, { "code": null, "e": 3318, "s": 3305, "text": "Input Image:" }, { "code": "import cv2path =\"white dot.png\" # reading the image in grayscale modegray = cv2.imread(path, 0) # thresholdth, threshed = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU) # findcontourscnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2] # filter by areas1 = 3s2 = 20xcnts = [] for cnt in cnts: if s1<cv2.contourArea(cnt) <s2: xcnts.append(cnt) # printing outputprint(\"\\nDots number: {}\".format(len(xcnts)))", "e": 3813, "s": 3318, "text": null }, { "code": null, "e": 3822, "s": 3813, "text": "Output :" }, { "code": null, "e": 3826, "s": 3822, "text": "583" }, { "code": null, "e": 4005, "s": 3828, "text": "References:https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_thresholding/py_thresholding.htmlhttps://docs.opencv.org/3.1.0/d4/d73/tutorial_py_contours_begin.html" }, { "code": null, "e": 4022, "s": 4005, "text": "Image-Processing" }, { "code": null, "e": 4029, "s": 4022, "text": "OpenCV" }, { "code": null, "e": 4036, "s": 4029, "text": "Python" }, { "code": null, "e": 4134, "s": 4036, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4152, "s": 4134, "text": "Python Dictionary" }, { "code": null, "e": 4194, "s": 4152, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4216, "s": 4194, "text": "Enumerate() in Python" }, { "code": null, "e": 4242, "s": 4216, "text": "Python String | replace()" }, { "code": null, "e": 4274, "s": 4242, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4303, "s": 4274, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4330, "s": 4303, "text": "Python Classes and Objects" }, { "code": null, "e": 4351, "s": 4330, "text": "Python OOPs Concepts" }, { "code": null, "e": 4387, "s": 4351, "text": "Convert integer to string in Python" } ]
Partition the array into three equal sum segments
06 Jul, 2021 Given an array of n integers, we have to partition the array into three segments such that all the segments have an equal sum. Segment sum is the sum of all the elements in the segment. Examples: Input : 1, 3, 6, 2, 7, 1, 2, 8 Output : [1, 3, 6], [2, 7, 1], [2, 8] Input : 7, 6, 1, 7 Output : [7], [6, 1], [7] Input : 7, 6, 2, 7 Output : Cannot divide the array into segments A simple solution is to consider all pairs of indexes and, for every pair, check if it divides the array into three equal parts. If yes, then return true. The time complexity of this solution is O(n2) An efficient approach is to use two auxiliary arrays and store the prefix and suffix array sum in these arrays respectively. We then use the two-pointer approach, with variable ‘i’ pointing to the start of the prefix array and variable ‘j’ pointing to the end of the suffix array. If pre[i] > suf[j], then decrement ‘j’, otherwise increment ‘i’. We maintain a variable whose value is the total sum of the array and whenever we encounter pre[i] = total_sum / 3 or suf[j] = total_sum / 3, we store the value of i or j respectively as segment boundaries. C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // First segment's end indexstatic int pos1 = -1; // Third segment's start indexstatic int pos2 = -1; // This function returns true if the array// can be divided into three equal sum segmentsbool equiSumUtil(int arr[],int n){ // Prefix Sum Array int pre[n]; int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; pre[i] = sum; } // Suffix Sum Array int suf[n]; sum = 0; for (int i = n - 1; i >= 0; i--) { sum += arr[i]; suf[i] = sum; } // Stores the total sum of the array int total_sum = sum; int i = 0, j = n - 1; while (i < j - 1) { if (pre[i] == total_sum / 3) { pos1 = i; } if (suf[j] == total_sum / 3) { pos2 = j; } if (pos1 != -1 && pos2 != -1) { // We can also take pre[pos2 - 1] - pre[pos1] == // total_sum / 3 here. if (suf[pos1 + 1] - suf[pos2] == total_sum / 3) { return true; } else { return false; } } if (pre[i] < suf[j]) { i++; } else { j--; } } return false;} void equiSum(int arr[],int n){ bool ans = equiSumUtil(arr,n); if (ans) { cout << "First Segment : "; for (int i = 0; i <= pos1; i++) { cout << arr[i] << " "; } cout << endl; cout << "Second Segment : "; for (int i = pos1 + 1; i < pos2; i++) { cout << arr[i] << " "; } cout << endl; cout << "Third Segment : "; for (int i = pos2; i < n; i++) { cout << arr[i] << " "; } cout<<endl; } else { cout << "Array cannot be divided into three equal sum segments"; }} // Driver codeint main(){ int arr[] = { 1, 3, 6, 2, 7, 1, 2, 8 }; int n = sizeof(arr) / sizeof(arr[0]); equiSum(arr,n); return 0;} // This code is contributed by mits public class Main { // First segment's end index public static int pos1 = -1; // Third segment's start index public static int pos2 = -1; // This function returns true if the array // can be divided into three equal sum segments public static boolean equiSumUtil(int[] arr) { int n = arr.length; // Prefix Sum Array int[] pre = new int[n]; int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; pre[i] = sum; } // Suffix Sum Array int[] suf = new int[n]; sum = 0; for (int i = n - 1; i >= 0; i--) { sum += arr[i]; suf[i] = sum; } // Stores the total sum of the array int total_sum = sum; int i = 0, j = n - 1; while (i < j - 1) { if (pre[i] == total_sum / 3) { pos1 = i; } if (suf[j] == total_sum / 3) { pos2 = j; } if (pos1 != -1 && pos2 != -1) { // We can also take pre[pos2 - 1] - pre[pos1] == // total_sum / 3 here. if (suf[pos1 + 1] - suf[pos2] == total_sum / 3) { return true; } else { return false; } } if (pre[i] < suf[j]) { i++; } else { j--; } } return false; } public static void equiSum(int[] arr) { boolean ans = equiSumUtil(arr); if (ans) { System.out.print("First Segment : "); for (int i = 0; i <= pos1; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.print("Second Segment : "); for (int i = pos1 + 1; i < pos2; i++) { System.out.print(arr[i] + " "); } System.out.println(); System.out.print("Third Segment : "); for (int i = pos2; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } else { System.out.println("Array cannot be " + "divided into three equal sum segments"); } } public static void main(String[] args) { int[] arr = { 1, 3, 6, 2, 7, 1, 2, 8 }; equiSum(arr); }} # Python3 implementation of the given approach # This function returns true if the array# can be divided into three equal sum segmentsdef equiSumUtil(arr, pos1, pos2): n = len(arr); # Prefix Sum Array pre = [0] * n; sum = 0; for i in range(n): sum += arr[i]; pre[i] = sum; # Suffix Sum Array suf = [0] * n; sum = 0; for i in range(n - 1, -1, -1): sum += arr[i]; suf[i] = sum; # Stores the total sum of the array total_sum = sum; i = 0; j = n - 1; while (i < j - 1): if (pre[i] == total_sum // 3): pos1 = i; if (suf[j] == total_sum // 3): pos2 = j; if (pos1 != -1 and pos2 != -1): # We can also take pre[pos2 - 1] - pre[pos1] == # total_sum / 3 here. if (suf[pos1 + 1] - suf[pos2] == total_sum // 3): return [True, pos1, pos2]; else: return [False, pos1, pos2]; if (pre[i] < suf[j]): i += 1; else: j -= 1; return [False, pos1, pos2]; def equiSum(arr): pos1 = -1; pos2 = -1; ans = equiSumUtil(arr, pos1, pos2); pos1 = ans[1]; pos2 = ans[2]; if (ans[0]): print("First Segment : ", end = ""); for i in range(pos1 + 1): print(arr[i], end = " "); print(""); print("Second Segment : ", end = ""); for i in range(pos1 + 1, pos2): print(arr[i], end = " "); print(""); print("Third Segment : ", end = ""); for i in range(pos2, len(arr)): print(arr[i], end = " "); print(""); else: println("Array cannot be divided into", "three equal sum segments"); # Driver Codearr = [1, 3, 6, 2, 7, 1, 2, 8 ];equiSum(arr); # This code is contributed by mits // C# implementation of the approachusing System; class GFG{ // First segment's end index public static int pos1 = -1; // Third segment's start index public static int pos2 = -1; // This function returns true if the array // can be divided into three equal sum segments public static bool equiSumUtil(int[] arr) { int n = arr.Length; // Prefix Sum Array int[] pre = new int[n]; int sum = 0,i; for (i = 0; i < n; i++) { sum += arr[i]; pre[i] = sum; } // Suffix Sum Array int[] suf = new int[n]; sum = 0; for (i = n - 1; i >= 0; i--) { sum += arr[i]; suf[i] = sum; } // Stores the total sum of the array int total_sum = sum; int j = n - 1; i = 0; while (i < j - 1) { if (pre[i] == total_sum / 3) { pos1 = i; } if (suf[j] == total_sum / 3) { pos2 = j; } if (pos1 != -1 && pos2 != -1) { // We can also take pre[pos2 - 1] - pre[pos1] == // total_sum / 3 here. if (suf[pos1 + 1] - suf[pos2] == total_sum / 3) { return true; } else { return false; } } if (pre[i] < suf[j]) { i++; } else { j--; } } return false; } public static void equiSum(int[] arr) { bool ans = equiSumUtil(arr); if (ans) { Console.Write("First Segment : "); for (int i = 0; i <= pos1; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(); Console.Write("Second Segment : "); for (int i = pos1 + 1; i < pos2; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(); Console.Write("Third Segment : "); for (int i = pos2; i < arr.Length; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(); } else { Console.WriteLine("Array cannot be " + "divided into three equal sum segments"); } } public static void Main(String[] args) { int[] arr = { 1, 3, 6, 2, 7, 1, 2, 8 }; equiSum(arr); }} // This code contributed by Rajput-Ji <?php// PHP implementation of the given approach // First segment's end index$pos1 = -1; // Third segment's start index$pos2 = -1; // This function returns true if the array// can be divided into three equal sum segmentsfunction equiSumUtil($arr){ global $pos2, $pos1; $n = count($arr); // Prefix Sum Array $pre = array_fill(0, $n, 0); $sum = 0; for ($i = 0; $i < $n; $i++) { $sum += $arr[$i]; $pre[$i] = $sum; } // Suffix Sum Array $suf = array_fill(0, $n, 0); $sum = 0; for ($i = $n - 1; $i >= 0; $i--) { $sum += $arr[$i]; $suf[$i] = $sum; } // Stores the total sum of the array $total_sum = $sum; $i = 0; $j = $n - 1; while ($i < $j - 1) { if ($pre[$i] == $total_sum / 3) { $pos1 = $i; } if ($suf[$j] == $total_sum / 3) { $pos2 = $j; } if ($pos1 != -1 && $pos2 != -1) { // We can also take pre[pos2 - 1] - pre[pos1] == // total_sum / 3 here. if ($suf[$pos1 + 1] - $suf[$pos2] == $total_sum / 3) { return true; } else { return false; } } if ($pre[$i] < $suf[$j]) { $i++; } else { $j--; } } return false;} function equiSum($arr){ global $pos2,$pos1; $ans = equiSumUtil($arr); if ($ans) { print("First Segment : "); for ($i = 0; $i <= $pos1; $i++) { print($arr[$i] . " "); } print("\n"); print("Second Segment : "); for ($i = $pos1 + 1; $i < $pos2; $i++) { print($arr[$i] . " "); } print("\n"); print("Third Segment : "); for ($i = $pos2; $i < count($arr); $i++) { print($arr[$i] . " "); } print("\n"); } else { println("Array cannot be divided into ", "three equal sum segments"); }} // Driver Code$arr = array(1, 3, 6, 2, 7, 1, 2, 8 );equiSum($arr); // This code is contributed by mits?> <script> // C# implementation of the approach // First segment's end indexlet pos1 = -1; // Third segment's start indexlet pos2 = -1; // This function returns true if the array// can be divided into three equal sum segmentsfunction equiSumUtil(arr){ let n = arr.length; // Prefix Sum Array let pre = new Array(n); let sum = 0,i; for (i = 0; i < n; i++) { sum += arr[i]; pre[i] = sum; } // Suffix Sum Array let suf = new Array(n); sum = 0; for (i = n - 1; i >= 0; i--) { sum += arr[i]; suf[i] = sum; } // Stores the total sum of the array let total_sum = sum; let j = n - 1; i = 0; while (i < j - 1) { if (pre[i] == total_sum / 3) { pos1 = i; } if (suf[j] == total_sum / 3) { pos2 = j; } if (pos1 != -1 && pos2 != -1) { // We can also take pre[pos2 - 1] - pre[pos1] == // total_sum / 3 here. if (suf[pos1 + 1] - suf[pos2] == total_sum / 3) { return true; } else { return false; } } if (pre[i] < suf[j]) { i++; } else { j--; } } return false;} function equiSum(arr){ let ans = equiSumUtil(arr); if (ans) { document.write("First Segment : "); for (let i = 0; i <= pos1; i++) { document.write(arr[i] + " "); } document.write("<br>"); document.write("Second Segment : "); for (let i = pos1 + 1; i < pos2; i++) { document.write(arr[i] + " "); } document.write("<br>"); document.write("Third Segment : "); for (let i = pos2; i < arr.length; i++) { document.write(arr[i] + " "); } document.write("<br>"); } else { document.writeLine("Array cannot be" + " divided into three equal sum segments"); }} let arr =[1, 3, 6, 2, 7, 1, 2, 8];equiSum(arr); </script> First Segment : 1 3 6 Second Segment : 2 7 1 Third Segment : 2 8 Time Complexity : O(n) Auxiliary Space : O(n) Rajput-Ji Mithun Kumar mohit kumar 29 bunnyram19 Marketing prefix-sum Arrays Searching prefix-sum Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search K'th Smallest/Largest Element in Unsorted Array | Set 1 Search an element in a sorted and rotated array
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2021" }, { "code": null, "e": 240, "s": 54, "text": "Given an array of n integers, we have to partition the array into three segments such that all the segments have an equal sum. Segment sum is the sum of all the elements in the segment." }, { "code": null, "e": 252, "s": 240, "text": "Examples: " }, { "code": null, "e": 439, "s": 252, "text": "Input : 1, 3, 6, 2, 7, 1, 2, 8\nOutput : [1, 3, 6], [2, 7, 1], [2, 8]\n\nInput : 7, 6, 1, 7\nOutput : [7], [6, 1], [7]\n\nInput : 7, 6, 2, 7\nOutput : Cannot divide the array into segments " }, { "code": null, "e": 640, "s": 439, "text": "A simple solution is to consider all pairs of indexes and, for every pair, check if it divides the array into three equal parts. If yes, then return true. The time complexity of this solution is O(n2)" }, { "code": null, "e": 1194, "s": 640, "text": "An efficient approach is to use two auxiliary arrays and store the prefix and suffix array sum in these arrays respectively. We then use the two-pointer approach, with variable ‘i’ pointing to the start of the prefix array and variable ‘j’ pointing to the end of the suffix array. If pre[i] > suf[j], then decrement ‘j’, otherwise increment ‘i’. We maintain a variable whose value is the total sum of the array and whenever we encounter pre[i] = total_sum / 3 or suf[j] = total_sum / 3, we store the value of i or j respectively as segment boundaries. " }, { "code": null, "e": 1198, "s": 1194, "text": "C++" }, { "code": null, "e": 1203, "s": 1198, "text": "Java" }, { "code": null, "e": 1211, "s": 1203, "text": "Python3" }, { "code": null, "e": 1214, "s": 1211, "text": "C#" }, { "code": null, "e": 1218, "s": 1214, "text": "PHP" }, { "code": null, "e": 1229, "s": 1218, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // First segment's end indexstatic int pos1 = -1; // Third segment's start indexstatic int pos2 = -1; // This function returns true if the array// can be divided into three equal sum segmentsbool equiSumUtil(int arr[],int n){ // Prefix Sum Array int pre[n]; int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; pre[i] = sum; } // Suffix Sum Array int suf[n]; sum = 0; for (int i = n - 1; i >= 0; i--) { sum += arr[i]; suf[i] = sum; } // Stores the total sum of the array int total_sum = sum; int i = 0, j = n - 1; while (i < j - 1) { if (pre[i] == total_sum / 3) { pos1 = i; } if (suf[j] == total_sum / 3) { pos2 = j; } if (pos1 != -1 && pos2 != -1) { // We can also take pre[pos2 - 1] - pre[pos1] == // total_sum / 3 here. if (suf[pos1 + 1] - suf[pos2] == total_sum / 3) { return true; } else { return false; } } if (pre[i] < suf[j]) { i++; } else { j--; } } return false;} void equiSum(int arr[],int n){ bool ans = equiSumUtil(arr,n); if (ans) { cout << \"First Segment : \"; for (int i = 0; i <= pos1; i++) { cout << arr[i] << \" \"; } cout << endl; cout << \"Second Segment : \"; for (int i = pos1 + 1; i < pos2; i++) { cout << arr[i] << \" \"; } cout << endl; cout << \"Third Segment : \"; for (int i = pos2; i < n; i++) { cout << arr[i] << \" \"; } cout<<endl; } else { cout << \"Array cannot be divided into three equal sum segments\"; }} // Driver codeint main(){ int arr[] = { 1, 3, 6, 2, 7, 1, 2, 8 }; int n = sizeof(arr) / sizeof(arr[0]); equiSum(arr,n); return 0;} // This code is contributed by mits", "e": 3368, "s": 1229, "text": null }, { "code": "public class Main { // First segment's end index public static int pos1 = -1; // Third segment's start index public static int pos2 = -1; // This function returns true if the array // can be divided into three equal sum segments public static boolean equiSumUtil(int[] arr) { int n = arr.length; // Prefix Sum Array int[] pre = new int[n]; int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; pre[i] = sum; } // Suffix Sum Array int[] suf = new int[n]; sum = 0; for (int i = n - 1; i >= 0; i--) { sum += arr[i]; suf[i] = sum; } // Stores the total sum of the array int total_sum = sum; int i = 0, j = n - 1; while (i < j - 1) { if (pre[i] == total_sum / 3) { pos1 = i; } if (suf[j] == total_sum / 3) { pos2 = j; } if (pos1 != -1 && pos2 != -1) { // We can also take pre[pos2 - 1] - pre[pos1] == // total_sum / 3 here. if (suf[pos1 + 1] - suf[pos2] == total_sum / 3) { return true; } else { return false; } } if (pre[i] < suf[j]) { i++; } else { j--; } } return false; } public static void equiSum(int[] arr) { boolean ans = equiSumUtil(arr); if (ans) { System.out.print(\"First Segment : \"); for (int i = 0; i <= pos1; i++) { System.out.print(arr[i] + \" \"); } System.out.println(); System.out.print(\"Second Segment : \"); for (int i = pos1 + 1; i < pos2; i++) { System.out.print(arr[i] + \" \"); } System.out.println(); System.out.print(\"Third Segment : \"); for (int i = pos2; i < arr.length; i++) { System.out.print(arr[i] + \" \"); } System.out.println(); } else { System.out.println(\"Array cannot be \" + \"divided into three equal sum segments\"); } } public static void main(String[] args) { int[] arr = { 1, 3, 6, 2, 7, 1, 2, 8 }; equiSum(arr); }}", "e": 5794, "s": 3368, "text": null }, { "code": "# Python3 implementation of the given approach # This function returns true if the array# can be divided into three equal sum segmentsdef equiSumUtil(arr, pos1, pos2): n = len(arr); # Prefix Sum Array pre = [0] * n; sum = 0; for i in range(n): sum += arr[i]; pre[i] = sum; # Suffix Sum Array suf = [0] * n; sum = 0; for i in range(n - 1, -1, -1): sum += arr[i]; suf[i] = sum; # Stores the total sum of the array total_sum = sum; i = 0; j = n - 1; while (i < j - 1): if (pre[i] == total_sum // 3): pos1 = i; if (suf[j] == total_sum // 3): pos2 = j; if (pos1 != -1 and pos2 != -1): # We can also take pre[pos2 - 1] - pre[pos1] == # total_sum / 3 here. if (suf[pos1 + 1] - suf[pos2] == total_sum // 3): return [True, pos1, pos2]; else: return [False, pos1, pos2]; if (pre[i] < suf[j]): i += 1; else: j -= 1; return [False, pos1, pos2]; def equiSum(arr): pos1 = -1; pos2 = -1; ans = equiSumUtil(arr, pos1, pos2); pos1 = ans[1]; pos2 = ans[2]; if (ans[0]): print(\"First Segment : \", end = \"\"); for i in range(pos1 + 1): print(arr[i], end = \" \"); print(\"\"); print(\"Second Segment : \", end = \"\"); for i in range(pos1 + 1, pos2): print(arr[i], end = \" \"); print(\"\"); print(\"Third Segment : \", end = \"\"); for i in range(pos2, len(arr)): print(arr[i], end = \" \"); print(\"\"); else: println(\"Array cannot be divided into\", \"three equal sum segments\"); # Driver Codearr = [1, 3, 6, 2, 7, 1, 2, 8 ];equiSum(arr); # This code is contributed by mits", "e": 7625, "s": 5794, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // First segment's end index public static int pos1 = -1; // Third segment's start index public static int pos2 = -1; // This function returns true if the array // can be divided into three equal sum segments public static bool equiSumUtil(int[] arr) { int n = arr.Length; // Prefix Sum Array int[] pre = new int[n]; int sum = 0,i; for (i = 0; i < n; i++) { sum += arr[i]; pre[i] = sum; } // Suffix Sum Array int[] suf = new int[n]; sum = 0; for (i = n - 1; i >= 0; i--) { sum += arr[i]; suf[i] = sum; } // Stores the total sum of the array int total_sum = sum; int j = n - 1; i = 0; while (i < j - 1) { if (pre[i] == total_sum / 3) { pos1 = i; } if (suf[j] == total_sum / 3) { pos2 = j; } if (pos1 != -1 && pos2 != -1) { // We can also take pre[pos2 - 1] - pre[pos1] == // total_sum / 3 here. if (suf[pos1 + 1] - suf[pos2] == total_sum / 3) { return true; } else { return false; } } if (pre[i] < suf[j]) { i++; } else { j--; } } return false; } public static void equiSum(int[] arr) { bool ans = equiSumUtil(arr); if (ans) { Console.Write(\"First Segment : \"); for (int i = 0; i <= pos1; i++) { Console.Write(arr[i] + \" \"); } Console.WriteLine(); Console.Write(\"Second Segment : \"); for (int i = pos1 + 1; i < pos2; i++) { Console.Write(arr[i] + \" \"); } Console.WriteLine(); Console.Write(\"Third Segment : \"); for (int i = pos2; i < arr.Length; i++) { Console.Write(arr[i] + \" \"); } Console.WriteLine(); } else { Console.WriteLine(\"Array cannot be \" + \"divided into three equal sum segments\"); } } public static void Main(String[] args) { int[] arr = { 1, 3, 6, 2, 7, 1, 2, 8 }; equiSum(arr); }} // This code contributed by Rajput-Ji", "e": 10258, "s": 7625, "text": null }, { "code": "<?php// PHP implementation of the given approach // First segment's end index$pos1 = -1; // Third segment's start index$pos2 = -1; // This function returns true if the array// can be divided into three equal sum segmentsfunction equiSumUtil($arr){ global $pos2, $pos1; $n = count($arr); // Prefix Sum Array $pre = array_fill(0, $n, 0); $sum = 0; for ($i = 0; $i < $n; $i++) { $sum += $arr[$i]; $pre[$i] = $sum; } // Suffix Sum Array $suf = array_fill(0, $n, 0); $sum = 0; for ($i = $n - 1; $i >= 0; $i--) { $sum += $arr[$i]; $suf[$i] = $sum; } // Stores the total sum of the array $total_sum = $sum; $i = 0; $j = $n - 1; while ($i < $j - 1) { if ($pre[$i] == $total_sum / 3) { $pos1 = $i; } if ($suf[$j] == $total_sum / 3) { $pos2 = $j; } if ($pos1 != -1 && $pos2 != -1) { // We can also take pre[pos2 - 1] - pre[pos1] == // total_sum / 3 here. if ($suf[$pos1 + 1] - $suf[$pos2] == $total_sum / 3) { return true; } else { return false; } } if ($pre[$i] < $suf[$j]) { $i++; } else { $j--; } } return false;} function equiSum($arr){ global $pos2,$pos1; $ans = equiSumUtil($arr); if ($ans) { print(\"First Segment : \"); for ($i = 0; $i <= $pos1; $i++) { print($arr[$i] . \" \"); } print(\"\\n\"); print(\"Second Segment : \"); for ($i = $pos1 + 1; $i < $pos2; $i++) { print($arr[$i] . \" \"); } print(\"\\n\"); print(\"Third Segment : \"); for ($i = $pos2; $i < count($arr); $i++) { print($arr[$i] . \" \"); } print(\"\\n\"); } else { println(\"Array cannot be divided into \", \"three equal sum segments\"); }} // Driver Code$arr = array(1, 3, 6, 2, 7, 1, 2, 8 );equiSum($arr); // This code is contributed by mits?>", "e": 12429, "s": 10258, "text": null }, { "code": "<script> // C# implementation of the approach // First segment's end indexlet pos1 = -1; // Third segment's start indexlet pos2 = -1; // This function returns true if the array// can be divided into three equal sum segmentsfunction equiSumUtil(arr){ let n = arr.length; // Prefix Sum Array let pre = new Array(n); let sum = 0,i; for (i = 0; i < n; i++) { sum += arr[i]; pre[i] = sum; } // Suffix Sum Array let suf = new Array(n); sum = 0; for (i = n - 1; i >= 0; i--) { sum += arr[i]; suf[i] = sum; } // Stores the total sum of the array let total_sum = sum; let j = n - 1; i = 0; while (i < j - 1) { if (pre[i] == total_sum / 3) { pos1 = i; } if (suf[j] == total_sum / 3) { pos2 = j; } if (pos1 != -1 && pos2 != -1) { // We can also take pre[pos2 - 1] - pre[pos1] == // total_sum / 3 here. if (suf[pos1 + 1] - suf[pos2] == total_sum / 3) { return true; } else { return false; } } if (pre[i] < suf[j]) { i++; } else { j--; } } return false;} function equiSum(arr){ let ans = equiSumUtil(arr); if (ans) { document.write(\"First Segment : \"); for (let i = 0; i <= pos1; i++) { document.write(arr[i] + \" \"); } document.write(\"<br>\"); document.write(\"Second Segment : \"); for (let i = pos1 + 1; i < pos2; i++) { document.write(arr[i] + \" \"); } document.write(\"<br>\"); document.write(\"Third Segment : \"); for (let i = pos2; i < arr.length; i++) { document.write(arr[i] + \" \"); } document.write(\"<br>\"); } else { document.writeLine(\"Array cannot be\" + \" divided into three equal sum segments\"); }} let arr =[1, 3, 6, 2, 7, 1, 2, 8];equiSum(arr); </script>", "e": 14528, "s": 12429, "text": null }, { "code": null, "e": 14595, "s": 14528, "text": "First Segment : 1 3 6 \nSecond Segment : 2 7 1 \nThird Segment : 2 8" }, { "code": null, "e": 14644, "s": 14597, "text": "Time Complexity : O(n) Auxiliary Space : O(n) " }, { "code": null, "e": 14654, "s": 14644, "text": "Rajput-Ji" }, { "code": null, "e": 14667, "s": 14654, "text": "Mithun Kumar" }, { "code": null, "e": 14682, "s": 14667, "text": "mohit kumar 29" }, { "code": null, "e": 14693, "s": 14682, "text": "bunnyram19" }, { "code": null, "e": 14703, "s": 14693, "text": "Marketing" }, { "code": null, "e": 14714, "s": 14703, "text": "prefix-sum" }, { "code": null, "e": 14721, "s": 14714, "text": "Arrays" }, { "code": null, "e": 14731, "s": 14721, "text": "Searching" }, { "code": null, "e": 14742, "s": 14731, "text": "prefix-sum" }, { "code": null, "e": 14749, "s": 14742, "text": "Arrays" }, { "code": null, "e": 14759, "s": 14749, "text": "Searching" }, { "code": null, "e": 14857, "s": 14759, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14925, "s": 14857, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 14969, "s": 14925, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 15001, "s": 14969, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 15049, "s": 15001, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 15063, "s": 15049, "text": "Linear Search" }, { "code": null, "e": 15077, "s": 15063, "text": "Binary Search" }, { "code": null, "e": 15145, "s": 15077, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 15159, "s": 15145, "text": "Linear Search" }, { "code": null, "e": 15215, "s": 15159, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" } ]
Spring Security – In-Memory Authentication
30 Dec, 2021 Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements. Some of the key features of Spring Security are: Comprehensive and extensible support for both Authentication and Authorization Protection against attacks like session fixation, clickjacking, cross-site request forgery, etc Servlet API integration Optional integration with Spring Web MVC. Let’s first discuss the basic simple authentication of Spring Security. In Simple authentication, Spring Security provides a default user name and the password that we have to use for valid authentication. XML <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency> Login page of simple authentication of Spring Security: Password: It is very difficult to remember this password because this is a random password and Spring Security generates a random password every time when we execute the Spring Application. If we want to add a custom user name and password in the Spring application for authentication we can add it easily(using application.properties ) but if we want to make our Spring application for multiple users it is difficult to configure their credentials. So to overcome this situation when we handle multiple authentications along with their respective roles. We will use in-memory authentication in the Spring Application. in-memory authentication is the way for handling authentication in Spring Security. In the in-memory authentication we hardcore all the user details such as roles, passwords, and the user name. We can perform validation until the Spring server is running. If the server is stopped the memory is cleared out and we cannot perform validation. This is the main drawback of in-memory authentication. inMemoryAuthentication() is the method of AuthenticationManagerBuilder class is used to perform in-memory authentication in the Spring Security. This method is used for creating the user with respective roles and passwords. Let’s discuss how to implement inmemoryAuthentication in Spring Security. Step 1: Create a Spring Boot Project Project: Maven Language: Java Spring Boot: 2.2.8 Packaging: JAR Java: 8 Dependencies: Spring Web,Spring Security Step 2: Click on Generate which will download the starter project. Project Structure: Step 3: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows: Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project. Step 4: Now go to the src > main > java > com.gfg.Spring.boot.app and create two java files one is controller.java and the other is config.java controller.java Java @RestControllerpublic class controller { @GetMapping("/delete") public String delete() { return "This is the delete request"; }} The above java file is used to set the controller for handling the incoming request from the client side. Now we have to configure the request for that we will use the config.java file. config.java This config file is extending the WebSecurityConfigureAdapter class and we override two methods configure(AuthenticationManagerBuilder auth) and configure(HttpSecurity Http) both methods are used for handling the multiple authentications on the Spring application. The first method is used for adding the credentials of the users with respective roles in the inMemory of SpringApplication. The second method is used for handling the user-defined API in the Spring application. Java package com.example.SpringBootApp; import org.springframework.context.annotation.Bean;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.password.NoOpPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder; @EnableWebSecuritypublic class config extends WebSecurityConfigurerAdapter { // Adding the roles @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("Zack") .password("aayush") .roles("admin_role") .and() .withUser("GFG") .password("Helloword") .roles("student"); } // Configuring the api // according to the roles. @Override protected void configure(HttpSecurity http) throws Exception { http. httpBasic() .and() .authorizeRequests() .antMatchers("/delete").hasRole("admin_role") .antMatchers("/details").hasAnyRole("admin_role","student") .and() .formLogin(); } // Function to encode the password // assign to the particular roles. @Bean public PasswordEncoder getPasswordEncoder(){ return NoOpPasswordEncoder.getInstance(); }} Note: There is no default password is generated because we have already used external configuration for handling the user credentials. Go to the postman and type localhost:8080/delete Using the admin roles: Using the student role: Try to access the details API using the student role’s user name and password. Java-Spring-Security Java 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 HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Stack Class in Java Set in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Dec, 2021" }, { "code": null, "e": 516, "s": 52, "text": "Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements. Some of the key features of Spring Security are:" }, { "code": null, "e": 595, "s": 516, "text": "Comprehensive and extensible support for both Authentication and Authorization" }, { "code": null, "e": 691, "s": 595, "text": "Protection against attacks like session fixation, clickjacking, cross-site request forgery, etc" }, { "code": null, "e": 715, "s": 691, "text": "Servlet API integration" }, { "code": null, "e": 757, "s": 715, "text": "Optional integration with Spring Web MVC." }, { "code": null, "e": 963, "s": 757, "text": "Let’s first discuss the basic simple authentication of Spring Security. In Simple authentication, Spring Security provides a default user name and the password that we have to use for valid authentication." }, { "code": null, "e": 967, "s": 963, "text": "XML" }, { "code": "<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>", "e": 1209, "s": 967, "text": null }, { "code": null, "e": 1265, "s": 1209, "text": "Login page of simple authentication of Spring Security:" }, { "code": null, "e": 1275, "s": 1265, "text": "Password:" }, { "code": null, "e": 1884, "s": 1275, "text": "It is very difficult to remember this password because this is a random password and Spring Security generates a random password every time when we execute the Spring Application. If we want to add a custom user name and password in the Spring application for authentication we can add it easily(using application.properties ) but if we want to make our Spring application for multiple users it is difficult to configure their credentials. So to overcome this situation when we handle multiple authentications along with their respective roles. We will use in-memory authentication in the Spring Application." }, { "code": null, "e": 2281, "s": 1884, "text": " in-memory authentication is the way for handling authentication in Spring Security. In the in-memory authentication we hardcore all the user details such as roles, passwords, and the user name. We can perform validation until the Spring server is running. If the server is stopped the memory is cleared out and we cannot perform validation. This is the main drawback of in-memory authentication." }, { "code": null, "e": 2579, "s": 2281, "text": "inMemoryAuthentication() is the method of AuthenticationManagerBuilder class is used to perform in-memory authentication in the Spring Security. This method is used for creating the user with respective roles and passwords. Let’s discuss how to implement inmemoryAuthentication in Spring Security." }, { "code": null, "e": 2616, "s": 2579, "text": "Step 1: Create a Spring Boot Project" }, { "code": null, "e": 2729, "s": 2616, "text": "Project: Maven\nLanguage: Java\nSpring Boot: 2.2.8\nPackaging: JAR\nJava: 8\nDependencies: Spring Web,Spring Security" }, { "code": null, "e": 2796, "s": 2729, "text": "Step 2: Click on Generate which will download the starter project." }, { "code": null, "e": 2815, "s": 2796, "text": "Project Structure:" }, { "code": null, "e": 3074, "s": 2815, "text": "Step 3: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:" }, { "code": null, "e": 3212, "s": 3074, "text": "Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project." }, { "code": null, "e": 3356, "s": 3212, "text": "Step 4: Now go to the src > main > java > com.gfg.Spring.boot.app and create two java files one is controller.java and the other is config.java" }, { "code": null, "e": 3372, "s": 3356, "text": "controller.java" }, { "code": null, "e": 3377, "s": 3372, "text": "Java" }, { "code": "@RestControllerpublic class controller { @GetMapping(\"/delete\") public String delete() { return \"This is the delete request\"; }}", "e": 3524, "s": 3377, "text": null }, { "code": null, "e": 3710, "s": 3524, "text": "The above java file is used to set the controller for handling the incoming request from the client side. Now we have to configure the request for that we will use the config.java file." }, { "code": null, "e": 3722, "s": 3710, "text": "config.java" }, { "code": null, "e": 3987, "s": 3722, "text": "This config file is extending the WebSecurityConfigureAdapter class and we override two methods configure(AuthenticationManagerBuilder auth) and configure(HttpSecurity Http) both methods are used for handling the multiple authentications on the Spring application." }, { "code": null, "e": 4112, "s": 3987, "text": "The first method is used for adding the credentials of the users with respective roles in the inMemory of SpringApplication." }, { "code": null, "e": 4200, "s": 4112, "text": "The second method is used for handling the user-defined API in the Spring application." }, { "code": null, "e": 4205, "s": 4200, "text": "Java" }, { "code": "package com.example.SpringBootApp; import org.springframework.context.annotation.Bean;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;import org.springframework.security.crypto.password.NoOpPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder; @EnableWebSecuritypublic class config extends WebSecurityConfigurerAdapter { // Adding the roles @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser(\"Zack\") .password(\"aayush\") .roles(\"admin_role\") .and() .withUser(\"GFG\") .password(\"Helloword\") .roles(\"student\"); } // Configuring the api // according to the roles. @Override protected void configure(HttpSecurity http) throws Exception { http. httpBasic() .and() .authorizeRequests() .antMatchers(\"/delete\").hasRole(\"admin_role\") .antMatchers(\"/details\").hasAnyRole(\"admin_role\",\"student\") .and() .formLogin(); } // Function to encode the password // assign to the particular roles. @Bean public PasswordEncoder getPasswordEncoder(){ return NoOpPasswordEncoder.getInstance(); }}", "e": 5898, "s": 4205, "text": null }, { "code": null, "e": 6033, "s": 5898, "text": "Note: There is no default password is generated because we have already used external configuration for handling the user credentials." }, { "code": null, "e": 6082, "s": 6033, "text": "Go to the postman and type localhost:8080/delete" }, { "code": null, "e": 6105, "s": 6082, "text": "Using the admin roles:" }, { "code": null, "e": 6208, "s": 6105, "text": "Using the student role: Try to access the details API using the student role’s user name and password." }, { "code": null, "e": 6229, "s": 6208, "text": "Java-Spring-Security" }, { "code": null, "e": 6234, "s": 6229, "text": "Java" }, { "code": null, "e": 6239, "s": 6234, "text": "Java" }, { "code": null, "e": 6337, "s": 6239, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6388, "s": 6337, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 6419, "s": 6388, "text": "How to iterate any Map in Java" }, { "code": null, "e": 6438, "s": 6419, "text": "Interfaces in Java" }, { "code": null, "e": 6468, "s": 6438, "text": "HashMap in Java with Examples" }, { "code": null, "e": 6486, "s": 6468, "text": "ArrayList in Java" }, { "code": null, "e": 6501, "s": 6486, "text": "Stream In Java" }, { "code": null, "e": 6521, "s": 6501, "text": "Collections in Java" }, { "code": null, "e": 6553, "s": 6521, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 6573, "s": 6553, "text": "Stack Class in Java" } ]
How to add metadata to your Azure Data Lake | by René Bremer | Towards Data Science
A lot of companies consider setting up an Enterprise Data Lake. The idea is to store data in a centralized repository. In this way, it becomes easier for teams to create business value with data. To prevent that a Data Lake becomes a Data Swamp with untrusted data, metadata is key. In this, the following types of metadata are distinguished: Business metadata: Data owner, data source, privacy level Technical metadata: Schema name, table name, field name/type Operational metadata: Timestamp, size of data, lineage In the remainder of this blog, it is discussed how an Azure Data Lake can be set up and how metadata is added. For more details how to secure data orchestration in your Azure Data Lake, see my follow-up blog here. For a solution how to prevent data loss in your Data lake using snapshots and incremental backups, see this blog. In the architecture of this project, the functionality of popular Azure services is combined to create a data lake, where data/metadata is copied from SQLDB to Azure Data Lake Store. The setup of the project can be found below. The Azure services and its usage in this project are described as follows: Metadata store is used to store the business metadata. In this project, a blob storage account is used in which the data owner, privacy level of data is stored in a json file. SQLDB is used as source system that contains the table data that will be copied. It also contains the technical metadata that will be used to describe the data. Azure Data Factory v2 (ADFv2) is used as orchestrator that copies the data from source to destination. It also gathers the business metadata and technical metadata and produces the operational metadata. Azure Function Python is used by Azure Data Factory to create a single metadata file adhering to the Common Data Model (CDM) format. In this, it uses the business/technical/operational metadata as input and creates a model.json using the jsonschema of CDM. Azure Data Lake Store gen2 (ADLS gen2) is used to store the data from 10 SQLDB tables. A File System is created and each table is a root folder in the File System. Next to the data itself, the metadata is stored using the model.json in CDM format created by the Azure Function Python. In the next three chapters, this architecture is realized. In chapter 3, the prerequisites to create the Data Lake are deployed. Then in chapter 4, a pipeline is deployed and run. Finally, a conclusion is drawn in chapter 5. For more details how to secure an ADFv2 pipeline, see my other blog here. In this chapter, an Azure Data Lake with metadata is realized. The following steps are executed: 3a. Create SQLDB 3b. Create storage account with metadata 3c. Create ADLS gen2 account 3d. Create Azure Function in python 3e. Create an Azure Data Factory instance 3f. Grant access rights to ADLS gen2 using Managed Identities Follow the steps in the quickstart how to create is SQLDB database. In this make sure that you select the basic database, see below. Also, make sure that you install the AdventureWorksLT sample database, see also below. In this step, a regular Storage account is created. Follow the steps in this quickstart. Make sure that the storage account is stored in the same resource group in which SQLDB is installed. Also, create a container in the storage account and name the container processmetadata. Then download the following business metadata file that contains data owner, privacy level of data using the following link: https://raw.githubusercontent.com/rebremer/adfv2_cdm_metadata/master/procesdataexample/MetadataProcess.json Upload the MetadataProcess.json to your storage container, see also below. In this step, a ADLS gen2 storage account is created. Follow the steps in this quickstart. Make sure that hierarchical namespace is yes, this will create a Hierarchical File System (HFS) in which folders can be created (instead of an object based file system in which all information is stored in the object itself). See also below. Subsequently, create a File System in ADLS gen 2, see below. Make sure that the File System is named as sqldbdata. In this step, an Azure Function in Python is created. Follow the steps in this quickstart that creates a Function in Azure Python. After you published your initial Azure Function Python using an HTTP trigger, update the __init__.py and requirement.txt with the following code and add cdmschema.py to your project next to __init__.py. For links, see below. https://raw.githubusercontent.com/rebremer/adfv2_cdm_metadata/master/modeljson/modeljsonwrite/__init__.pyhttps://raw.githubusercontent.com/rebremer/adfv2_cdm_metadata/master/modeljson/modeljsonwrite/cdmschema.pyhttps://raw.githubusercontent.com/rebremer/adfv2_cdm_metadata/master/modeljson/requirements.txt The __init__.py receives metadata input as parameters, creates a model.json object adhering to the CDM jsonschema and then returns the JSON object to ADFv2. ADFv2 will then write the data to the ADLS gen2 File System. Requirement.txt contains the Pypi libraries that the Azure Function in Python needs to functions. Subsequently, publish the code by using the following command. func azure functionapp publish <APP_NAME> --build remote When your Azure Function is deployed successfully, you can see the code in your function, see below. 3e. Create an Azure Data Factory instance In this step, an Azure Function in Python is created. Follow the steps in this quickstart that creates an Azure Data Factory. After the Data Factory is created, find your ADFv2 resource and click on author & monitor. Then select to set up a code repository and import the following GitHub repository rebremer and project adfv2_cdm_metadata, see below. In the discussed Architecure, ADFv2 is used to copy data from SQLDB to ADLS gen2. Furthermore, business metadata is read from a blob storage and written to ADLS gen 2 using an Azure Python Function. For that purpose, access need to be granted to ADLS gen2, blob storage and SQLDB. In this tutorial, it is explained how RBAC rules can be assigned to storage. Assign the following RBAC rules as follows: Grant your ADFv2 instance the role “Storage Blob Data Contributor” to you storage account with business metadata (created in 3b) Grant your ADFv2 instance the role “Storage Blob Data Contributor” to you ADLS gen account (created in 3c) It can be verified in Access control tab if RBAC are successfully added, see below for ADFv2 instance (3c) and Azure Function (3d). For simplicity, Managed Identies are not used in the following two steps: ADFv2 uses SQL authentication to authenticate to SQLDB, however, this could also have been done with MI, refer to this link. ADFv2 uses a key to authenticate to the Azure Function. Refer to this tutorial how Managed Identity could have been used for this as well All prerequisites are now deployed. In the next chapter, the pipeline is built an run in ADFv2. In this chapter, a build and run pipeline in ADFv2 is realized. The following steps are executed: 4a. Set parameters and linked services 4b. Configure applications insights in Azure Function 4c. Run pipeline In the first step, the pipeline needs to be customized to your storage accounts and SQLDB. Make sure that ADFv2 is running in Data Factory mode and fill in the parameters of the pipeline using your parameters, see below Subsequently, refer in the linked services to your own storage account for logging, ADLS gen 2, SQLDB and Azure Function. See linked services that need to be changed below: It is likely that the pipeline does not correctly run the first time you run it. Error messages can be seen in ADFv2, however, ADFv2 also refers to an external Azure Function. To see the logging of the Azure Function, Applications insights need to be enabled. Go the monitor tab and follow the wizard to set up Applications Insights, see below When an Azure Function is run, all logging.info and raised exceptions are logged, see example below. In the final step, the pipeline can be run in ADFv2. Go to your pipeline and click debug. When everything goes well, all green checks will appear in the output, see below. Go to your ADLS gen storage account and verify that the data and metadata is copied. See the example below for table dboversio When you open the model.json, the metadata can be found using the CDM format, see snippet below. { "name": "BlogMetaData", "description": "Example model.json using CDM json schema", "version": "1.0", "annotation": { "retentionPeriod": 62, "sourceSystem": "bremerov", "IngestionDate": "2019-09-09 16:56:00Z", "privacyLevel": "10" }, "entities": [ { "$type": "LocalEntity", "name": "SalesLTProductModel", "description": "", "attributes": [ { "name": "ProductModelID", "dataType": "int64" },... A lot of companies consider setting up an Enterprise Data Lake. To prevent that a Data Lake becomes a Data Swamp, metadata is key. In this, the following types of metadata are distinguished: Business metadata: Data owner, data source, privacy level Technical metadata: Schema name, table name, fields, field type Operational metadata: Timestamp that ingestion starts/ends In this blog, it was discussed how to add metadata to your datalake using the architecture below.
[ { "code": null, "e": 515, "s": 172, "text": "A lot of companies consider setting up an Enterprise Data Lake. The idea is to store data in a centralized repository. In this way, it becomes easier for teams to create business value with data. To prevent that a Data Lake becomes a Data Swamp with untrusted data, metadata is key. In this, the following types of metadata are distinguished:" }, { "code": null, "e": 573, "s": 515, "text": "Business metadata: Data owner, data source, privacy level" }, { "code": null, "e": 634, "s": 573, "text": "Technical metadata: Schema name, table name, field name/type" }, { "code": null, "e": 689, "s": 634, "text": "Operational metadata: Timestamp, size of data, lineage" }, { "code": null, "e": 1017, "s": 689, "text": "In the remainder of this blog, it is discussed how an Azure Data Lake can be set up and how metadata is added. For more details how to secure data orchestration in your Azure Data Lake, see my follow-up blog here. For a solution how to prevent data loss in your Data lake using snapshots and incremental backups, see this blog." }, { "code": null, "e": 1245, "s": 1017, "text": "In the architecture of this project, the functionality of popular Azure services is combined to create a data lake, where data/metadata is copied from SQLDB to Azure Data Lake Store. The setup of the project can be found below." }, { "code": null, "e": 1320, "s": 1245, "text": "The Azure services and its usage in this project are described as follows:" }, { "code": null, "e": 1496, "s": 1320, "text": "Metadata store is used to store the business metadata. In this project, a blob storage account is used in which the data owner, privacy level of data is stored in a json file." }, { "code": null, "e": 1657, "s": 1496, "text": "SQLDB is used as source system that contains the table data that will be copied. It also contains the technical metadata that will be used to describe the data." }, { "code": null, "e": 1860, "s": 1657, "text": "Azure Data Factory v2 (ADFv2) is used as orchestrator that copies the data from source to destination. It also gathers the business metadata and technical metadata and produces the operational metadata." }, { "code": null, "e": 2117, "s": 1860, "text": "Azure Function Python is used by Azure Data Factory to create a single metadata file adhering to the Common Data Model (CDM) format. In this, it uses the business/technical/operational metadata as input and creates a model.json using the jsonschema of CDM." }, { "code": null, "e": 2402, "s": 2117, "text": "Azure Data Lake Store gen2 (ADLS gen2) is used to store the data from 10 SQLDB tables. A File System is created and each table is a root folder in the File System. Next to the data itself, the metadata is stored using the model.json in CDM format created by the Azure Function Python." }, { "code": null, "e": 2701, "s": 2402, "text": "In the next three chapters, this architecture is realized. In chapter 3, the prerequisites to create the Data Lake are deployed. Then in chapter 4, a pipeline is deployed and run. Finally, a conclusion is drawn in chapter 5. For more details how to secure an ADFv2 pipeline, see my other blog here." }, { "code": null, "e": 2798, "s": 2701, "text": "In this chapter, an Azure Data Lake with metadata is realized. The following steps are executed:" }, { "code": null, "e": 2815, "s": 2798, "text": "3a. Create SQLDB" }, { "code": null, "e": 2856, "s": 2815, "text": "3b. Create storage account with metadata" }, { "code": null, "e": 2885, "s": 2856, "text": "3c. Create ADLS gen2 account" }, { "code": null, "e": 2921, "s": 2885, "text": "3d. Create Azure Function in python" }, { "code": null, "e": 2963, "s": 2921, "text": "3e. Create an Azure Data Factory instance" }, { "code": null, "e": 3025, "s": 2963, "text": "3f. Grant access rights to ADLS gen2 using Managed Identities" }, { "code": null, "e": 3158, "s": 3025, "text": "Follow the steps in the quickstart how to create is SQLDB database. In this make sure that you select the basic database, see below." }, { "code": null, "e": 3245, "s": 3158, "text": "Also, make sure that you install the AdventureWorksLT sample database, see also below." }, { "code": null, "e": 3648, "s": 3245, "text": "In this step, a regular Storage account is created. Follow the steps in this quickstart. Make sure that the storage account is stored in the same resource group in which SQLDB is installed. Also, create a container in the storage account and name the container processmetadata. Then download the following business metadata file that contains data owner, privacy level of data using the following link:" }, { "code": null, "e": 3756, "s": 3648, "text": "https://raw.githubusercontent.com/rebremer/adfv2_cdm_metadata/master/procesdataexample/MetadataProcess.json" }, { "code": null, "e": 3831, "s": 3756, "text": "Upload the MetadataProcess.json to your storage container, see also below." }, { "code": null, "e": 4164, "s": 3831, "text": "In this step, a ADLS gen2 storage account is created. Follow the steps in this quickstart. Make sure that hierarchical namespace is yes, this will create a Hierarchical File System (HFS) in which folders can be created (instead of an object based file system in which all information is stored in the object itself). See also below." }, { "code": null, "e": 4225, "s": 4164, "text": "Subsequently, create a File System in ADLS gen 2, see below." }, { "code": null, "e": 4279, "s": 4225, "text": "Make sure that the File System is named as sqldbdata." }, { "code": null, "e": 4635, "s": 4279, "text": "In this step, an Azure Function in Python is created. Follow the steps in this quickstart that creates a Function in Azure Python. After you published your initial Azure Function Python using an HTTP trigger, update the __init__.py and requirement.txt with the following code and add cdmschema.py to your project next to __init__.py. For links, see below." }, { "code": null, "e": 4942, "s": 4635, "text": "https://raw.githubusercontent.com/rebremer/adfv2_cdm_metadata/master/modeljson/modeljsonwrite/__init__.pyhttps://raw.githubusercontent.com/rebremer/adfv2_cdm_metadata/master/modeljson/modeljsonwrite/cdmschema.pyhttps://raw.githubusercontent.com/rebremer/adfv2_cdm_metadata/master/modeljson/requirements.txt" }, { "code": null, "e": 5321, "s": 4942, "text": "The __init__.py receives metadata input as parameters, creates a model.json object adhering to the CDM jsonschema and then returns the JSON object to ADFv2. ADFv2 will then write the data to the ADLS gen2 File System. Requirement.txt contains the Pypi libraries that the Azure Function in Python needs to functions. Subsequently, publish the code by using the following command." }, { "code": null, "e": 5378, "s": 5321, "text": "func azure functionapp publish <APP_NAME> --build remote" }, { "code": null, "e": 5479, "s": 5378, "text": "When your Azure Function is deployed successfully, you can see the code in your function, see below." }, { "code": null, "e": 5521, "s": 5479, "text": "3e. Create an Azure Data Factory instance" }, { "code": null, "e": 5873, "s": 5521, "text": "In this step, an Azure Function in Python is created. Follow the steps in this quickstart that creates an Azure Data Factory. After the Data Factory is created, find your ADFv2 resource and click on author & monitor. Then select to set up a code repository and import the following GitHub repository rebremer and project adfv2_cdm_metadata, see below." }, { "code": null, "e": 6275, "s": 5873, "text": "In the discussed Architecure, ADFv2 is used to copy data from SQLDB to ADLS gen2. Furthermore, business metadata is read from a blob storage and written to ADLS gen 2 using an Azure Python Function. For that purpose, access need to be granted to ADLS gen2, blob storage and SQLDB. In this tutorial, it is explained how RBAC rules can be assigned to storage. Assign the following RBAC rules as follows:" }, { "code": null, "e": 6404, "s": 6275, "text": "Grant your ADFv2 instance the role “Storage Blob Data Contributor” to you storage account with business metadata (created in 3b)" }, { "code": null, "e": 6511, "s": 6404, "text": "Grant your ADFv2 instance the role “Storage Blob Data Contributor” to you ADLS gen account (created in 3c)" }, { "code": null, "e": 6643, "s": 6511, "text": "It can be verified in Access control tab if RBAC are successfully added, see below for ADFv2 instance (3c) and Azure Function (3d)." }, { "code": null, "e": 6717, "s": 6643, "text": "For simplicity, Managed Identies are not used in the following two steps:" }, { "code": null, "e": 6842, "s": 6717, "text": "ADFv2 uses SQL authentication to authenticate to SQLDB, however, this could also have been done with MI, refer to this link." }, { "code": null, "e": 6980, "s": 6842, "text": "ADFv2 uses a key to authenticate to the Azure Function. Refer to this tutorial how Managed Identity could have been used for this as well" }, { "code": null, "e": 7076, "s": 6980, "text": "All prerequisites are now deployed. In the next chapter, the pipeline is built an run in ADFv2." }, { "code": null, "e": 7174, "s": 7076, "text": "In this chapter, a build and run pipeline in ADFv2 is realized. The following steps are executed:" }, { "code": null, "e": 7213, "s": 7174, "text": "4a. Set parameters and linked services" }, { "code": null, "e": 7267, "s": 7213, "text": "4b. Configure applications insights in Azure Function" }, { "code": null, "e": 7284, "s": 7267, "text": "4c. Run pipeline" }, { "code": null, "e": 7504, "s": 7284, "text": "In the first step, the pipeline needs to be customized to your storage accounts and SQLDB. Make sure that ADFv2 is running in Data Factory mode and fill in the parameters of the pipeline using your parameters, see below" }, { "code": null, "e": 7677, "s": 7504, "text": "Subsequently, refer in the linked services to your own storage account for logging, ADLS gen 2, SQLDB and Azure Function. See linked services that need to be changed below:" }, { "code": null, "e": 8021, "s": 7677, "text": "It is likely that the pipeline does not correctly run the first time you run it. Error messages can be seen in ADFv2, however, ADFv2 also refers to an external Azure Function. To see the logging of the Azure Function, Applications insights need to be enabled. Go the monitor tab and follow the wizard to set up Applications Insights, see below" }, { "code": null, "e": 8122, "s": 8021, "text": "When an Azure Function is run, all logging.info and raised exceptions are logged, see example below." }, { "code": null, "e": 8294, "s": 8122, "text": "In the final step, the pipeline can be run in ADFv2. Go to your pipeline and click debug. When everything goes well, all green checks will appear in the output, see below." }, { "code": null, "e": 8421, "s": 8294, "text": "Go to your ADLS gen storage account and verify that the data and metadata is copied. See the example below for table dboversio" }, { "code": null, "e": 8518, "s": 8421, "text": "When you open the model.json, the metadata can be found using the CDM format, see snippet below." }, { "code": null, "e": 8987, "s": 8518, "text": "{ \"name\": \"BlogMetaData\", \"description\": \"Example model.json using CDM json schema\", \"version\": \"1.0\", \"annotation\": { \"retentionPeriod\": 62, \"sourceSystem\": \"bremerov\", \"IngestionDate\": \"2019-09-09 16:56:00Z\", \"privacyLevel\": \"10\" }, \"entities\": [ { \"$type\": \"LocalEntity\", \"name\": \"SalesLTProductModel\", \"description\": \"\", \"attributes\": [ { \"name\": \"ProductModelID\", \"dataType\": \"int64\" },..." }, { "code": null, "e": 9178, "s": 8987, "text": "A lot of companies consider setting up an Enterprise Data Lake. To prevent that a Data Lake becomes a Data Swamp, metadata is key. In this, the following types of metadata are distinguished:" }, { "code": null, "e": 9236, "s": 9178, "text": "Business metadata: Data owner, data source, privacy level" }, { "code": null, "e": 9300, "s": 9236, "text": "Technical metadata: Schema name, table name, fields, field type" }, { "code": null, "e": 9359, "s": 9300, "text": "Operational metadata: Timestamp that ingestion starts/ends" } ]
SAP ABAP - User Exits
User exits are used in an extraction if the standard SAP extractors do not provide the expected data or the required functionality, for instance in authorizations or time checks. User exits are commonly used in Sales and Distribution (SD) modules. There are many exits provided by SAP in the areas of sales, transportation, shipping and billing. A user exit is designed to make some changes when standard SAP is not capable of fulfilling all the requirements. To be able to access what exits are available in each area of sales, go to IMG using this path: IMG → Sales and Distribution → System Modifications → User Exits. The documentation for each exit in the areas of SD is explained thoroughly. For instance, if you want to find user exits in Sales Document Processing (contract, quotation or sales order), follow the path mentioned above and continue to expand the node User Exits in Sales → User Exits. Click on icon documentation to see all user exits available in Sales Document Processing. USEREXIT_FIELD_MODIFICATION Used to modify screen attributes. USEREXIT_SAVE_DOCUMENT Helps in performing operations when the user hits Save. USEREXIT_SAVE_DOCUMENT_PREPARE Very useful to check input fields, put any value in the field or show a popup to users and to confirm the document. USEREXIT_MOVE_FIELD_TO_VBAK Used when user header changes are moved to header work area. USEREXIT_MOVE_FIELD_TO_VBAP Used when user item changes are moved to SAP item work area. A User Exit serves the same purpose as Customer Exits but they are available only for the SD module. The exit is implemented as a call to a Function Module. User Exits are modifications to SAP standard programs. REPORT ZUSEREXIT1. TABLES: TSTC, TSTCT, TADIR, TRDIR, TFDIR, ENLFDIR, MODSAPT, MODACT. DATA: JTAB LIKE TADIR OCCURS 0 WITH HEADER LINE, field1(30), v_devclass LIKE TADIR-devclass. PARAMETERS: P_TCODE LIKE TSTC-tcode OBLIGATORY. SELECT SINGLE * FROM TSTC WHERE tcode EQ P_TCODE. IF SY-SUBRC EQ 0. SELECT SINGLE * FROM TADIR WHERE pgmid = 'R3TR' AND object = 'PROG' AND obj_name = TSTC-pgmna. MOVE TADIR-devclass TO v_devclass. IF SY-SUBRC NE 0. SELECT SINGLE * FROM TRDIR WHERE name = TSTC-pgmna. IF TRDIR-subc EQ 'F'. SELECT SINGLE * FROM TFDIR WHERE pname = TSTC-pgmna. SELECT SINGLE * FROM ENLFDIR WHERE funcname = TFDIR-funcname. SELECT SINGLE * FROM TADIR WHERE pgmid = 'R3TR' AND object = 'FUGR' AND obj_name EQ ENLFDIR-area. MOVE TADIR-devclass TO v_devclass. ENDIF. ENDIF. SELECT * FROM TADIR INTO TABLE JTAB WHERE pgmid = 'R3TR' AND object = 'SMOD' AND devclass = v_devclass. SELECT SINGLE * FROM TSTCT WHERE sprsl EQ SY-LANGU AND tcode EQ P_TCODE. FORMAT COLOR COL_POSITIVE INTENSIFIED OFF. WRITE:/(19) 'Transaction Code - ', 20(20) P_TCODE, 45(50) TSTCT-ttext. SKIP. IF NOT JTAB[] IS INITIAL. WRITE:/(95) SY-ULINE. FORMAT COLOR COL_HEADING INTENSIFIED ON. WRITE:/1 SY-VLINE, 2 'Exit Name', 21 SY-VLINE , 22 'Description', 95 SY-VLINE. WRITE:/(95) SY-ULINE. LOOP AT JTAB. SELECT SINGLE * FROM MODSAPT WHERE sprsl = SY-LANGU AND name = JTAB-obj_name. FORMAT COLOR COL_NORMAL INTENSIFIED OFF. WRITE:/1 SY-VLINE, 2 JTAB-obj_name HOTSPOT ON, 21 SY-VLINE , 22 MODSAPT-modtext, 95 SY-VLINE. ENDLOOP. WRITE:/(95) SY-ULINE. DESCRIBE TABLE JTAB. SKIP. FORMAT COLOR COL_TOTAL INTENSIFIED ON. WRITE:/ 'No of Exits:' , SY-TFILL. ELSE. FORMAT COLOR COL_NEGATIVE INTENSIFIED ON. WRITE:/(95) 'User Exit doesn’t exist'. ENDIF. ELSE. FORMAT COLOR COL_NEGATIVE INTENSIFIED ON. WRITE:/(95) 'Transaction Code Does Not Exist'. ENDIF. AT LINE-SELECTION. GET CURSOR FIELD field1. CHECK field1(4) EQ 'JTAB'. SET PARAMETER ID 'MON' FIELD sy-lisel+1(10). CALL TRANSACTION 'SMOD' AND SKIP FIRST SCREEN. While processing, enter the transaction code ‘ME01’ and press F8 (Execute) button. The above code produces the following output − 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 3358, "s": 2898, "text": "User exits are used in an extraction if the standard SAP extractors do not provide the expected data or the required functionality, for instance in authorizations or time checks. User exits are commonly used in Sales and Distribution (SD) modules. There are many exits provided by SAP in the areas of sales, transportation, shipping and billing. A user exit is designed to make some changes when standard SAP is not capable of fulfilling all the requirements." }, { "code": null, "e": 3596, "s": 3358, "text": "To be able to access what exits are available in each area of sales, go to IMG using this path: IMG → Sales and Distribution → System Modifications → User Exits. The documentation for each exit in the areas of SD is explained thoroughly." }, { "code": null, "e": 3896, "s": 3596, "text": "For instance, if you want to find user exits in Sales Document Processing (contract, quotation or sales order), follow the path mentioned above and continue to expand the node User Exits in Sales → User Exits. Click on icon documentation to see all user exits available in Sales Document Processing." }, { "code": null, "e": 3924, "s": 3896, "text": "USEREXIT_FIELD_MODIFICATION" }, { "code": null, "e": 3958, "s": 3924, "text": "Used to modify screen attributes." }, { "code": null, "e": 3981, "s": 3958, "text": "USEREXIT_SAVE_DOCUMENT" }, { "code": null, "e": 4037, "s": 3981, "text": "Helps in performing operations when the user hits Save." }, { "code": null, "e": 4068, "s": 4037, "text": "USEREXIT_SAVE_DOCUMENT_PREPARE" }, { "code": null, "e": 4184, "s": 4068, "text": "Very useful to check input fields, put any value in the field or show a popup to users and to confirm the document." }, { "code": null, "e": 4212, "s": 4184, "text": "USEREXIT_MOVE_FIELD_TO_VBAK" }, { "code": null, "e": 4273, "s": 4212, "text": "Used when user header changes are moved to header work area." }, { "code": null, "e": 4301, "s": 4273, "text": "USEREXIT_MOVE_FIELD_TO_VBAP" }, { "code": null, "e": 4362, "s": 4301, "text": "Used when user item changes are moved to SAP item work area." }, { "code": null, "e": 4574, "s": 4362, "text": "A User Exit serves the same purpose as Customer Exits but they are available only for the SD module. The exit is implemented as a call to a Function Module. User Exits are modifications to SAP standard programs." }, { "code": null, "e": 7198, "s": 4574, "text": "REPORT ZUSEREXIT1. \nTABLES: \n TSTC, TSTCT,\n TADIR, TRDIR, TFDIR, ENLFDIR,\n MODSAPT, MODACT. \n\t\nDATA: \n JTAB LIKE TADIR OCCURS 0 WITH HEADER LINE,\n field1(30),\n v_devclass LIKE TADIR-devclass. \n\t\nPARAMETERS:\n P_TCODE LIKE TSTC-tcode OBLIGATORY. \n\t\nSELECT SINGLE *\n FROM TSTC\n WHERE tcode EQ P_TCODE. \n\t\nIF SY-SUBRC EQ 0.\n SELECT SINGLE *\n FROM TADIR\n\t\n WHERE pgmid = 'R3TR' AND \n object = 'PROG' AND\n obj_name = TSTC-pgmna.\n\t\t\n MOVE TADIR-devclass TO v_devclass.\n\t\n IF SY-SUBRC NE 0.\n SELECT SINGLE * \n FROM TRDIR\n WHERE name = TSTC-pgmna.\n\t\t\n IF TRDIR-subc EQ 'F'.\n SELECT SINGLE *\n FROM TFDIR\n WHERE pname = TSTC-pgmna.\n\t\t\t\n SELECT SINGLE *\n FROM ENLFDIR \n WHERE funcname = TFDIR-funcname.\n\t\t\t\n SELECT SINGLE * \n FROM TADIR\n WHERE pgmid = 'R3TR' AND\n object = 'FUGR' AND \n obj_name EQ ENLFDIR-area.\n MOVE TADIR-devclass TO v_devclass.\n ENDIF.\n ENDIF.\n\t\n SELECT *\n FROM TADIR\n INTO TABLE JTAB\n\t\t\n WHERE pgmid = 'R3TR' AND\n object = 'SMOD' AND\n devclass = v_devclass.\n\t\t\t\n SELECT SINGLE *\n FROM TSTCT\n WHERE sprsl EQ SY-LANGU AND\n tcode EQ P_TCODE.\n\t\t\t\n FORMAT COLOR COL_POSITIVE INTENSIFIED OFF.\n WRITE:/(19) 'Transaction Code - ', \n 20(20) P_TCODE,\n 45(50) TSTCT-ttext.\n SKIP.\n\t\n IF NOT JTAB[] IS INITIAL.\n WRITE:/(95) SY-ULINE.\n FORMAT COLOR COL_HEADING INTENSIFIED ON.\n\t\t\n WRITE:/1 SY-VLINE, \n 2 'Exit Name',\n 21 SY-VLINE , \n 22 'Description',\n 95 SY-VLINE.\n\t\t\t\n WRITE:/(95) SY-ULINE.\n LOOP AT JTAB.\n SELECT SINGLE * FROM MODSAPT\n WHERE sprsl = SY-LANGU AND\n name = JTAB-obj_name.\n\t\t\t\t\n FORMAT COLOR COL_NORMAL INTENSIFIED OFF.\n WRITE:/1 SY-VLINE,\n 2 JTAB-obj_name HOTSPOT ON,\n 21 SY-VLINE ,\n 22 MODSAPT-modtext,\n 95 SY-VLINE.\n ENDLOOP.\n\t\t\n WRITE:/(95) SY-ULINE.\n DESCRIBE TABLE JTAB.\n SKIP.\n FORMAT COLOR COL_TOTAL INTENSIFIED ON.\n WRITE:/ 'No of Exits:' , SY-TFILL.\n\t\t\n ELSE.\n FORMAT COLOR COL_NEGATIVE INTENSIFIED ON.\n WRITE:/(95) 'User Exit doesn’t exist'.\n ENDIF. \nELSE.\n\n FORMAT COLOR COL_NEGATIVE INTENSIFIED ON.\n WRITE:/(95) 'Transaction Code Does Not Exist'. \nENDIF.\n \nAT LINE-SELECTION.\n GET CURSOR FIELD field1.\n CHECK field1(4) EQ 'JTAB'.\n SET PARAMETER ID 'MON' FIELD sy-lisel+1(10).\n CALL TRANSACTION 'SMOD' AND SKIP FIRST SCREEN. " }, { "code": null, "e": 7328, "s": 7198, "text": "While processing, enter the transaction code ‘ME01’ and press F8 (Execute) button. The above code produces the following output −" }, { "code": null, "e": 7361, "s": 7328, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 7375, "s": 7361, "text": " Sanjo Thomas" }, { "code": null, "e": 7408, "s": 7375, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 7420, "s": 7408, "text": " Neha Gupta" }, { "code": null, "e": 7455, "s": 7420, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7470, "s": 7455, "text": " Sumit Agarwal" }, { "code": null, "e": 7503, "s": 7470, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 7518, "s": 7503, "text": " Sumit Agarwal" }, { "code": null, "e": 7553, "s": 7518, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7565, "s": 7553, "text": " Neha Malik" }, { "code": null, "e": 7600, "s": 7565, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7612, "s": 7600, "text": " Neha Malik" }, { "code": null, "e": 7619, "s": 7612, "text": " Print" }, { "code": null, "e": 7630, "s": 7619, "text": " Add Notes" } ]
How to move mouse pointer to a specific position using JavaScript ? - GeeksforGeeks
30 Nov, 2021 In this article, we will learn how to move a mouse pointer to any specific position in the web browser using JavaScript. Before we start, you need to know that it’s not actually possible to move the mouse pointer to a position using Javascript, such functionality can we easily misused but we can simulate something similar. In this article, we will learn to move the mouse pointer from one pointer to another pointer. Since we cannot make actual mouse pointer using JavaScript, we use an image as a cursor. Suppose variables x, y, px, py, x1, x2x: x-position of the actual mouse pointer y: y-position of the actual mouse pointer x1: x-position where we want the mouse to appear x2: y-position where we want the mouse to appear Now, let x + px = x1 px = x1 - x similarly, py = y1 - y Now, px, py is the relative position of x, y with respect to x1, y1. The position where our image cursor will appear with respect to x1, y1 will be given by x + px and y + py for all x, y x: x-position of the actual mouse pointer y: y-position of the actual mouse pointer x1: x-position where we want the mouse to appear x2: y-position where we want the mouse to appear Now, let x + px = x1 px = x1 - x similarly, py = y1 - y Now, px, py is the relative position of x, y with respect to x1, y1. The position where our image cursor will appear with respect to x1, y1 will be given by x + px and y + py for all x, y Now, the problem is how to detect click since the mouse cursor may not be on the pointer. To do this, we use document.elementFromPoint(x+px, y+py) in which we pass the position of image cursor. This will gives us the object of the element, the image cursor is on. After obtaining the required object, we can invoke the object.click(). Example: HTML Code:<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /></head> <body> <img id="cursor" src="https://media.geeksforgeeks.org/wp-content/uploads/20200319212118/cursor2.png" width="15" height="20" /> <p> <button id="b1">BUTTON1</button> </p> <p> <button id="b2">BUTTON2</button> </p> </body> </html> <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /></head> <body> <img id="cursor" src="https://media.geeksforgeeks.org/wp-content/uploads/20200319212118/cursor2.png" width="15" height="20" /> <p> <button id="b1">BUTTON1</button> </p> <p> <button id="b2">BUTTON2</button> </p> </body> </html> CSS Code:<style> img { pointer-events: none; /* doing this makes sure .elementFromPoint do not acquires the image cursor object */ position: absolute; } /* makes the cursor invisible */ * { cursor: none; }</style> <style> img { pointer-events: none; /* doing this makes sure .elementFromPoint do not acquires the image cursor object */ position: absolute; } /* makes the cursor invisible */ * { cursor: none; }</style> JavaScript Code:<script> var x, y; var px, py; px = py = 0; // Image of cursor var cursor = document.getElementById("cursor"); // Button 1 var b1 = document.getElementById("b1"); // Button 2 var b2 = document.getElementById("b2"); /* mutex is used to avoid multiple click event from firing at the same time due to different position of image cursor and actual cursor Using mutex avoid any conflicts if original cursor and image cursor are both on a clickable element This makes sure only 1 click event is triggered at a time*/ var mutex = false; /* The following event is selecting the element on the image cursor and fires click() on it. The following event is triggered only when mouse is pressed. */ window.addEventListener("mouseup", function(e) { // gets the object on image cursor position var tmp = document.elementFromPoint(x + px, y + py); mutex = true; tmp.click(); cursor.style.left = (px + x) + "px"; cursor.style.top = (py + y) + "px"; }) /* The following event listener moves the image pointer with respect to the actual mouse cursor The function is triggered every time mouse is moved */ window.addEventListener("mousemove", function(e) { // Gets the x,y position of the mouse cursor x = e.clientX; y = e.clientY; // sets the image cursor to new relative position cursor.style.left = (px + x) + "px"; cursor.style.top = (py + y) + "px"; }); /* The following function re-calculates px,py with respect to new position Clicking on b1 moves the pointer to b2 Clicking on b2 moves the pointer to b1 */ b1.onclick = function() { if (mutex) { mutex = false; px = b2.offsetLeft - x; py = b2.offsetTop - y; } } b2.onclick = function() { if (mutex) { mutex = false; px = b1.offsetLeft - x; py = b1.offsetTop - y; } }</script> <script> var x, y; var px, py; px = py = 0; // Image of cursor var cursor = document.getElementById("cursor"); // Button 1 var b1 = document.getElementById("b1"); // Button 2 var b2 = document.getElementById("b2"); /* mutex is used to avoid multiple click event from firing at the same time due to different position of image cursor and actual cursor Using mutex avoid any conflicts if original cursor and image cursor are both on a clickable element This makes sure only 1 click event is triggered at a time*/ var mutex = false; /* The following event is selecting the element on the image cursor and fires click() on it. The following event is triggered only when mouse is pressed. */ window.addEventListener("mouseup", function(e) { // gets the object on image cursor position var tmp = document.elementFromPoint(x + px, y + py); mutex = true; tmp.click(); cursor.style.left = (px + x) + "px"; cursor.style.top = (py + y) + "px"; }) /* The following event listener moves the image pointer with respect to the actual mouse cursor The function is triggered every time mouse is moved */ window.addEventListener("mousemove", function(e) { // Gets the x,y position of the mouse cursor x = e.clientX; y = e.clientY; // sets the image cursor to new relative position cursor.style.left = (px + x) + "px"; cursor.style.top = (py + y) + "px"; }); /* The following function re-calculates px,py with respect to new position Clicking on b1 moves the pointer to b2 Clicking on b2 moves the pointer to b1 */ b1.onclick = function() { if (mutex) { mutex = false; px = b2.offsetLeft - x; py = b2.offsetTop - y; } } b2.onclick = function() { if (mutex) { mutex = false; px = b1.offsetLeft - x; py = b1.offsetTop - y; } }</script> Final Solution: In this section we will combine all the above section into one and perform the task. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title></title> <style> img { pointer-events: none; /* doing this makes sure .elementFromPoint do not acquires the image cursor object */ position: absolute; } /* makes the cursor invisible */ * { cursor: none; } </style></head> <body> <img id="cursor" src="https://media.geeksforgeeks.org/wp-content/uploads/20200319212118/cursor2.png" width="15" height="20" /> <p> <button id="b1">BUTTON1</button> </p> <p> <button id="b2">BUTTON2</button> </p> <script> var x, y; var px, py; px = py = 0; // Image of cursor var cursor = document.getElementById("cursor"); // Button 1 var b1 = document.getElementById("b1"); // Button 2 var b2 = document.getElementById("b2"); /* mutex is used to avoid multiple click event from firing at the same time due to different position of image cursor and actual cursor Using mutex avoid any conflicts if original cursor and image cursor are both on a clickable element This makes sure only 1 click event is triggered at a time*/ var mutex = false; /* The following event is selecting the element on the image cursor and fires click() on it. The following event is triggered only when mouse is pressed. */ window.addEventListener("mouseup", function(e) { // gets the object on image cursor position var tmp = document.elementFromPoint(x + px, y + py); mutex = true; tmp.click(); cursor.style.left = (px + x) + "px"; cursor.style.top = (py + y) + "px"; }) /* The following event listener moves the image pointer with respect to the actual mouse cursor The function is triggered every time mouse is moved */ window.addEventListener("mousemove", function(e) { // Gets the x,y position of the mouse cursor x = e.clientX; y = e.clientY; // sets the image cursor to new relative position cursor.style.left = (px + x) + "px"; cursor.style.top = (py + y) + "px"; }); /* The following function re-calculates px,py with respect to new position Clicking on b1 moves the pointer to b2 Clicking on b2 moves the pointer to b1 */ b1.onclick = function() { if (mutex) { mutex = false; px = b2.offsetLeft - x; py = b2.offsetTop - y; } } b2.onclick = function() { if (mutex) { mutex = false; px = b1.offsetLeft - x; py = b1.offsetTop - y; } } </script> </body> </html> Output: as5853535 CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to position a div at the bottom of its container using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet) Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 24245, "s": 24217, "text": "\n30 Nov, 2021" }, { "code": null, "e": 24570, "s": 24245, "text": "In this article, we will learn how to move a mouse pointer to any specific position in the web browser using JavaScript. Before we start, you need to know that it’s not actually possible to move the mouse pointer to a position using Javascript, such functionality can we easily misused but we can simulate something similar." }, { "code": null, "e": 24664, "s": 24570, "text": "In this article, we will learn to move the mouse pointer from one pointer to another pointer." }, { "code": null, "e": 24753, "s": 24664, "text": "Since we cannot make actual mouse pointer using JavaScript, we use an image as a cursor." }, { "code": null, "e": 25222, "s": 24753, "text": "Suppose variables x, y, px, py, x1, x2x: x-position of the actual mouse pointer\ny: y-position of the actual mouse pointer\nx1: x-position where we want the mouse to appear\nx2: y-position where we want the mouse to appear\n\nNow, let\nx + px = x1\npx = x1 - x\n\nsimilarly,\npy = y1 - y\n\nNow, px, py is the relative position of x, y with respect to x1, y1.\nThe position where our image cursor will appear with respect to x1, \ny1 will be given by \nx + px and y + py\nfor all x, y" }, { "code": null, "e": 25653, "s": 25222, "text": "x: x-position of the actual mouse pointer\ny: y-position of the actual mouse pointer\nx1: x-position where we want the mouse to appear\nx2: y-position where we want the mouse to appear\n\nNow, let\nx + px = x1\npx = x1 - x\n\nsimilarly,\npy = y1 - y\n\nNow, px, py is the relative position of x, y with respect to x1, y1.\nThe position where our image cursor will appear with respect to x1, \ny1 will be given by \nx + px and y + py\nfor all x, y" }, { "code": null, "e": 25988, "s": 25653, "text": "Now, the problem is how to detect click since the mouse cursor may not be on the pointer. To do this, we use document.elementFromPoint(x+px, y+py) in which we pass the position of image cursor. This will gives us the object of the element, the image cursor is on. After obtaining the required object, we can invoke the object.click()." }, { "code": null, "e": 25997, "s": 25988, "text": "Example:" }, { "code": null, "e": 26381, "s": 25997, "text": "HTML Code:<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /></head> <body> <img id=\"cursor\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200319212118/cursor2.png\" width=\"15\" height=\"20\" /> <p> <button id=\"b1\">BUTTON1</button> </p> <p> <button id=\"b2\">BUTTON2</button> </p> </body> </html> " }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /></head> <body> <img id=\"cursor\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200319212118/cursor2.png\" width=\"15\" height=\"20\" /> <p> <button id=\"b1\">BUTTON1</button> </p> <p> <button id=\"b2\">BUTTON2</button> </p> </body> </html> ", "e": 26755, "s": 26381, "text": null }, { "code": null, "e": 27030, "s": 26755, "text": "CSS Code:<style> img { pointer-events: none; /* doing this makes sure .elementFromPoint do not acquires the image cursor object */ position: absolute; } /* makes the cursor invisible */ * { cursor: none; }</style>" }, { "code": "<style> img { pointer-events: none; /* doing this makes sure .elementFromPoint do not acquires the image cursor object */ position: absolute; } /* makes the cursor invisible */ * { cursor: none; }</style>", "e": 27296, "s": 27030, "text": null }, { "code": null, "e": 29450, "s": 27296, "text": "JavaScript Code:<script> var x, y; var px, py; px = py = 0; // Image of cursor var cursor = document.getElementById(\"cursor\"); // Button 1 var b1 = document.getElementById(\"b1\"); // Button 2 var b2 = document.getElementById(\"b2\"); /* mutex is used to avoid multiple click event from firing at the same time due to different position of image cursor and actual cursor Using mutex avoid any conflicts if original cursor and image cursor are both on a clickable element This makes sure only 1 click event is triggered at a time*/ var mutex = false; /* The following event is selecting the element on the image cursor and fires click() on it. The following event is triggered only when mouse is pressed. */ window.addEventListener(\"mouseup\", function(e) { // gets the object on image cursor position var tmp = document.elementFromPoint(x + px, y + py); mutex = true; tmp.click(); cursor.style.left = (px + x) + \"px\"; cursor.style.top = (py + y) + \"px\"; }) /* The following event listener moves the image pointer with respect to the actual mouse cursor The function is triggered every time mouse is moved */ window.addEventListener(\"mousemove\", function(e) { // Gets the x,y position of the mouse cursor x = e.clientX; y = e.clientY; // sets the image cursor to new relative position cursor.style.left = (px + x) + \"px\"; cursor.style.top = (py + y) + \"px\"; }); /* The following function re-calculates px,py with respect to new position Clicking on b1 moves the pointer to b2 Clicking on b2 moves the pointer to b1 */ b1.onclick = function() { if (mutex) { mutex = false; px = b2.offsetLeft - x; py = b2.offsetTop - y; } } b2.onclick = function() { if (mutex) { mutex = false; px = b1.offsetLeft - x; py = b1.offsetTop - y; } }</script>" }, { "code": "<script> var x, y; var px, py; px = py = 0; // Image of cursor var cursor = document.getElementById(\"cursor\"); // Button 1 var b1 = document.getElementById(\"b1\"); // Button 2 var b2 = document.getElementById(\"b2\"); /* mutex is used to avoid multiple click event from firing at the same time due to different position of image cursor and actual cursor Using mutex avoid any conflicts if original cursor and image cursor are both on a clickable element This makes sure only 1 click event is triggered at a time*/ var mutex = false; /* The following event is selecting the element on the image cursor and fires click() on it. The following event is triggered only when mouse is pressed. */ window.addEventListener(\"mouseup\", function(e) { // gets the object on image cursor position var tmp = document.elementFromPoint(x + px, y + py); mutex = true; tmp.click(); cursor.style.left = (px + x) + \"px\"; cursor.style.top = (py + y) + \"px\"; }) /* The following event listener moves the image pointer with respect to the actual mouse cursor The function is triggered every time mouse is moved */ window.addEventListener(\"mousemove\", function(e) { // Gets the x,y position of the mouse cursor x = e.clientX; y = e.clientY; // sets the image cursor to new relative position cursor.style.left = (px + x) + \"px\"; cursor.style.top = (py + y) + \"px\"; }); /* The following function re-calculates px,py with respect to new position Clicking on b1 moves the pointer to b2 Clicking on b2 moves the pointer to b1 */ b1.onclick = function() { if (mutex) { mutex = false; px = b2.offsetLeft - x; py = b2.offsetTop - y; } } b2.onclick = function() { if (mutex) { mutex = false; px = b1.offsetLeft - x; py = b1.offsetTop - y; } }</script>", "e": 31588, "s": 29450, "text": null }, { "code": null, "e": 31689, "s": 31588, "text": "Final Solution: In this section we will combine all the above section into one and perform the task." }, { "code": "<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <title></title> <style> img { pointer-events: none; /* doing this makes sure .elementFromPoint do not acquires the image cursor object */ position: absolute; } /* makes the cursor invisible */ * { cursor: none; } </style></head> <body> <img id=\"cursor\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200319212118/cursor2.png\" width=\"15\" height=\"20\" /> <p> <button id=\"b1\">BUTTON1</button> </p> <p> <button id=\"b2\">BUTTON2</button> </p> <script> var x, y; var px, py; px = py = 0; // Image of cursor var cursor = document.getElementById(\"cursor\"); // Button 1 var b1 = document.getElementById(\"b1\"); // Button 2 var b2 = document.getElementById(\"b2\"); /* mutex is used to avoid multiple click event from firing at the same time due to different position of image cursor and actual cursor Using mutex avoid any conflicts if original cursor and image cursor are both on a clickable element This makes sure only 1 click event is triggered at a time*/ var mutex = false; /* The following event is selecting the element on the image cursor and fires click() on it. The following event is triggered only when mouse is pressed. */ window.addEventListener(\"mouseup\", function(e) { // gets the object on image cursor position var tmp = document.elementFromPoint(x + px, y + py); mutex = true; tmp.click(); cursor.style.left = (px + x) + \"px\"; cursor.style.top = (py + y) + \"px\"; }) /* The following event listener moves the image pointer with respect to the actual mouse cursor The function is triggered every time mouse is moved */ window.addEventListener(\"mousemove\", function(e) { // Gets the x,y position of the mouse cursor x = e.clientX; y = e.clientY; // sets the image cursor to new relative position cursor.style.left = (px + x) + \"px\"; cursor.style.top = (py + y) + \"px\"; }); /* The following function re-calculates px,py with respect to new position Clicking on b1 moves the pointer to b2 Clicking on b2 moves the pointer to b1 */ b1.onclick = function() { if (mutex) { mutex = false; px = b2.offsetLeft - x; py = b2.offsetTop - y; } } b2.onclick = function() { if (mutex) { mutex = false; px = b1.offsetLeft - x; py = b1.offsetTop - y; } } </script> </body> </html>", "e": 34726, "s": 31689, "text": null }, { "code": null, "e": 34734, "s": 34726, "text": "Output:" }, { "code": null, "e": 34744, "s": 34734, "text": "as5853535" }, { "code": null, "e": 34753, "s": 34744, "text": "CSS-Misc" }, { "code": null, "e": 34763, "s": 34753, "text": "HTML-Misc" }, { "code": null, "e": 34779, "s": 34763, "text": "JavaScript-Misc" }, { "code": null, "e": 34783, "s": 34779, "text": "CSS" }, { "code": null, "e": 34788, "s": 34783, "text": "HTML" }, { "code": null, "e": 34799, "s": 34788, "text": "JavaScript" }, { "code": null, "e": 34816, "s": 34799, "text": "Web Technologies" }, { "code": null, "e": 34843, "s": 34816, "text": "Web technologies Questions" }, { "code": null, "e": 34848, "s": 34843, "text": "HTML" }, { "code": null, "e": 34946, "s": 34848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34955, "s": 34946, "text": "Comments" }, { "code": null, "e": 34968, "s": 34955, "text": "Old Comments" }, { "code": null, "e": 35026, "s": 34968, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 35063, "s": 35026, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 35104, "s": 35063, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 35141, "s": 35104, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 35205, "s": 35141, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 35265, "s": 35205, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 35326, "s": 35265, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 35363, "s": 35326, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 35416, "s": 35363, "text": "Hide or show elements in HTML using display property" } ]
Setting the limits on a colorbar of a contour plot in Matplotlib
To set the limits on a colorbar of a countour plot in Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create x and y data points using numpy. Get the data using x and y. Get the coordinate matrices from the coordinate vectors. Initialize vmin and vmax to set the limits on a colorbar of a contour plot in matplotlib. Plot contours using contourf() method. Make the colorbar using scalar mappable within the range of vmin and vmax. To display the figure, use show() method. from matplotlib import pyplot as plt import numpy as np from matplotlib.cm import ScalarMappable plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.arange(20) y = np.arange(20) data = x[:, None] + y[None, :] X, Y = np.meshgrid(x, y) vmin = 0 vmax = 15 fig, ax = plt.subplots() qcs = ax.contourf( X, Y, data, vmin=vmin, vmax=vmax ) fig.colorbar( ScalarMappable(norm=qcs.norm, cmap=qcs.cmap), ticks=range(vmin, vmax+5, 5) ) plt.show()
[ { "code": null, "e": 1162, "s": 1062, "text": "To set the limits on a colorbar of a countour plot in Matplotlib, we can take the following steps −" }, { "code": null, "e": 1238, "s": 1162, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1278, "s": 1238, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1306, "s": 1278, "text": "Get the data using x and y." }, { "code": null, "e": 1363, "s": 1306, "text": "Get the coordinate matrices from the coordinate vectors." }, { "code": null, "e": 1453, "s": 1363, "text": "Initialize vmin and vmax to set the limits on a colorbar of a contour plot in matplotlib." }, { "code": null, "e": 1492, "s": 1453, "text": "Plot contours using contourf() method." }, { "code": null, "e": 1567, "s": 1492, "text": "Make the colorbar using scalar mappable within the range of vmin and vmax." }, { "code": null, "e": 1609, "s": 1567, "text": "To display the figure, use show() method." }, { "code": null, "e": 2111, "s": 1609, "text": "from matplotlib import pyplot as plt\nimport numpy as np\nfrom matplotlib.cm import ScalarMappable\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.arange(20)\ny = np.arange(20)\n\ndata = x[:, None] + y[None, :]\nX, Y = np.meshgrid(x, y)\n\nvmin = 0\nvmax = 15\n\nfig, ax = plt.subplots()\n\nqcs = ax.contourf(\n X, Y, data,\n vmin=vmin, vmax=vmax\n)\n\nfig.colorbar(\n ScalarMappable(norm=qcs.norm, cmap=qcs.cmap),\n ticks=range(vmin, vmax+5, 5)\n)\n\nplt.show()" } ]
LESS - Extend
Extend is a LESS pseudo class which extends other selector styles in one selector by using :extend selector. The following example demonstrates the use of extend in the LESS file − <!doctype html> <head> <link rel = "stylesheet" href = "style.css" type = "text/css" /> </head> <body> <div class = "style"> <h2>Welcome to TutorialsPoint</h2> <p>Hello!!!!!</p> </div> </body> </html> Next, create the style.less file. h2 { &:extend(.style); font-style: italic; } .style { background: green; } You can compile the extend.less file to extend.css by using the following command − lessc style.less style.css Execute the above command; it will create the style.css file automatically with the following code − h2 { font-style: italic; } .style, h2 { background: blue; } Follow these steps to see how the above code works − Save the above html code in the extend_syntax.htm file. Save the above html code in the extend_syntax.htm file. Open this HTML file in a browser, the following output will get displayed. Open this HTML file in a browser, the following output will get displayed. Extend is placed into ruleset or attached to a selector. It is similar to a pseudo class containing one or more classes, which are separated by comma. Using the optional keyword all, each selector can be followed. The following example demonstrates the use of extend syntax in the LESS file − <!doctype html> <head> <link rel = "stylesheet" href = "style.css" type = "text/css" /> </head> <body> <div class = "style"> <h2>Welcome to TutorialsPoint</h2> <div class = "container"> <p>Hello!!!!!</p> </div> </div> </body> </html> Now create the style.less file. .style:extend(.container, .img) { background: #BF70A5; } .container { font-style: italic; } .img { font-size: 30px; } You can compile the style.less file to style.css by using the following command − lessc style.less style.css Execute the above command; it will create the style.css file automatically with the following code − .style { background: #BF70A5; } .container, .style { font-style: italic; } .img, .style { font-size: 30px; } Follow these steps to see how the above code works − Save the above html code in the extend_syntax.htm file. Save the above html code in the extend_syntax.htm file. Open this HTML file in a browser, the following output will get displayed. Open this HTML file in a browser, the following output will get displayed. The following table lists all the types of extend syntax which you can use in LESS − Extend is connected to a selector which looks similar to a pseudo class with selector as parameter. The &:extend(selector) syntax can be put inside the body of ruleset. Nested selectors are matched using the extend selector. By default, extend looks for the exact match between the selectors. The form of nth expression is important in extend otherwise, it treats selector as different. When the keyword all is identified at last in the extend argument then LESS matches that selector as part of another selector. The extend can be connected to interpolated selector. Extend matches the selector only that is present inside the same media declaration. It cannot detect the duplication of selectors. Following are the types of Use Cases for Extend Classic use case is used to avoid adding the base class in LESS. Extend is used to move the selector as far as the properties you want to use; this helps in reducing the css generated code. Using extend we can combine the same styles of a particular selectors into other selector. 20 Lectures 1 hours Anadi Sharma 44 Lectures 7.5 hours Eduonix Learning Solutions 17 Lectures 2 hours Zach Miller 23 Lectures 1.5 hours Zach Miller 34 Lectures 4 hours Syed Raza 31 Lectures 3 hours Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2659, "s": 2550, "text": "Extend is a LESS pseudo class which extends other selector styles in one selector by using :extend selector." }, { "code": null, "e": 2731, "s": 2659, "text": "The following example demonstrates the use of extend in the LESS file −" }, { "code": null, "e": 2981, "s": 2731, "text": "<!doctype html>\n <head>\n <link rel = \"stylesheet\" href = \"style.css\" type = \"text/css\" />\n </head>\n\n <body>\n <div class = \"style\">\n <h2>Welcome to TutorialsPoint</h2>\n <p>Hello!!!!!</p>\n </div>\n </body>\n</html>" }, { "code": null, "e": 3015, "s": 2981, "text": "Next, create the style.less file." }, { "code": null, "e": 3100, "s": 3015, "text": "h2 {\n &:extend(.style);\n font-style: italic;\n}\n\n.style {\n background: green;\n}" }, { "code": null, "e": 3184, "s": 3100, "text": "You can compile the extend.less file to extend.css by using the following command −" }, { "code": null, "e": 3212, "s": 3184, "text": "lessc style.less style.css\n" }, { "code": null, "e": 3313, "s": 3212, "text": "Execute the above command; it will create the style.css file automatically with the following code −" }, { "code": null, "e": 3380, "s": 3313, "text": "h2 {\n font-style: italic;\n}\n\n.style,\nh2 {\n background: blue;\n}" }, { "code": null, "e": 3433, "s": 3380, "text": "Follow these steps to see how the above code works −" }, { "code": null, "e": 3489, "s": 3433, "text": "Save the above html code in the extend_syntax.htm file." }, { "code": null, "e": 3545, "s": 3489, "text": "Save the above html code in the extend_syntax.htm file." }, { "code": null, "e": 3620, "s": 3545, "text": "Open this HTML file in a browser, the following output will get displayed." }, { "code": null, "e": 3695, "s": 3620, "text": "Open this HTML file in a browser, the following output will get displayed." }, { "code": null, "e": 3909, "s": 3695, "text": "Extend is placed into ruleset or attached to a selector. It is similar to a pseudo class containing one or more classes, which are separated by comma. Using the optional keyword all, each selector can be followed." }, { "code": null, "e": 3988, "s": 3909, "text": "The following example demonstrates the use of extend syntax in the LESS file −" }, { "code": null, "e": 4309, "s": 3988, "text": "<!doctype html>\n <head>\n <link rel = \"stylesheet\" href = \"style.css\" type = \"text/css\" />\n </head>\n\n <body>\n <div class = \"style\">\n <h2>Welcome to TutorialsPoint</h2>\n \n <div class = \"container\">\n <p>Hello!!!!!</p>\n </div>\n \n </div>\n </body>\n</html>" }, { "code": null, "e": 4341, "s": 4309, "text": "Now create the style.less file." }, { "code": null, "e": 4470, "s": 4341, "text": ".style:extend(.container, .img) {\n background: #BF70A5;\n}\n\n.container {\n font-style: italic;\n}\n\n.img {\n font-size: 30px;\n}" }, { "code": null, "e": 4552, "s": 4470, "text": "You can compile the style.less file to style.css by using the following command −" }, { "code": null, "e": 4580, "s": 4552, "text": "lessc style.less style.css\n" }, { "code": null, "e": 4681, "s": 4580, "text": "Execute the above command; it will create the style.css file automatically with the following code −" }, { "code": null, "e": 4801, "s": 4681, "text": ".style {\n background: #BF70A5;\n}\n\n.container,\n.style {\n font-style: italic;\n}\n\n.img,\n.style {\n font-size: 30px;\n}" }, { "code": null, "e": 4854, "s": 4801, "text": "Follow these steps to see how the above code works −" }, { "code": null, "e": 4910, "s": 4854, "text": "Save the above html code in the extend_syntax.htm file." }, { "code": null, "e": 4966, "s": 4910, "text": "Save the above html code in the extend_syntax.htm file." }, { "code": null, "e": 5041, "s": 4966, "text": "Open this HTML file in a browser, the following output will get displayed." }, { "code": null, "e": 5116, "s": 5041, "text": "Open this HTML file in a browser, the following output will get displayed." }, { "code": null, "e": 5201, "s": 5116, "text": "The following table lists all the types of extend syntax which you can use in LESS −" }, { "code": null, "e": 5301, "s": 5201, "text": "Extend is connected to a selector which looks similar to a pseudo class with selector as parameter." }, { "code": null, "e": 5370, "s": 5301, "text": "The &:extend(selector) syntax can be put inside the body of ruleset." }, { "code": null, "e": 5426, "s": 5370, "text": "Nested selectors are matched using the extend selector." }, { "code": null, "e": 5494, "s": 5426, "text": "By default, extend looks for the exact match between the selectors." }, { "code": null, "e": 5588, "s": 5494, "text": "The form of nth expression is important in extend otherwise, it treats selector as different." }, { "code": null, "e": 5715, "s": 5588, "text": "When the keyword all is identified at last in the extend argument then LESS matches that selector as part of another selector." }, { "code": null, "e": 5769, "s": 5715, "text": "The extend can be connected to interpolated selector." }, { "code": null, "e": 5853, "s": 5769, "text": "Extend matches the selector only that is present inside the same media declaration." }, { "code": null, "e": 5900, "s": 5853, "text": "It cannot detect the duplication of selectors." }, { "code": null, "e": 5948, "s": 5900, "text": "Following are the types of Use Cases for Extend" }, { "code": null, "e": 6013, "s": 5948, "text": "Classic use case is used to avoid adding the base class in LESS." }, { "code": null, "e": 6138, "s": 6013, "text": "Extend is used to move the selector as far as the properties you want to use; this helps in reducing the css generated code." }, { "code": null, "e": 6229, "s": 6138, "text": "Using extend we can combine the same styles of a particular selectors into other selector." }, { "code": null, "e": 6262, "s": 6229, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 6276, "s": 6262, "text": " Anadi Sharma" }, { "code": null, "e": 6311, "s": 6276, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6339, "s": 6311, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6372, "s": 6339, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 6385, "s": 6372, "text": " Zach Miller" }, { "code": null, "e": 6420, "s": 6385, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6433, "s": 6420, "text": " Zach Miller" }, { "code": null, "e": 6466, "s": 6433, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 6477, "s": 6466, "text": " Syed Raza" }, { "code": null, "e": 6510, "s": 6477, "text": "\n 31 Lectures \n 3 hours \n" }, { "code": null, "e": 6530, "s": 6510, "text": " Harshit Srivastava" }, { "code": null, "e": 6537, "s": 6530, "text": " Print" }, { "code": null, "e": 6548, "s": 6537, "text": " Add Notes" } ]
Generating Regressions in the Automated Data Analysis Process | by Peter Grant | Towards Data Science
This is the sixth article in a four part series teaching you how to automate scientific data analysis. The first article introduced the concept, provided motivation, and described the general process. The second, third, and fourth articles described how to control data sets, identify the conditions in each test, process the data, and check the data for errors. The fifth article described how to store the data in a logical manner to facilitate generating regressions. This sixth, and final, article will teach you how to develop regressions from those results, and validate and document the resulting models. The final Python-based automation of laboratory data analysis topic to discuss is that of generating and validating regressions from the stored data. This is often the ultimate goal of laboratory data analysis projects, and there are still several things to think through before declaring the project completed. When generating regressions, the following topics must be considered: How to determine the optimal order of the regression, Creating 1-dimensional regressions with numpy, An introduction to scikit-learn for creating n-dimensional regressions, Validating models, and Visualizing the results of the regression and validation. This section occasionally uses the example of regressions predicting the performance of heat exchangers. For an introduction to that technology, and the testing and data analysis used to model them, see Part 2. The order of the regression has a dramatic impact on the prediction accuracy of the resulting model. Higher order regressions are much more flexible providing the ability to statistically match data sets better than lower order regressions, or the ability to match more complex data sets. However, the increased flexibility can lead to models that statistically appear to fit the data well, but have dramatic inaccuracies when making predictions between measured points in the data set. Lower order regressions are less flexible, often struggling to statistically match the data as well, but providing a more stable prediction. This can result in lower accuracy at the measured points, but higher accuracy in between. The difference is created by the number of data points in the data set. More data points are needed to create stable regressions of higher order. Figures 1 and 2 show this effect plainly. Both figures show 2nd, 3rd, and 4th order regressions. Figure 1 shows the regressions created with a thorough data set. Notice how there are not dramatic differences in the regressions. The 4th order regression fits the data set a little closer than the 3rd, and the 3rd slightly better than the 2nd. But they are all quite close, and since the trends are quite close to those shown by the measured data, they can be trusted to accurately predict intermediate values. In this case, clearly the 4th order regression should be chosen. The same cannot be true of the regressions in Figure 2. Figure 2 shows regressions created using a subset of the same set of measured data. In this case, the 4th order regression again matches the measured data points better than the 2nd or 3rd order regressions. However, there’s a combination of too much complexity and not enough data for the higher order regressions. As they attempt to match the shape of the curve presented by the data points with the limited data set, they become less stable. This can be observed by how wavey the 3rd, and especially the 4th order regressions are. While the 4th order regression clearly matches the measured data the best of the three, it cannot be trusted to interpolate within the bounds of the data set. This is especially true at flow rates above 3.5 gal/min. There are several possible solutions to this problem. They are, listed in order of preference, as follows: Collect more data to create a better data set, Split the data set into multiple sections and generate multiple lower order regressions, and Attempt to identify the best regression from the currently available options. Collecting more data yields a more stable regression by providing more points constraining it. When identifying new tests to improve the data set, specify tests that fill wide gaps in the current set. For instance, the reduced data set shown in Figure 2 would be much more complete if additional points were added to fill the gaps from 3.5 to 5.5 gal/min, and from 5.5 to 7.5 gal/min. Splitting the data means identifying multiple sections that could each have a separate, smooth regression, splitting the data set into those multiple sections, and creating individual regressions for those split data sets. While it reduces the amount of data for each regression, it creates smoother shapes for them to match. As a result, it’s possible to get a smoother curve, and a better match, even with the smaller data set. In this case, splitting the data set to create one regression from 0.5–2 gal/min, and a second for 2.5–7.5 gal/min yields much better results. Figure 3 shows the result of creating a second and third order regression using the previously stated split. The results show a much better match with the split data set than they did with a single data set. The split occurs at 2 gal/min and is evident by a sudden increase in the prediction from the 2nd order regression. This bump shows an increase in error using the 2nd order regression in the range from 2.0–2.5 gal/min. Aside from that region, the 2nd order regression matches the data set very closely. The 3rd order regression does not show the same uncertainty at the split point, and very closely matches the regression over the entire 0.5–7.5 gal/min range. This shows that the approach of splitting the data set at 2 gal/min, and creating separate regressions for above and below, is very effective for this data set. The least effective approach, reserved for when it’s not possible to collect more data and splitting the data set doesn’t yield satisfying results, is to choose the best regression from the available options. In this data set, and the regressions presented in Figure 2, this means using the fourth order regression. The second order regression may be the smoothest of the three options, but it clearly overpredicts the effectiveness at low flow rates and underpredicts at high flow rates. The third order regression is a little closer, but also a little less stable. The fourth order regression very closely matches both the data points and the trend very closely until 3.5 gal/min. From 3.5 to 5.5 gal/min it will overpredict, and from 5.5 gal/min to 7.5 gal/min it will underpredict; however, inaccurate predictions in that range is true of all three options, and not much more dramatic than the third order regression. When using this regression, it will be important to remember that it’s extremely accurate below 2.5 gal/min, and less trustworthy at higher flow rates. NumPy is a package of scientific computing tools available in Python. Among the many tools it provides is a toolset for creating 1-dimensional regressions. The main two tools are: polyfit: This tool identifies the coefficients of a 1-dimensional, nth order polynomial using the x and y data provided by the user. NumPy.polyfit is called with the syntax “numpy.polyfit(Data_x, Data_y, Order)”. poly1d: poly1d creates a regression using user-specified coefficients and assigns them to a variable so that the regression can easily be referenced later. NumPy.poly1d is called with the syntax “numpy.poly1d(Coefficients)”. These tools can generate regressions of results quite naturally if the results were stored in a manner consistent with the recommendations in Storing Intermediate Results for Later Analysis. The process uses the following steps: 1. Open the data file containing the desired data, and store it in a data frame. For this example, the data frame will be called “Data.” 2. Use NumPy.polyfit to identify the coefficients for the data set and store them to a variable. This can be done with code similar to the following: Coefficients = numpy.polyfit(Data[‘Flow Rate (gal/min)’], Data[‘Effectiveness (-)’], 2) In this case, the coefficients for a 2nd order regression with flow rate as the x data and effectiveness as the y data are stored to the variable “Coefficients”. In the heat exchanger, this data set only has a single flow rate representing a situation with the same flow rate on either side of the device. 3. Call NumPy.poly1d with the coefficients to assign the regression as a function to a variable. For example, the coefficients from the previous step could be used to create a regression using the following: Effectiveness_SecondOrder = numpy.poly1d(Coefficients) Now the effectiveness of this heat exchanger can be estimated using a second order regression by calling the “Effectiveness_SecondOrder” function. 4. The final step is calling the function to generate the desired regressed estimate. A few examples of how this could be used are as follows: If using the regression to evaluate the result in a specific condition, call the function referencing that condition and assign it to a descriptive variable. For example, the effectiveness of this heat exchanger with the same 2 gallons/minute of flow on either sidecould be identified and saved with: Effectiveness_2_GalPerMin = Effectiveness_SecondOrder(2). Another possible use is filling a column of a data frame with estimated regressed values. This is extremely useful when validating models, as the regressed estimates can be stored in a data frame right next to the measured values and easily compared. This can be done with code similar to: Data[‘Effectiveness, Estimated, Second Order (-)’] = Effectiveness_SecondOrder(Data[‘Flow Rate (gal/min)’] c. A third possibility allows plotting of smooth regressed curves, and uses the NumPy “arange” function. NumPy.arange creates a range of values as specified by the user. It’s done with the syntax: numpy.arange(Minimum Value, Maximum Value, Step) For example, numpy.arange(0.5, 7.6, 0.1) creates a range starting at 0.5, with each value increasing by a step of 0.1, and a maximum value of 7.6. This works well for plotting smooth curves, because it’s a quick way to predict the result of the regression at the desired interval. For instance, the following code will create an x and y data set for plotting the curve of this regression with an interval of 0.1 gal/min from a minimum of 0.5 to a maximum of 7.5 gal/min: x_array = np.arange(0.5, 7.6, 0.1)Effectiveness_array = Effectiveness_SecondOrder(x_array) Currently the best tool for creating n-dimensional, nth order regressions is the scikit-learn package. It’s based on scipy, NumPy, and matplotlib, and is commonly used in the field of data science and machine learning. It provides many different tools for regressions, with many different approaches. Those interested in learning about all of the capabilities in scikit-learn should consult their documentation, and be prepared to learn about many different types of regression techniques. An understanding of the fundamentals of data science would also be beneficial, and Andrew Ng has published an informative, free course on Coursera.org. Since a full discussion of data science and scikit-learn is entirely too large for this text, this section focuses on introducing some basic linear regression techniques. Two very useful tools for creating linear regressions with scikit-learn are 1) sklearn.preprocessing.PolynomialFeatures and 2) sklearn.linear_model.LinearRegression. PolynomialFeatures provides a set of matrix operations, which are used to massage the data into the form needed by LinearRegression. It creates a matrix consisting of all combinations of the input variables of degree less than or equal to that specified by the user. For example, a matrix created using PolynomialFeatures with two input variables (x and y) preparing a 2nd order model will have the terms [1, x, y, x2, xy, y2]. This approach is sometimes referred to as “black-box modeling” because it does not attempt to understand the structure behind why the model behaves this way, and instead aims to create a matching regression based solely on mathematical techniques. The input matrix can be created using the following steps: Create the matrix object by calling PolynomialFeatures and specifying the order of the regression. Note that scikit-learn uses the term “degree” instead of “order.”Arrange the input data in the correct format for the upcoming linear regression. For use with PolynomialFeatures, this means a single matrix containing submatrices specifying the conditions for each test. For example, the input matrix with three tests and two input conditions will be of the form [[x_1, y_1], [x_2, y_2], [x_3, y_3]].Call the PolynomialFeatures fit_transform function on the input data, and use numpy.delete to remove the first row. Create the matrix object by calling PolynomialFeatures and specifying the order of the regression. Note that scikit-learn uses the term “degree” instead of “order.” Arrange the input data in the correct format for the upcoming linear regression. For use with PolynomialFeatures, this means a single matrix containing submatrices specifying the conditions for each test. For example, the input matrix with three tests and two input conditions will be of the form [[x_1, y_1], [x_2, y_2], [x_3, y_3]]. Call the PolynomialFeatures fit_transform function on the input data, and use numpy.delete to remove the first row. As an example, the following code generates the correct matrix for a 5th order regression with the two inputs ‘Hot Flow Rate (gal/min)’ and ‘Cold Flow Rate (gal/min)’. Note that the input data matrix is created using a for loop that reads values from the Effectiveness data frame. poly = PolynomialFeatures(degree=5)All_Flow_Pairs = []for i in Effectiveness.index: FlowRate_Hot = Effectiveness.loc[i, ‘Hot Flow Rate (gal/min)’] FlowRate_Cold = Effectiveness.loc[i, Cold Flow Rate (gal/min)’] All_Flow_Pairs.append([FlowRate_Hot, FlowRate_Cold]) All_Flow_Pairs_Transformed = poly.fit_transform(All_Flow_Pairs) All_Flow_Pairs_Transformed = np.delete(All_Flow_Pairs_Transformed, (0), axis = 1) LinearRegression is designed to easily accept this matrix, and generate the specified regression. It provides four functions that are especially useful for this process. They are: .fit: This function accepts the input data matrix, and a matching result matrix, and fits the regression specified in PolynomialFeatures to the data. This is the step that creates the regression. .coef_: This function prints the coefficients describing the regression. Storing the result from .coef_ to a variable, and printing it at the end of the program allows storage of the coefficients for later, external use. .intercept_: This function returns the value of the regression if all inputs are set to 0. .score: This function returns the r2 value of the regression when compared to the data set used to create it. It provides a measure of how capable the regression is of predicting the input data set. This concept will be discussed more in the next section. The following code continues the example from PolynomialFeatures, and shows how the functions of LinearRegression can create, document, and test a regression. clf = LinearRegression()clf.fit(All_Flow_Pairs_Transformed, Effectiveness[‘Effectiveness (-)’])n_Dimensional_Coefficients = clf.coef_n_Dimensional_Intercept = clf.intercept_n_Dimensional_Score = clf.score(All_Flow_Pairs_Transformed, Effectiveness[‘Effectiveness (-)’]) The most important part of model development, and one that is entirely too elaborate to describe in complete detail in this conceptual text, is that of validation. Validation is the process of ensuring that the predictions generated by a modelmatch the phenomena being modeled. This is a complex, multiple-stage process that is never really finished. The steps to perform a quality model validation are as follows: Ensure that the model matches the data set used to create it, Compare the model predictions to an additional data set, Publish the report detailing the strengths, weaknesses, and appropriate applications of the model. The first step is to compare the model predictions to the source data. This step is commonly referred to as “verification.” The goal of this step is simple: Ensure that the model matches the experimental data used to create it. In situations where a specific data set was created explicitly for creating the model, as is discussed in this book, the error in the model should be extremely low. When performing this step, there are two general questions to answer: Does the model match the data set within an acceptable limit of error?What aspects of the data set are well/poorly represented by the model? Does the model match the data set within an acceptable limit of error? What aspects of the data set are well/poorly represented by the model? Typically, a model is considered to match the data set within an acceptable limit of error if the error is less than the uncertainty of the measurements used to collect the data. This is often used as the limit, because it represents the limits of the knowledge; if the error between the model and the measurements is less than the uncertainty in the measurements, then there’s no way to know that the model is imperfect. Inevitably, the model will be better at some predictions than others. It’s important to identify, and investigate these differences. They may show deficiencies in the model, and different modeling approaches may need to be used to correct them. If they’re minor issues that don’t have significant impact on the final results, then noting them for documentation is sufficient. The section Determining the Optimal Regression Structure provided a few responses to these situations. The second step in model validation is comparing the model predictions to a second data set. This is an important step because the first step didn’t really validate the model, it merely showed that it’s capable of matching the data set that it was mathematically forced to match. The solution to this challenge is to include extra tests in the test plan, but not include them in the data set used to generate the regression. Keep them in a separate data set, created solely for the purposes of model validation. This way they have no impact on the regression, and provide additional points which can be used for the validation check. The tests in the validation data set should test the model as thoroughly as possible. Include tests in regions where the model is highly sensitive to changes in inputs, to ensure that it gets the predictions in those ranges correct. Include variation in all the different variables in the model, to ensure that it accurately predicts the behavior of the model in response to changes in those variables. Place tests in areas where there are large gaps in between data points in the original data set, to ensure that the model remains stable in those regions, as was shown in Creating the Optimal Regression Structure. During this validation phase, attempt to answer the same questions as in the first phase. Is the model accurate within measurement uncertainty? Are there areas where it’s more accurate than others? If it isn’t accurate within measurement uncertainty, can the model be improved? As before, any issues that can be improved should be improved, and any issues that can’t be improved should be documented. The final step of the model validation process is to publish the findings while realizing that it’s more complicated than a simple “valid” or “not valid” declaration. No model is valid in every way, or invalid in every way. Simply proclaiming a model to be invalid doesn’t represent the value that even a limited model can provide. And proclaiming a model to be “valid” gives the impression that it predicts everything accurately, with no weaknesses. The solution to this problem is straightforward: Instead of proclaiming the model to be valid, publish the strengths and weaknesses of the model. This provides users with a more accurate understanding of appropriate uses of the model, allowing them to decide when they should use the model and when they should not. It also provides documentation supporting future efforts to improve the model. As an example, these articles have used the example of developing regressions predicting the steady state effectiveness of heat exchangers. That model was designed to predict the steady state effectiveness when the flow rates are between 0.5 and 7.5 gal/min. It is extremely accurate within so long as the flow rate is identical on either side of the device. The models do not address flow rates out side of that range, or situations with differing flow rates on either side of the device. Also, it is designed specifically for steady state effectiveness and should not be used for predictions in transient simulations. This series of four articles has introduced you to all of the concepts necessary to write programs that automatically analyze your scientific data sets for you. You’ve learned about the following topics: Some possible benefits of automating data analysis, The structure of programs that automate data analysis, How to structure data sets to enable automation, How to identify the conditions of each data test, How to split data files, How to write a for loop iterating through each data file, How to analyze the data in each file, How to check the data in each file for errors, How to store the data from each file so it’s ready for use generating regressions, and How to generate, validate, and document the final regressions from your data set. Hopefully these articles have helped you develop new skills, and hopefully you can use them to find more ease and more satisfaction in your career.
[ { "code": null, "e": 783, "s": 171, "text": "This is the sixth article in a four part series teaching you how to automate scientific data analysis. The first article introduced the concept, provided motivation, and described the general process. The second, third, and fourth articles described how to control data sets, identify the conditions in each test, process the data, and check the data for errors. The fifth article described how to store the data in a logical manner to facilitate generating regressions. This sixth, and final, article will teach you how to develop regressions from those results, and validate and document the resulting models." }, { "code": null, "e": 1165, "s": 783, "text": "The final Python-based automation of laboratory data analysis topic to discuss is that of generating and validating regressions from the stored data. This is often the ultimate goal of laboratory data analysis projects, and there are still several things to think through before declaring the project completed. When generating regressions, the following topics must be considered:" }, { "code": null, "e": 1219, "s": 1165, "text": "How to determine the optimal order of the regression," }, { "code": null, "e": 1266, "s": 1219, "text": "Creating 1-dimensional regressions with numpy," }, { "code": null, "e": 1338, "s": 1266, "text": "An introduction to scikit-learn for creating n-dimensional regressions," }, { "code": null, "e": 1361, "s": 1338, "text": "Validating models, and" }, { "code": null, "e": 1419, "s": 1361, "text": "Visualizing the results of the regression and validation." }, { "code": null, "e": 1630, "s": 1419, "text": "This section occasionally uses the example of regressions predicting the performance of heat exchangers. For an introduction to that technology, and the testing and data analysis used to model them, see Part 2." }, { "code": null, "e": 2348, "s": 1630, "text": "The order of the regression has a dramatic impact on the prediction accuracy of the resulting model. Higher order regressions are much more flexible providing the ability to statistically match data sets better than lower order regressions, or the ability to match more complex data sets. However, the increased flexibility can lead to models that statistically appear to fit the data well, but have dramatic inaccuracies when making predictions between measured points in the data set. Lower order regressions are less flexible, often struggling to statistically match the data as well, but providing a more stable prediction. This can result in lower accuracy at the measured points, but higher accuracy in between." }, { "code": null, "e": 3069, "s": 2348, "text": "The difference is created by the number of data points in the data set. More data points are needed to create stable regressions of higher order. Figures 1 and 2 show this effect plainly. Both figures show 2nd, 3rd, and 4th order regressions. Figure 1 shows the regressions created with a thorough data set. Notice how there are not dramatic differences in the regressions. The 4th order regression fits the data set a little closer than the 3rd, and the 3rd slightly better than the 2nd. But they are all quite close, and since the trends are quite close to those shown by the measured data, they can be trusted to accurately predict intermediate values. In this case, clearly the 4th order regression should be chosen." }, { "code": null, "e": 3875, "s": 3069, "text": "The same cannot be true of the regressions in Figure 2. Figure 2 shows regressions created using a subset of the same set of measured data. In this case, the 4th order regression again matches the measured data points better than the 2nd or 3rd order regressions. However, there’s a combination of too much complexity and not enough data for the higher order regressions. As they attempt to match the shape of the curve presented by the data points with the limited data set, they become less stable. This can be observed by how wavey the 3rd, and especially the 4th order regressions are. While the 4th order regression clearly matches the measured data the best of the three, it cannot be trusted to interpolate within the bounds of the data set. This is especially true at flow rates above 3.5 gal/min." }, { "code": null, "e": 3982, "s": 3875, "text": "There are several possible solutions to this problem. They are, listed in order of preference, as follows:" }, { "code": null, "e": 4029, "s": 3982, "text": "Collect more data to create a better data set," }, { "code": null, "e": 4122, "s": 4029, "text": "Split the data set into multiple sections and generate multiple lower order regressions, and" }, { "code": null, "e": 4200, "s": 4122, "text": "Attempt to identify the best regression from the currently available options." }, { "code": null, "e": 4585, "s": 4200, "text": "Collecting more data yields a more stable regression by providing more points constraining it. When identifying new tests to improve the data set, specify tests that fill wide gaps in the current set. For instance, the reduced data set shown in Figure 2 would be much more complete if additional points were added to fill the gaps from 3.5 to 5.5 gal/min, and from 5.5 to 7.5 gal/min." }, { "code": null, "e": 5267, "s": 4585, "text": "Splitting the data means identifying multiple sections that could each have a separate, smooth regression, splitting the data set into those multiple sections, and creating individual regressions for those split data sets. While it reduces the amount of data for each regression, it creates smoother shapes for them to match. As a result, it’s possible to get a smoother curve, and a better match, even with the smaller data set. In this case, splitting the data set to create one regression from 0.5–2 gal/min, and a second for 2.5–7.5 gal/min yields much better results. Figure 3 shows the result of creating a second and third order regression using the previously stated split." }, { "code": null, "e": 5988, "s": 5267, "text": "The results show a much better match with the split data set than they did with a single data set. The split occurs at 2 gal/min and is evident by a sudden increase in the prediction from the 2nd order regression. This bump shows an increase in error using the 2nd order regression in the range from 2.0–2.5 gal/min. Aside from that region, the 2nd order regression matches the data set very closely. The 3rd order regression does not show the same uncertainty at the split point, and very closely matches the regression over the entire 0.5–7.5 gal/min range. This shows that the approach of splitting the data set at 2 gal/min, and creating separate regressions for above and below, is very effective for this data set." }, { "code": null, "e": 7062, "s": 5988, "text": "The least effective approach, reserved for when it’s not possible to collect more data and splitting the data set doesn’t yield satisfying results, is to choose the best regression from the available options. In this data set, and the regressions presented in Figure 2, this means using the fourth order regression. The second order regression may be the smoothest of the three options, but it clearly overpredicts the effectiveness at low flow rates and underpredicts at high flow rates. The third order regression is a little closer, but also a little less stable. The fourth order regression very closely matches both the data points and the trend very closely until 3.5 gal/min. From 3.5 to 5.5 gal/min it will overpredict, and from 5.5 gal/min to 7.5 gal/min it will underpredict; however, inaccurate predictions in that range is true of all three options, and not much more dramatic than the third order regression. When using this regression, it will be important to remember that it’s extremely accurate below 2.5 gal/min, and less trustworthy at higher flow rates." }, { "code": null, "e": 7242, "s": 7062, "text": "NumPy is a package of scientific computing tools available in Python. Among the many tools it provides is a toolset for creating 1-dimensional regressions. The main two tools are:" }, { "code": null, "e": 7455, "s": 7242, "text": "polyfit: This tool identifies the coefficients of a 1-dimensional, nth order polynomial using the x and y data provided by the user. NumPy.polyfit is called with the syntax “numpy.polyfit(Data_x, Data_y, Order)”." }, { "code": null, "e": 7680, "s": 7455, "text": "poly1d: poly1d creates a regression using user-specified coefficients and assigns them to a variable so that the regression can easily be referenced later. NumPy.poly1d is called with the syntax “numpy.poly1d(Coefficients)”." }, { "code": null, "e": 7909, "s": 7680, "text": "These tools can generate regressions of results quite naturally if the results were stored in a manner consistent with the recommendations in Storing Intermediate Results for Later Analysis. The process uses the following steps:" }, { "code": null, "e": 8046, "s": 7909, "text": "1. Open the data file containing the desired data, and store it in a data frame. For this example, the data frame will be called “Data.”" }, { "code": null, "e": 8196, "s": 8046, "text": "2. Use NumPy.polyfit to identify the coefficients for the data set and store them to a variable. This can be done with code similar to the following:" }, { "code": null, "e": 8284, "s": 8196, "text": "Coefficients = numpy.polyfit(Data[‘Flow Rate (gal/min)’], Data[‘Effectiveness (-)’], 2)" }, { "code": null, "e": 8590, "s": 8284, "text": "In this case, the coefficients for a 2nd order regression with flow rate as the x data and effectiveness as the y data are stored to the variable “Coefficients”. In the heat exchanger, this data set only has a single flow rate representing a situation with the same flow rate on either side of the device." }, { "code": null, "e": 8798, "s": 8590, "text": "3. Call NumPy.poly1d with the coefficients to assign the regression as a function to a variable. For example, the coefficients from the previous step could be used to create a regression using the following:" }, { "code": null, "e": 8853, "s": 8798, "text": "Effectiveness_SecondOrder = numpy.poly1d(Coefficients)" }, { "code": null, "e": 9000, "s": 8853, "text": "Now the effectiveness of this heat exchanger can be estimated using a second order regression by calling the “Effectiveness_SecondOrder” function." }, { "code": null, "e": 9143, "s": 9000, "text": "4. The final step is calling the function to generate the desired regressed estimate. A few examples of how this could be used are as follows:" }, { "code": null, "e": 9444, "s": 9143, "text": "If using the regression to evaluate the result in a specific condition, call the function referencing that condition and assign it to a descriptive variable. For example, the effectiveness of this heat exchanger with the same 2 gallons/minute of flow on either sidecould be identified and saved with:" }, { "code": null, "e": 9502, "s": 9444, "text": "Effectiveness_2_GalPerMin = Effectiveness_SecondOrder(2)." }, { "code": null, "e": 9792, "s": 9502, "text": "Another possible use is filling a column of a data frame with estimated regressed values. This is extremely useful when validating models, as the regressed estimates can be stored in a data frame right next to the measured values and easily compared. This can be done with code similar to:" }, { "code": null, "e": 9899, "s": 9792, "text": "Data[‘Effectiveness, Estimated, Second Order (-)’] = Effectiveness_SecondOrder(Data[‘Flow Rate (gal/min)’]" }, { "code": null, "e": 10096, "s": 9899, "text": "c. A third possibility allows plotting of smooth regressed curves, and uses the NumPy “arange” function. NumPy.arange creates a range of values as specified by the user. It’s done with the syntax:" }, { "code": null, "e": 10145, "s": 10096, "text": "numpy.arange(Minimum Value, Maximum Value, Step)" }, { "code": null, "e": 10616, "s": 10145, "text": "For example, numpy.arange(0.5, 7.6, 0.1) creates a range starting at 0.5, with each value increasing by a step of 0.1, and a maximum value of 7.6. This works well for plotting smooth curves, because it’s a quick way to predict the result of the regression at the desired interval. For instance, the following code will create an x and y data set for plotting the curve of this regression with an interval of 0.1 gal/min from a minimum of 0.5 to a maximum of 7.5 gal/min:" }, { "code": null, "e": 10707, "s": 10616, "text": "x_array = np.arange(0.5, 7.6, 0.1)Effectiveness_array = Effectiveness_SecondOrder(x_array)" }, { "code": null, "e": 11520, "s": 10707, "text": "Currently the best tool for creating n-dimensional, nth order regressions is the scikit-learn package. It’s based on scipy, NumPy, and matplotlib, and is commonly used in the field of data science and machine learning. It provides many different tools for regressions, with many different approaches. Those interested in learning about all of the capabilities in scikit-learn should consult their documentation, and be prepared to learn about many different types of regression techniques. An understanding of the fundamentals of data science would also be beneficial, and Andrew Ng has published an informative, free course on Coursera.org. Since a full discussion of data science and scikit-learn is entirely too large for this text, this section focuses on introducing some basic linear regression techniques." }, { "code": null, "e": 11686, "s": 11520, "text": "Two very useful tools for creating linear regressions with scikit-learn are 1) sklearn.preprocessing.PolynomialFeatures and 2) sklearn.linear_model.LinearRegression." }, { "code": null, "e": 12362, "s": 11686, "text": "PolynomialFeatures provides a set of matrix operations, which are used to massage the data into the form needed by LinearRegression. It creates a matrix consisting of all combinations of the input variables of degree less than or equal to that specified by the user. For example, a matrix created using PolynomialFeatures with two input variables (x and y) preparing a 2nd order model will have the terms [1, x, y, x2, xy, y2]. This approach is sometimes referred to as “black-box modeling” because it does not attempt to understand the structure behind why the model behaves this way, and instead aims to create a matching regression based solely on mathematical techniques." }, { "code": null, "e": 12421, "s": 12362, "text": "The input matrix can be created using the following steps:" }, { "code": null, "e": 13035, "s": 12421, "text": "Create the matrix object by calling PolynomialFeatures and specifying the order of the regression. Note that scikit-learn uses the term “degree” instead of “order.”Arrange the input data in the correct format for the upcoming linear regression. For use with PolynomialFeatures, this means a single matrix containing submatrices specifying the conditions for each test. For example, the input matrix with three tests and two input conditions will be of the form [[x_1, y_1], [x_2, y_2], [x_3, y_3]].Call the PolynomialFeatures fit_transform function on the input data, and use numpy.delete to remove the first row." }, { "code": null, "e": 13200, "s": 13035, "text": "Create the matrix object by calling PolynomialFeatures and specifying the order of the regression. Note that scikit-learn uses the term “degree” instead of “order.”" }, { "code": null, "e": 13535, "s": 13200, "text": "Arrange the input data in the correct format for the upcoming linear regression. For use with PolynomialFeatures, this means a single matrix containing submatrices specifying the conditions for each test. For example, the input matrix with three tests and two input conditions will be of the form [[x_1, y_1], [x_2, y_2], [x_3, y_3]]." }, { "code": null, "e": 13651, "s": 13535, "text": "Call the PolynomialFeatures fit_transform function on the input data, and use numpy.delete to remove the first row." }, { "code": null, "e": 13932, "s": 13651, "text": "As an example, the following code generates the correct matrix for a 5th order regression with the two inputs ‘Hot Flow Rate (gal/min)’ and ‘Cold Flow Rate (gal/min)’. Note that the input data matrix is created using a for loop that reads values from the Effectiveness data frame." }, { "code": null, "e": 14357, "s": 13932, "text": "poly = PolynomialFeatures(degree=5)All_Flow_Pairs = []for i in Effectiveness.index: FlowRate_Hot = Effectiveness.loc[i, ‘Hot Flow Rate (gal/min)’] FlowRate_Cold = Effectiveness.loc[i, Cold Flow Rate (gal/min)’] All_Flow_Pairs.append([FlowRate_Hot, FlowRate_Cold]) All_Flow_Pairs_Transformed = poly.fit_transform(All_Flow_Pairs) All_Flow_Pairs_Transformed = np.delete(All_Flow_Pairs_Transformed, (0), axis = 1)" }, { "code": null, "e": 14537, "s": 14357, "text": "LinearRegression is designed to easily accept this matrix, and generate the specified regression. It provides four functions that are especially useful for this process. They are:" }, { "code": null, "e": 14733, "s": 14537, "text": ".fit: This function accepts the input data matrix, and a matching result matrix, and fits the regression specified in PolynomialFeatures to the data. This is the step that creates the regression." }, { "code": null, "e": 14954, "s": 14733, "text": ".coef_: This function prints the coefficients describing the regression. Storing the result from .coef_ to a variable, and printing it at the end of the program allows storage of the coefficients for later, external use." }, { "code": null, "e": 15045, "s": 14954, "text": ".intercept_: This function returns the value of the regression if all inputs are set to 0." }, { "code": null, "e": 15301, "s": 15045, "text": ".score: This function returns the r2 value of the regression when compared to the data set used to create it. It provides a measure of how capable the regression is of predicting the input data set. This concept will be discussed more in the next section." }, { "code": null, "e": 15460, "s": 15301, "text": "The following code continues the example from PolynomialFeatures, and shows how the functions of LinearRegression can create, document, and test a regression." }, { "code": null, "e": 15729, "s": 15460, "text": "clf = LinearRegression()clf.fit(All_Flow_Pairs_Transformed, Effectiveness[‘Effectiveness (-)’])n_Dimensional_Coefficients = clf.coef_n_Dimensional_Intercept = clf.intercept_n_Dimensional_Score = clf.score(All_Flow_Pairs_Transformed, Effectiveness[‘Effectiveness (-)’])" }, { "code": null, "e": 16144, "s": 15729, "text": "The most important part of model development, and one that is entirely too elaborate to describe in complete detail in this conceptual text, is that of validation. Validation is the process of ensuring that the predictions generated by a modelmatch the phenomena being modeled. This is a complex, multiple-stage process that is never really finished. The steps to perform a quality model validation are as follows:" }, { "code": null, "e": 16206, "s": 16144, "text": "Ensure that the model matches the data set used to create it," }, { "code": null, "e": 16263, "s": 16206, "text": "Compare the model predictions to an additional data set," }, { "code": null, "e": 16362, "s": 16263, "text": "Publish the report detailing the strengths, weaknesses, and appropriate applications of the model." }, { "code": null, "e": 16825, "s": 16362, "text": "The first step is to compare the model predictions to the source data. This step is commonly referred to as “verification.” The goal of this step is simple: Ensure that the model matches the experimental data used to create it. In situations where a specific data set was created explicitly for creating the model, as is discussed in this book, the error in the model should be extremely low. When performing this step, there are two general questions to answer:" }, { "code": null, "e": 16966, "s": 16825, "text": "Does the model match the data set within an acceptable limit of error?What aspects of the data set are well/poorly represented by the model?" }, { "code": null, "e": 17037, "s": 16966, "text": "Does the model match the data set within an acceptable limit of error?" }, { "code": null, "e": 17108, "s": 17037, "text": "What aspects of the data set are well/poorly represented by the model?" }, { "code": null, "e": 17530, "s": 17108, "text": "Typically, a model is considered to match the data set within an acceptable limit of error if the error is less than the uncertainty of the measurements used to collect the data. This is often used as the limit, because it represents the limits of the knowledge; if the error between the model and the measurements is less than the uncertainty in the measurements, then there’s no way to know that the model is imperfect." }, { "code": null, "e": 18009, "s": 17530, "text": "Inevitably, the model will be better at some predictions than others. It’s important to identify, and investigate these differences. They may show deficiencies in the model, and different modeling approaches may need to be used to correct them. If they’re minor issues that don’t have significant impact on the final results, then noting them for documentation is sufficient. The section Determining the Optimal Regression Structure provided a few responses to these situations." }, { "code": null, "e": 18289, "s": 18009, "text": "The second step in model validation is comparing the model predictions to a second data set. This is an important step because the first step didn’t really validate the model, it merely showed that it’s capable of matching the data set that it was mathematically forced to match." }, { "code": null, "e": 18643, "s": 18289, "text": "The solution to this challenge is to include extra tests in the test plan, but not include them in the data set used to generate the regression. Keep them in a separate data set, created solely for the purposes of model validation. This way they have no impact on the regression, and provide additional points which can be used for the validation check." }, { "code": null, "e": 19260, "s": 18643, "text": "The tests in the validation data set should test the model as thoroughly as possible. Include tests in regions where the model is highly sensitive to changes in inputs, to ensure that it gets the predictions in those ranges correct. Include variation in all the different variables in the model, to ensure that it accurately predicts the behavior of the model in response to changes in those variables. Place tests in areas where there are large gaps in between data points in the original data set, to ensure that the model remains stable in those regions, as was shown in Creating the Optimal Regression Structure." }, { "code": null, "e": 19661, "s": 19260, "text": "During this validation phase, attempt to answer the same questions as in the first phase. Is the model accurate within measurement uncertainty? Are there areas where it’s more accurate than others? If it isn’t accurate within measurement uncertainty, can the model be improved? As before, any issues that can be improved should be improved, and any issues that can’t be improved should be documented." }, { "code": null, "e": 20112, "s": 19661, "text": "The final step of the model validation process is to publish the findings while realizing that it’s more complicated than a simple “valid” or “not valid” declaration. No model is valid in every way, or invalid in every way. Simply proclaiming a model to be invalid doesn’t represent the value that even a limited model can provide. And proclaiming a model to be “valid” gives the impression that it predicts everything accurately, with no weaknesses." }, { "code": null, "e": 20507, "s": 20112, "text": "The solution to this problem is straightforward: Instead of proclaiming the model to be valid, publish the strengths and weaknesses of the model. This provides users with a more accurate understanding of appropriate uses of the model, allowing them to decide when they should use the model and when they should not. It also provides documentation supporting future efforts to improve the model." }, { "code": null, "e": 21127, "s": 20507, "text": "As an example, these articles have used the example of developing regressions predicting the steady state effectiveness of heat exchangers. That model was designed to predict the steady state effectiveness when the flow rates are between 0.5 and 7.5 gal/min. It is extremely accurate within so long as the flow rate is identical on either side of the device. The models do not address flow rates out side of that range, or situations with differing flow rates on either side of the device. Also, it is designed specifically for steady state effectiveness and should not be used for predictions in transient simulations." }, { "code": null, "e": 21331, "s": 21127, "text": "This series of four articles has introduced you to all of the concepts necessary to write programs that automatically analyze your scientific data sets for you. You’ve learned about the following topics:" }, { "code": null, "e": 21383, "s": 21331, "text": "Some possible benefits of automating data analysis," }, { "code": null, "e": 21438, "s": 21383, "text": "The structure of programs that automate data analysis," }, { "code": null, "e": 21487, "s": 21438, "text": "How to structure data sets to enable automation," }, { "code": null, "e": 21537, "s": 21487, "text": "How to identify the conditions of each data test," }, { "code": null, "e": 21562, "s": 21537, "text": "How to split data files," }, { "code": null, "e": 21620, "s": 21562, "text": "How to write a for loop iterating through each data file," }, { "code": null, "e": 21658, "s": 21620, "text": "How to analyze the data in each file," }, { "code": null, "e": 21705, "s": 21658, "text": "How to check the data in each file for errors," }, { "code": null, "e": 21792, "s": 21705, "text": "How to store the data from each file so it’s ready for use generating regressions, and" }, { "code": null, "e": 21874, "s": 21792, "text": "How to generate, validate, and document the final regressions from your data set." } ]
How to Develop Optimization Models in Python | by Idil Ismiguzel | Towards Data Science
Determining how to design and operate a system in the best way, under the given circumstances such as allocation of scarce resources, usually requires leveraging on quantitative methods in decision making. Mathematical optimization is one of the main approaches for deciding the best action for a given situation. It consists of maximizing or minimizing the real function by systematically choosing input values from an allowed set and computing the value of the objective function. Some use cases for optimization are: Product planning and inventory control: planning the issue of orders while avoiding stock-out and exceeding capacity limitations Routing decisions: process of determining the most cost-effective route Packing problems: deciding the packing method without exceeding the capacity while minimizing the free space Resource planning: determining the amount of each item and resource needed Scheduling: such as scheduling the shifts of workers Location problems: placement of facilities to minimize transportation costs while ensuring the requested demand. In this article, I will demonstrate solutions to some optimization problems, leveraging on linear programming, and using PuLP library in Python. Linear programming deals with the problem of optimizing a linear objective function (such as maximum profit or minimum cost) subject to linear equality/inequality constraints on the decision variables. There are three components of linear programming: Decision variable: variables that can be directly controlled by the decision-maker.Objective function: the linear function that mathematically expresses the quantities to be maximized or minimized.Constraints: mathematical expression of equalities or inequalities representing the restrictions on the decision variables. Decision variable: variables that can be directly controlled by the decision-maker. Objective function: the linear function that mathematically expresses the quantities to be maximized or minimized. Constraints: mathematical expression of equalities or inequalities representing the restrictions on the decision variables. Let’s look at some examples. You can check out the Jupyter Notebook on my GitHub for the full analysis. A bakery makes cakes and pies every day. It can make a total of 30 items in one day, which at least must be 5 cakes and 10 pies for its planned customers. The profit on each cake is $1.5 and the profit on each pie is $2.00. How many should be made to maximize the profit? This example is simple, meaning it doesn’t require us to use PuLP or any functionalities of Python, yet it is a good exercise to understand the concepts. The objective function of the question is to maximize the profit: max Profit = 1.5*C + 2*P Subject to following constraints: C >= 5, P >= 10, C + P <= 30 As can be seen in the graph below, if we draw the constraints: a vertical line at (5, 0), a horizontal line at (0,10) and a slanting line passes from (0,30) and (30,0) to fulfill the requirements, we can find the vertices of the polygonal region that are (5,10), (20,10) and (5,25). According to our objective function Profit = 1.5*C + 2*P we can get the maximum profit of $57.5 with (5,25) vertex, which means the bakery should make 5 cakes and 25 pies. But not all the problems are as easy as this one and if we want to calculate each constraint of each decision variable for complex problems we might have serious timing problems. 😅 Let’s look at another example: A bakery makes cakes and pies every day of a month. There is: 1 oven, 2 bakers, 1 packaging packer that works only 22 days of the month. The cake requires to use the oven for 1 day and the pie requires 0.5 day. Each baker needs to work for cake 0.5 days and pie 2 days. Packer needs to work for cake 1 day and pie 0.5 days. The profit on each cake is $15 and the profit on each pie is $12. How many should be made to maximize the profit under given conditions? To solve this problem using PuLP, we will follow the common modeling process. Inside LpProblem() method we define the problem name and sense of objective function which can either ‘LpMaximize’ or ‘LpMinimize’. import pulpfrom pulp import *model = LpProblem('Maximize Bakery Profits', sense= LpMaximize) Inside LpVariable() method we define a name for the variable, values for lower and upper bound, and category type which can be ‘Integer’, ‘Binary’, or ‘Continuous’. Since we want an integer value for the number of cakes and pies, we choose integer. C = LpVariable('C', lowBound=0, upBound=None, cat='Integer')P = LpVariable('P', lowBound=0, upBound=None, cat='Integer') Add the objective function to the initialized model using+= model += 15 * C + 12 * P Add the constraints to the initialized model using += Notice that constraints are different from the objective function because they have (in)equalities on the right-hand side. model += 1 * C + 0.5 * P <= 30model += 0.5 * C + 2 * P <= 60model += 1 * C + 0.5 * P <= 22 Call solve method model.solve() Check the status of the solution LpStatus[model.status] Print optimized decision variables C.varValue P.varValue Print optimized objective function value(model.objective)) #Results1OptimalProduce 8.0 Cake Produce 28.0 Pie 456.0 A post office is looking to hire postman, with the requirements to work 5 consecutive days and then 2 days off. The objective is to hire the minimum number of workers and the estimated number of postmen needed for each day is Monday: 25, Tuesday: 32, Wednesday: 22, Thursday: 18, Friday: 24, Saturday: 12, Sunday: 14. What would be the minimum number of postmen to hire? To solve this problem, we need to write down the constraints in terms of the number of workers we need to start working on each day such as; x_0 is the number of workers starting to work on Monday, x_1 is the number of workers starting to work on Tuesday, etc. By doing so, we can store x_0 from Monday to Friday and x_1 from Tuesday to Saturday since they need to work 5 consecutive days. #Initialize modelmodel = LpProblem("Minimize Number of Workers", LpMinimize)#Define decision variablesdays = list(range(7))x = LpVariable.dicts('workers_', days, lowBound=0, upbound=None, cat='Integer')#Define modelmodel += lpSum([x[i] for i in days])# Define constraintsmodel += x[0] + x[3] + x[4] + x[5] + x[6] >= 25model += x[0] + x[1] + x[4] + x[5] + x[6] >= 32model += x[0] + x[1] + x[2] + x[5] + x[6] >= 22model += x[0] + x[1] + x[2] + x[3] + x[6] >= 18model += x[0] + x[1] + x[2] + x[3] + x[4] >= 24model += x[1] + x[2] + x[3] + x[4] + x[5] >= 12model += x[2] + x[3] + x[4] + x[5] + x[6] >= 14# Solve modelmodel.solve()#Print model statusprint('Status:', LpStatus[model.status])#Print solution variablesfor variable in model.variables(): print ('{} = {}'.format(variable.name, variable.varValue)) Status: Optimalworkers__0 = 7.0workers__1 = 7.0workers__2 = 0.0workers__3 = 0.0workers__4 = 10.0workers__5 = 0.0workers__6 = 8.0 As the solution suggests, we need to hire 32 postmen in total, 7 of them start working on Monday, the other 7 on Tuesday, 10 on Friday, and 8 on Sunday. Assume that you need to optimize a manufacturing company’s supply chain network across 5 selling locations to meet with demand by location at the lowest cost. You can decide the plant size in each location where the options are low capacity and high capacity. One possibility is to set up a facility in each region with an advantage of low transportation costs and a disadvantage of having production plans sized to meet local demands and not exploiting the economies of scale. Another possibility is to set up a few manufacturing plants with an advantage of economies of scale but requiring higher transportation costs. Given, you have the estimated demand for each location, variable costs of transportation from one plant to another, fixed costs of having a plant-based on its size and the production capacity based on plant size is 500 for low capacity and 1500 for high capacity. How would you solve this problem with the minimum cost? Demand column shows the estimated demand for each location Columns A to E shows the transportation cost from locations in the index to each of the locations in columns (i.e. transportation cost from plant B to plant D is 14) ‘High_C’ and ‘Low_C’ columns show the fixed cost of having high and low capacity plants in each location (i.e. having a low capacity plant at location E has $6500 fixed cost) To solve this problem, we first need to initialize our model and decision variables. There are two decision variables; Production quantity that produced in plant i and shipped to plant j (continuous variable)Capacity of the production plant (binary variable: 1 if the plant at location i of capacity s is open, 0 if closed) Production quantity that produced in plant i and shipped to plant j (continuous variable) Capacity of the production plant (binary variable: 1 if the plant at location i of capacity s is open, 0 if closed) #Initialize modelmodel = LpProblem('Facility Location Problem', LpMinimize)#Define decision variablesloc = ['A', 'B', 'C', 'D', 'E']size = ['Low_C','High_C']x = LpVariable.dicts('production_', [(i,j) for i in loc for j in loc], lowBound=0, upBound=None, cat='Continuous')y = LpVariable.dicts('plant_', [(i,s) for s in size for i in loc], lowBound=None, upBound=None, cat='Binary')#Define modelmodel += (lpSum([fix_cost.loc[i,s] * y[(i,s)] for s in size for i in loc]) + lpSum([var_cost.loc[i,j] * x[(i,j)] for i in loc for j in loc])) Constraints are: Total production needs to be equal to total demandTotal production can be smaller or equal to total production capacity Total production needs to be equal to total demand Total production can be smaller or equal to total production capacity # Define constraintsfor j in loc: model += lpSum([x[(i, j)] for i in loc]) == demand.loc[j,'Demand']for i in loc: model += lpSum([x[i, j] for j in loc]) <= lpSum([capacity.loc[i,s] * y[i,s] for s in size]) # Solvemodel.solve() Since solve() method returns 1, the solution is optimal and we can print the results. # Results for production quantities[{'prod':'{} to {}'.format(i,j), 'quantity':x[(i,j)].varValue} for i in loc for j in loc]# Results for plant capacities based on location[{'lowCap':y[(i,size[0])].varValue, 'highCap':y[(i,size[1])].varValue} for i in loc]# Objective Valueprint('Objective = ', value(model.objective)) Results: prod quantityA to A 145.4A to B 0.0A to C 0.0A to D 0.0A to E 1219.6B to A 0.0B to B 0.0B to C 0.0B to D 0.0B to E 0.0C to A 0.0C to B 84.1C to C 156.4C to D 176.8C to E 0.0D to A 0.0D to B 0.0D to C 0.0D to D 1500.0D to E 0.0E to A 0.0E to B 0.0E to C 0.0E to D 0.0E to E 1500.0 lowCap highCapA 0.0 1.0B 0.0 0.0C 1.0 0.0D 0.0 1.0E 0.0 1.0Objective = 58850.9 As can be seen from results, the model suggests to open a low capacity plant in location C, and high capacity plants in locations A, D, and E. The demand at location B is suggested to be provided by the location C. Doing so, we can achieve the minimum cost of $58850.9. Once you call the solve method model.solve() and print the status of the solution LpStatus[model.status] you can receive following outcomes. Optimal: Model and constraints worked well and the solution is feasible. You can continue by checking whether variables are in expected ranges.Infeasible: There are no feasible solutions. You can turn back and review the constraints.Unbounded: Meaning that the objective function is not bounded and it tends towards infinity. You can turn back and review the objective function.Undefined: The optimal solution may exist but may not have been found. You can consider reviewing the model.Not Solved: Status prior to solving the problem. You can consider reviewing the model. Optimal: Model and constraints worked well and the solution is feasible. You can continue by checking whether variables are in expected ranges. Infeasible: There are no feasible solutions. You can turn back and review the constraints. Unbounded: Meaning that the objective function is not bounded and it tends towards infinity. You can turn back and review the objective function. Undefined: The optimal solution may exist but may not have been found. You can consider reviewing the model. Not Solved: Status prior to solving the problem. You can consider reviewing the model. If the model status is optimal, you can continue and check if the results are in expected ranges. If yes, then the model is completed. You can check the dual value if you are seeking to answer some business questions such as what would be the cost increase if the demand increases one unit, in other words, how much profit is needed to cover such a cost increase. You can also check the slack of each constraint if you are seeking to understand whether the constraints are binding, and if not which of them has room in production capacity for the future demand increase. # Print Dual Value and Slack[{'name':name, 'dual value':c.pi, 'slack': c.slack}for name, c in model.constraints.items()]name dual value slackC1 8.0 -0.0C2 13.0 -0.0C3 8.0 -0.0C4 10.0 -0.0C5 12.0 -0.0C6 0.0 135.0C7 -7.0 -0.0C8 0.0 82.7C9 -7.0 -0.0C10 -6.0 -0.0 The dual value represents the amount of the objective function changes for each unit change in the right-hand side of the constraints. Therefore if the demand in location A increases 1 unit, this will increase the overall cost $8, if the demand in location B increases 1 unit, this will increase the overall cost $13, etc. The slack of each constraint represents the amount of resource that is unused for each constraint. If the slack is equal to 0, then the constraint is binding, if the slack value is greater than 0 then it means its not binding. In the example, we can see that constraints C6 and C8 are not binding, meaning that they do not use their production capacities in full. In location A there is room to increase production by 135, and in location C there is room to increase production by 82.7. I hope you enjoyed following the examples and found the article useful in your journey towards linear programming. If you liked this article, you can read my other articles here and follow me on Medium. Let me know if you have any questions or suggestions.✨ Enjoy this article? Become a member for more!
[ { "code": null, "e": 655, "s": 172, "text": "Determining how to design and operate a system in the best way, under the given circumstances such as allocation of scarce resources, usually requires leveraging on quantitative methods in decision making. Mathematical optimization is one of the main approaches for deciding the best action for a given situation. It consists of maximizing or minimizing the real function by systematically choosing input values from an allowed set and computing the value of the objective function." }, { "code": null, "e": 692, "s": 655, "text": "Some use cases for optimization are:" }, { "code": null, "e": 821, "s": 692, "text": "Product planning and inventory control: planning the issue of orders while avoiding stock-out and exceeding capacity limitations" }, { "code": null, "e": 893, "s": 821, "text": "Routing decisions: process of determining the most cost-effective route" }, { "code": null, "e": 1002, "s": 893, "text": "Packing problems: deciding the packing method without exceeding the capacity while minimizing the free space" }, { "code": null, "e": 1077, "s": 1002, "text": "Resource planning: determining the amount of each item and resource needed" }, { "code": null, "e": 1130, "s": 1077, "text": "Scheduling: such as scheduling the shifts of workers" }, { "code": null, "e": 1243, "s": 1130, "text": "Location problems: placement of facilities to minimize transportation costs while ensuring the requested demand." }, { "code": null, "e": 1388, "s": 1243, "text": "In this article, I will demonstrate solutions to some optimization problems, leveraging on linear programming, and using PuLP library in Python." }, { "code": null, "e": 1590, "s": 1388, "text": "Linear programming deals with the problem of optimizing a linear objective function (such as maximum profit or minimum cost) subject to linear equality/inequality constraints on the decision variables." }, { "code": null, "e": 1640, "s": 1590, "text": "There are three components of linear programming:" }, { "code": null, "e": 1961, "s": 1640, "text": "Decision variable: variables that can be directly controlled by the decision-maker.Objective function: the linear function that mathematically expresses the quantities to be maximized or minimized.Constraints: mathematical expression of equalities or inequalities representing the restrictions on the decision variables." }, { "code": null, "e": 2045, "s": 1961, "text": "Decision variable: variables that can be directly controlled by the decision-maker." }, { "code": null, "e": 2160, "s": 2045, "text": "Objective function: the linear function that mathematically expresses the quantities to be maximized or minimized." }, { "code": null, "e": 2284, "s": 2160, "text": "Constraints: mathematical expression of equalities or inequalities representing the restrictions on the decision variables." }, { "code": null, "e": 2388, "s": 2284, "text": "Let’s look at some examples. You can check out the Jupyter Notebook on my GitHub for the full analysis." }, { "code": null, "e": 2660, "s": 2388, "text": "A bakery makes cakes and pies every day. It can make a total of 30 items in one day, which at least must be 5 cakes and 10 pies for its planned customers. The profit on each cake is $1.5 and the profit on each pie is $2.00. How many should be made to maximize the profit?" }, { "code": null, "e": 2814, "s": 2660, "text": "This example is simple, meaning it doesn’t require us to use PuLP or any functionalities of Python, yet it is a good exercise to understand the concepts." }, { "code": null, "e": 2880, "s": 2814, "text": "The objective function of the question is to maximize the profit:" }, { "code": null, "e": 2905, "s": 2880, "text": "max Profit = 1.5*C + 2*P" }, { "code": null, "e": 2939, "s": 2905, "text": "Subject to following constraints:" }, { "code": null, "e": 2956, "s": 2939, "text": "C >= 5, P >= 10," }, { "code": null, "e": 2968, "s": 2956, "text": "C + P <= 30" }, { "code": null, "e": 3251, "s": 2968, "text": "As can be seen in the graph below, if we draw the constraints: a vertical line at (5, 0), a horizontal line at (0,10) and a slanting line passes from (0,30) and (30,0) to fulfill the requirements, we can find the vertices of the polygonal region that are (5,10), (20,10) and (5,25)." }, { "code": null, "e": 3605, "s": 3251, "text": "According to our objective function Profit = 1.5*C + 2*P we can get the maximum profit of $57.5 with (5,25) vertex, which means the bakery should make 5 cakes and 25 pies. But not all the problems are as easy as this one and if we want to calculate each constraint of each decision variable for complex problems we might have serious timing problems. 😅" }, { "code": null, "e": 3636, "s": 3605, "text": "Let’s look at another example:" }, { "code": null, "e": 4097, "s": 3636, "text": "A bakery makes cakes and pies every day of a month. There is: 1 oven, 2 bakers, 1 packaging packer that works only 22 days of the month. The cake requires to use the oven for 1 day and the pie requires 0.5 day. Each baker needs to work for cake 0.5 days and pie 2 days. Packer needs to work for cake 1 day and pie 0.5 days. The profit on each cake is $15 and the profit on each pie is $12. How many should be made to maximize the profit under given conditions?" }, { "code": null, "e": 4175, "s": 4097, "text": "To solve this problem using PuLP, we will follow the common modeling process." }, { "code": null, "e": 4307, "s": 4175, "text": "Inside LpProblem() method we define the problem name and sense of objective function which can either ‘LpMaximize’ or ‘LpMinimize’." }, { "code": null, "e": 4400, "s": 4307, "text": "import pulpfrom pulp import *model = LpProblem('Maximize Bakery Profits', sense= LpMaximize)" }, { "code": null, "e": 4649, "s": 4400, "text": "Inside LpVariable() method we define a name for the variable, values for lower and upper bound, and category type which can be ‘Integer’, ‘Binary’, or ‘Continuous’. Since we want an integer value for the number of cakes and pies, we choose integer." }, { "code": null, "e": 4770, "s": 4649, "text": "C = LpVariable('C', lowBound=0, upBound=None, cat='Integer')P = LpVariable('P', lowBound=0, upBound=None, cat='Integer')" }, { "code": null, "e": 4830, "s": 4770, "text": "Add the objective function to the initialized model using+=" }, { "code": null, "e": 4855, "s": 4830, "text": "model += 15 * C + 12 * P" }, { "code": null, "e": 5032, "s": 4855, "text": "Add the constraints to the initialized model using += Notice that constraints are different from the objective function because they have (in)equalities on the right-hand side." }, { "code": null, "e": 5123, "s": 5032, "text": "model += 1 * C + 0.5 * P <= 30model += 0.5 * C + 2 * P <= 60model += 1 * C + 0.5 * P <= 22" }, { "code": null, "e": 5155, "s": 5123, "text": "Call solve method model.solve()" }, { "code": null, "e": 5211, "s": 5155, "text": "Check the status of the solution LpStatus[model.status]" }, { "code": null, "e": 5268, "s": 5211, "text": "Print optimized decision variables C.varValue P.varValue" }, { "code": null, "e": 5327, "s": 5268, "text": "Print optimized objective function value(model.objective))" }, { "code": null, "e": 5383, "s": 5327, "text": "#Results1OptimalProduce 8.0 Cake Produce 28.0 Pie 456.0" }, { "code": null, "e": 5754, "s": 5383, "text": "A post office is looking to hire postman, with the requirements to work 5 consecutive days and then 2 days off. The objective is to hire the minimum number of workers and the estimated number of postmen needed for each day is Monday: 25, Tuesday: 32, Wednesday: 22, Thursday: 18, Friday: 24, Saturday: 12, Sunday: 14. What would be the minimum number of postmen to hire?" }, { "code": null, "e": 6144, "s": 5754, "text": "To solve this problem, we need to write down the constraints in terms of the number of workers we need to start working on each day such as; x_0 is the number of workers starting to work on Monday, x_1 is the number of workers starting to work on Tuesday, etc. By doing so, we can store x_0 from Monday to Friday and x_1 from Tuesday to Saturday since they need to work 5 consecutive days." }, { "code": null, "e": 6951, "s": 6144, "text": "#Initialize modelmodel = LpProblem(\"Minimize Number of Workers\", LpMinimize)#Define decision variablesdays = list(range(7))x = LpVariable.dicts('workers_', days, lowBound=0, upbound=None, cat='Integer')#Define modelmodel += lpSum([x[i] for i in days])# Define constraintsmodel += x[0] + x[3] + x[4] + x[5] + x[6] >= 25model += x[0] + x[1] + x[4] + x[5] + x[6] >= 32model += x[0] + x[1] + x[2] + x[5] + x[6] >= 22model += x[0] + x[1] + x[2] + x[3] + x[6] >= 18model += x[0] + x[1] + x[2] + x[3] + x[4] >= 24model += x[1] + x[2] + x[3] + x[4] + x[5] >= 12model += x[2] + x[3] + x[4] + x[5] + x[6] >= 14# Solve modelmodel.solve()#Print model statusprint('Status:', LpStatus[model.status])#Print solution variablesfor variable in model.variables(): print ('{} = {}'.format(variable.name, variable.varValue))" }, { "code": null, "e": 7080, "s": 6951, "text": "Status: Optimalworkers__0 = 7.0workers__1 = 7.0workers__2 = 0.0workers__3 = 0.0workers__4 = 10.0workers__5 = 0.0workers__6 = 8.0" }, { "code": null, "e": 7233, "s": 7080, "text": "As the solution suggests, we need to hire 32 postmen in total, 7 of them start working on Monday, the other 7 on Tuesday, 10 on Friday, and 8 on Sunday." }, { "code": null, "e": 8174, "s": 7233, "text": "Assume that you need to optimize a manufacturing company’s supply chain network across 5 selling locations to meet with demand by location at the lowest cost. You can decide the plant size in each location where the options are low capacity and high capacity. One possibility is to set up a facility in each region with an advantage of low transportation costs and a disadvantage of having production plans sized to meet local demands and not exploiting the economies of scale. Another possibility is to set up a few manufacturing plants with an advantage of economies of scale but requiring higher transportation costs. Given, you have the estimated demand for each location, variable costs of transportation from one plant to another, fixed costs of having a plant-based on its size and the production capacity based on plant size is 500 for low capacity and 1500 for high capacity. How would you solve this problem with the minimum cost?" }, { "code": null, "e": 8233, "s": 8174, "text": "Demand column shows the estimated demand for each location" }, { "code": null, "e": 8399, "s": 8233, "text": "Columns A to E shows the transportation cost from locations in the index to each of the locations in columns (i.e. transportation cost from plant B to plant D is 14)" }, { "code": null, "e": 8574, "s": 8399, "text": "‘High_C’ and ‘Low_C’ columns show the fixed cost of having high and low capacity plants in each location (i.e. having a low capacity plant at location E has $6500 fixed cost)" }, { "code": null, "e": 8693, "s": 8574, "text": "To solve this problem, we first need to initialize our model and decision variables. There are two decision variables;" }, { "code": null, "e": 8898, "s": 8693, "text": "Production quantity that produced in plant i and shipped to plant j (continuous variable)Capacity of the production plant (binary variable: 1 if the plant at location i of capacity s is open, 0 if closed)" }, { "code": null, "e": 8988, "s": 8898, "text": "Production quantity that produced in plant i and shipped to plant j (continuous variable)" }, { "code": null, "e": 9104, "s": 8988, "text": "Capacity of the production plant (binary variable: 1 if the plant at location i of capacity s is open, 0 if closed)" }, { "code": null, "e": 9639, "s": 9104, "text": "#Initialize modelmodel = LpProblem('Facility Location Problem', LpMinimize)#Define decision variablesloc = ['A', 'B', 'C', 'D', 'E']size = ['Low_C','High_C']x = LpVariable.dicts('production_', [(i,j) for i in loc for j in loc], lowBound=0, upBound=None, cat='Continuous')y = LpVariable.dicts('plant_', [(i,s) for s in size for i in loc], lowBound=None, upBound=None, cat='Binary')#Define modelmodel += (lpSum([fix_cost.loc[i,s] * y[(i,s)] for s in size for i in loc]) + lpSum([var_cost.loc[i,j] * x[(i,j)] for i in loc for j in loc]))" }, { "code": null, "e": 9656, "s": 9639, "text": "Constraints are:" }, { "code": null, "e": 9776, "s": 9656, "text": "Total production needs to be equal to total demandTotal production can be smaller or equal to total production capacity" }, { "code": null, "e": 9827, "s": 9776, "text": "Total production needs to be equal to total demand" }, { "code": null, "e": 9897, "s": 9827, "text": "Total production can be smaller or equal to total production capacity" }, { "code": null, "e": 10133, "s": 9897, "text": "# Define constraintsfor j in loc: model += lpSum([x[(i, j)] for i in loc]) == demand.loc[j,'Demand']for i in loc: model += lpSum([x[i, j] for j in loc]) <= lpSum([capacity.loc[i,s] * y[i,s] for s in size]) # Solvemodel.solve()" }, { "code": null, "e": 10219, "s": 10133, "text": "Since solve() method returns 1, the solution is optimal and we can print the results." }, { "code": null, "e": 10547, "s": 10219, "text": "# Results for production quantities[{'prod':'{} to {}'.format(i,j), 'quantity':x[(i,j)].varValue} for i in loc for j in loc]# Results for plant capacities based on location[{'lowCap':y[(i,size[0])].varValue, 'highCap':y[(i,size[1])].varValue} for i in loc]# Objective Valueprint('Objective = ', value(model.objective))" }, { "code": null, "e": 10556, "s": 10547, "text": "Results:" }, { "code": null, "e": 11101, "s": 10556, "text": "prod quantityA to A 145.4A to B 0.0A to C 0.0A to D 0.0A to E 1219.6B to A 0.0B to B 0.0B to C 0.0B to D 0.0B to E 0.0C to A 0.0C to B 84.1C to C 156.4C to D 176.8C to E 0.0D to A 0.0D to B 0.0D to C 0.0D to D 1500.0D to E 0.0E to A 0.0E to B 0.0E to C 0.0E to D 0.0E to E 1500.0 lowCap highCapA 0.0 1.0B 0.0 0.0C 1.0 0.0D 0.0 1.0E 0.0 1.0Objective = 58850.9" }, { "code": null, "e": 11371, "s": 11101, "text": "As can be seen from results, the model suggests to open a low capacity plant in location C, and high capacity plants in locations A, D, and E. The demand at location B is suggested to be provided by the location C. Doing so, we can achieve the minimum cost of $58850.9." }, { "code": null, "e": 11512, "s": 11371, "text": "Once you call the solve method model.solve() and print the status of the solution LpStatus[model.status] you can receive following outcomes." }, { "code": null, "e": 12085, "s": 11512, "text": "Optimal: Model and constraints worked well and the solution is feasible. You can continue by checking whether variables are in expected ranges.Infeasible: There are no feasible solutions. You can turn back and review the constraints.Unbounded: Meaning that the objective function is not bounded and it tends towards infinity. You can turn back and review the objective function.Undefined: The optimal solution may exist but may not have been found. You can consider reviewing the model.Not Solved: Status prior to solving the problem. You can consider reviewing the model." }, { "code": null, "e": 12229, "s": 12085, "text": "Optimal: Model and constraints worked well and the solution is feasible. You can continue by checking whether variables are in expected ranges." }, { "code": null, "e": 12320, "s": 12229, "text": "Infeasible: There are no feasible solutions. You can turn back and review the constraints." }, { "code": null, "e": 12466, "s": 12320, "text": "Unbounded: Meaning that the objective function is not bounded and it tends towards infinity. You can turn back and review the objective function." }, { "code": null, "e": 12575, "s": 12466, "text": "Undefined: The optimal solution may exist but may not have been found. You can consider reviewing the model." }, { "code": null, "e": 12662, "s": 12575, "text": "Not Solved: Status prior to solving the problem. You can consider reviewing the model." }, { "code": null, "e": 12797, "s": 12662, "text": "If the model status is optimal, you can continue and check if the results are in expected ranges. If yes, then the model is completed." }, { "code": null, "e": 13233, "s": 12797, "text": "You can check the dual value if you are seeking to answer some business questions such as what would be the cost increase if the demand increases one unit, in other words, how much profit is needed to cover such a cost increase. You can also check the slack of each constraint if you are seeking to understand whether the constraints are binding, and if not which of them has room in production capacity for the future demand increase." }, { "code": null, "e": 13598, "s": 13233, "text": "# Print Dual Value and Slack[{'name':name, 'dual value':c.pi, 'slack': c.slack}for name, c in model.constraints.items()]name dual value slackC1 8.0 -0.0C2 13.0 -0.0C3 8.0 -0.0C4 10.0 -0.0C5 12.0 -0.0C6 0.0 135.0C7 -7.0 -0.0C8 0.0 82.7C9 -7.0 -0.0C10 -6.0 -0.0" }, { "code": null, "e": 13921, "s": 13598, "text": "The dual value represents the amount of the objective function changes for each unit change in the right-hand side of the constraints. Therefore if the demand in location A increases 1 unit, this will increase the overall cost $8, if the demand in location B increases 1 unit, this will increase the overall cost $13, etc." }, { "code": null, "e": 14408, "s": 13921, "text": "The slack of each constraint represents the amount of resource that is unused for each constraint. If the slack is equal to 0, then the constraint is binding, if the slack value is greater than 0 then it means its not binding. In the example, we can see that constraints C6 and C8 are not binding, meaning that they do not use their production capacities in full. In location A there is room to increase production by 135, and in location C there is room to increase production by 82.7." }, { "code": null, "e": 14523, "s": 14408, "text": "I hope you enjoyed following the examples and found the article useful in your journey towards linear programming." }, { "code": null, "e": 14666, "s": 14523, "text": "If you liked this article, you can read my other articles here and follow me on Medium. Let me know if you have any questions or suggestions.✨" } ]
Bell Numbers | Practice | GeeksforGeeks
Given a set of n elements, find number of ways of partitioning it. Example 1: Input: N = 2 Output: 2 Explanation: Let the set be {1, 2}: { {1}, {2} } { {1, 2} } Example 2: Input: N = 3 Output: 5 Your Task: You don't need to read input or print anything. Your task is to complete the function bellNumber() which takes the integer N as input parameters and returns the number of ways of partitioning n elements. Since the value can be quite large print the value modulo 109+7. Expected Time Complexity: O(N^2) Expected Auxiliary Space: O(N^2) Constraints: 1 ≤ N ≤ 1000 0 Jyoti9 months ago Jyoti int bellNumber(int n) { // Code Here int dp[n][n]; dp[0][0]=1; int k=1e9+7; for(int i=1;i<n;i++)<br> { dp[i][0]=dp[i-1][i-1]; for(int j=1;j<=i;j++) { dp[i][j]=(dp[i][j-1]+dp[i-1][j-1])%k; } } return dp[n-1][n-1]; } 0 Rohith Vazhathody9 months ago Rohith Vazhathody class Solution{ int bellNumber(int n){ // Code Here int mod = (int) (1e9 + 7); long [][] dp = new long [n + 1][n + 1]; dp[0][0] = 1; for (int i=1; i<=n; i++) { dp[i][0] = dp[i - 1][i - 1]; // previous row, previous col for (int j=1; j<=i; j++) { dp[i][j] = (dp[i][j - 1] + dp[i - 1][j - 1]) % mod; } } return (int)(dp[n - 1][n - 1] % mod); } }/*11 22 3. 55 7. 10 1515 20 27 37 52.........This is bell traingle*/ 0 Chandru9 months ago Chandru C++ Correct Answer:✅✅✅ int bellNumber(int n) { int mod = 1e9 + 7; int dp[n+1][n+1]; dp[0][0]=1; for(int i=1;i<=n;i++) { dp[i][0] = dp[i-1][i-1]; for(int j=1;j<=i;j++) { dp[i][j] = (dp[i-1][j-1]+dp[i][j-1])%mod; } } return dp[n-1][n-1]; } 0 ashutoshvimal229 months ago ashutoshvimal22 If you are not able to understand the output then watch this video https://www.youtube.com/wat... 0 i_am_chitti9 months ago i_am_chitti int bellNumber(int n) { // Code Here long long dp[n+1][n+1]; dp[1][1]=1; long long MOD = 1000000007; for(int i=2;i<=n;i++) { dp[i][1]=dp[i-1][i-1]; for(int j=2;j<=i;j++) { dp[i][j] = ((dp[i][j-1]%MOD)+(dp[i-1][j-1]%MOD))%MOD; } } return dp[n][n]; } 0 Saranya Maity9 months ago Saranya Maity how its an easy question! Hints save the day ! Go and understand Bell triangle given in hints !rest apply dp for the rest :/ One thing that's unacceptable is that how a single variable problem turn into a 2D DP problem which is solvable by Bell Triangle and how the DP for the bell triangle assuring partitioning OR how the intuition came ? Nothing is clear , 0 Sakshi Agarwal9 months ago Sakshi Agarwal class Solution{ public: int padovanSequence(int n) { //code here int dp[n+1]; dp[0]=dp[1]=dp[2]=1; for(int i=3;i<=n;i++){ dp[i] = (dp[i-2]+dp[i-3])%1000000007; } return dp[n]; } }; 0 AnimeCringeLord11 months ago AnimeCringeLord Python3 Sol using Bell Triangle https://uploads.disquscdn.c... 0 Ankit Rai2 years ago Ankit Rai #include <bits stdc++.h="">using namespace std; int kset(int n){ long int mod=1000000007; long int sum=0; int a[n+1][n+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=i;j++){ if(j==1 || i==j) a[i][j]=1; else a[i][j]=((j*a[i-1][j])%mod + (a[i-1][j-1])%mod)%mod; } } for(int j=1;j<=n;j++){ sum+=a[n][j]; //sum=sum%mod; } return sum;}int main() {int t;cin>>t;while(t--){ int n; cin>>n; cout<<kset(n)<<endl; }="" return="" 0;="" }="" what="" is="" wrong="" in="" this="" code?(wrong="" answer="" at="" 916)=""> 0 RAJIV RAM S2 years ago RAJIV RAM S #include<bits stdc++.h="">using namespace std;int bellDP(int num){ int arr[num+1][num+1]; arr[0][0]=1; arr[0][1]=2; for(int i=1;i<=num;i++) { arr[i][0]=(arr[i-1][i-1])%(1000000007); for(int j=1;j<=i;j++) { arr[i][j]=(arr[i-1][j-1]+arr[i][j-1])%(1000000007);; } } return arr[num][0];} int main() { int t; cin>>t; while(t--) { int n; cin>>n; int res = bellDP(n); cout<<res<<endl; }="" 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": 293, "s": 226, "text": "Given a set of n elements, find number of ways of partitioning it." }, { "code": null, "e": 306, "s": 295, "text": "Example 1:" }, { "code": null, "e": 390, "s": 306, "text": "Input:\nN = 2\nOutput: 2\nExplanation:\nLet the set be \n{1, 2}:\n{ {1}, {2} } { {1, 2} }" }, { "code": null, "e": 403, "s": 392, "text": "Example 2:" }, { "code": null, "e": 427, "s": 403, "text": "Input:\nN = 3\nOutput: 5\n" }, { "code": null, "e": 777, "s": 427, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function bellNumber() which takes the integer N as input parameters and returns the number of ways of partitioning n elements. Since the value can be quite large print the value modulo 109+7.\n\nExpected Time Complexity: O(N^2)\nExpected Auxiliary Space: O(N^2)" }, { "code": null, "e": 792, "s": 779, "text": "Constraints:" }, { "code": null, "e": 805, "s": 792, "text": "1 ≤ N ≤ 1000" }, { "code": null, "e": 807, "s": 805, "text": "0" }, { "code": null, "e": 825, "s": 807, "text": "Jyoti9 months ago" }, { "code": null, "e": 831, "s": 825, "text": "Jyoti" }, { "code": null, "e": 1154, "s": 831, "text": "int bellNumber(int n) { // Code Here int dp[n][n]; dp[0][0]=1; int k=1e9+7; for(int i=1;i<n;i++)<br> { dp[i][0]=dp[i-1][i-1]; for(int j=1;j<=i;j++) { dp[i][j]=(dp[i][j-1]+dp[i-1][j-1])%k; } } return dp[n-1][n-1]; }" }, { "code": null, "e": 1156, "s": 1154, "text": "0" }, { "code": null, "e": 1186, "s": 1156, "text": "Rohith Vazhathody9 months ago" }, { "code": null, "e": 1204, "s": 1186, "text": "Rohith Vazhathody" }, { "code": null, "e": 1729, "s": 1204, "text": "class Solution{ int bellNumber(int n){ // Code Here int mod = (int) (1e9 + 7); long [][] dp = new long [n + 1][n + 1]; dp[0][0] = 1; for (int i=1; i<=n; i++) { dp[i][0] = dp[i - 1][i - 1]; // previous row, previous col for (int j=1; j<=i; j++) { dp[i][j] = (dp[i][j - 1] + dp[i - 1][j - 1]) % mod; } } return (int)(dp[n - 1][n - 1] % mod); } }/*11 22 3. 55 7. 10 1515 20 27 37 52.........This is bell traingle*/" }, { "code": null, "e": 1731, "s": 1729, "text": "0" }, { "code": null, "e": 1751, "s": 1731, "text": "Chandru9 months ago" }, { "code": null, "e": 1759, "s": 1751, "text": "Chandru" }, { "code": null, "e": 1782, "s": 1759, "text": "C++ Correct Answer:✅✅✅" }, { "code": null, "e": 2099, "s": 1782, "text": "int bellNumber(int n) { int mod = 1e9 + 7; int dp[n+1][n+1]; dp[0][0]=1; for(int i=1;i<=n;i++) { dp[i][0] = dp[i-1][i-1]; for(int j=1;j<=i;j++) { dp[i][j] = (dp[i-1][j-1]+dp[i][j-1])%mod; } } return dp[n-1][n-1]; }" }, { "code": null, "e": 2101, "s": 2099, "text": "0" }, { "code": null, "e": 2129, "s": 2101, "text": "ashutoshvimal229 months ago" }, { "code": null, "e": 2145, "s": 2129, "text": "ashutoshvimal22" }, { "code": null, "e": 2244, "s": 2145, "text": "If you are not able to understand the output then watch this video https://www.youtube.com/wat..." }, { "code": null, "e": 2246, "s": 2244, "text": "0" }, { "code": null, "e": 2270, "s": 2246, "text": "i_am_chitti9 months ago" }, { "code": null, "e": 2282, "s": 2270, "text": "i_am_chitti" }, { "code": null, "e": 2714, "s": 2282, "text": "int bellNumber(int n) { // Code Here long long dp[n+1][n+1]; dp[1][1]=1; long long MOD = 1000000007; for(int i=2;i<=n;i++) { dp[i][1]=dp[i-1][i-1]; for(int j=2;j<=i;j++) { dp[i][j] = ((dp[i][j-1]%MOD)+(dp[i-1][j-1]%MOD))%MOD; } } return dp[n][n]; }" }, { "code": null, "e": 2716, "s": 2714, "text": "0" }, { "code": null, "e": 2742, "s": 2716, "text": "Saranya Maity9 months ago" }, { "code": null, "e": 2756, "s": 2742, "text": "Saranya Maity" }, { "code": null, "e": 2782, "s": 2756, "text": "how its an easy question!" }, { "code": null, "e": 2881, "s": 2782, "text": "Hints save the day ! Go and understand Bell triangle given in hints !rest apply dp for the rest :/" }, { "code": null, "e": 3116, "s": 2881, "text": "One thing that's unacceptable is that how a single variable problem turn into a 2D DP problem which is solvable by Bell Triangle and how the DP for the bell triangle assuring partitioning OR how the intuition came ? Nothing is clear ," }, { "code": null, "e": 3118, "s": 3116, "text": "0" }, { "code": null, "e": 3145, "s": 3118, "text": "Sakshi Agarwal9 months ago" }, { "code": null, "e": 3160, "s": 3145, "text": "Sakshi Agarwal" }, { "code": null, "e": 3400, "s": 3160, "text": "class Solution{ public: int padovanSequence(int n) { //code here int dp[n+1]; dp[0]=dp[1]=dp[2]=1; for(int i=3;i<=n;i++){ dp[i] = (dp[i-2]+dp[i-3])%1000000007; } return dp[n]; } };" }, { "code": null, "e": 3402, "s": 3400, "text": "0" }, { "code": null, "e": 3431, "s": 3402, "text": "AnimeCringeLord11 months ago" }, { "code": null, "e": 3447, "s": 3431, "text": "AnimeCringeLord" }, { "code": null, "e": 3479, "s": 3447, "text": "Python3 Sol using Bell Triangle" }, { "code": null, "e": 3510, "s": 3479, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 3512, "s": 3510, "text": "0" }, { "code": null, "e": 3533, "s": 3512, "text": "Ankit Rai2 years ago" }, { "code": null, "e": 3543, "s": 3533, "text": "Ankit Rai" }, { "code": null, "e": 3591, "s": 3543, "text": "#include <bits stdc++.h=\"\">using namespace std;" }, { "code": null, "e": 4157, "s": 3591, "text": "int kset(int n){ long int mod=1000000007; long int sum=0; int a[n+1][n+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=i;j++){ if(j==1 || i==j) a[i][j]=1; else a[i][j]=((j*a[i-1][j])%mod + (a[i-1][j-1])%mod)%mod; } } for(int j=1;j<=n;j++){ sum+=a[n][j]; //sum=sum%mod; } return sum;}int main() {int t;cin>>t;while(t--){ int n; cin>>n; cout<<kset(n)<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\" what=\"\" is=\"\" wrong=\"\" in=\"\" this=\"\" code?(wrong=\"\" answer=\"\" at=\"\" 916)=\"\">" }, { "code": null, "e": 4159, "s": 4157, "text": "0" }, { "code": null, "e": 4182, "s": 4159, "text": "RAJIV RAM S2 years ago" }, { "code": null, "e": 4194, "s": 4182, "text": "RAJIV RAM S" }, { "code": null, "e": 4538, "s": 4194, "text": "#include<bits stdc++.h=\"\">using namespace std;int bellDP(int num){ int arr[num+1][num+1]; arr[0][0]=1; arr[0][1]=2; for(int i=1;i<=num;i++) { arr[i][0]=(arr[i-1][i-1])%(1000000007); for(int j=1;j<=i;j++) { arr[i][j]=(arr[i-1][j-1]+arr[i][j-1])%(1000000007);; } } return arr[num][0];}" }, { "code": null, "e": 4708, "s": 4538, "text": "int main() { int t; cin>>t; while(t--) { int n; cin>>n; int res = bellDP(n); cout<<res<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 4854, "s": 4708, "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": 4890, "s": 4854, "text": " Login to access your submissions. " }, { "code": null, "e": 4900, "s": 4890, "text": "\nProblem\n" }, { "code": null, "e": 4910, "s": 4900, "text": "\nContest\n" }, { "code": null, "e": 4973, "s": 4910, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5121, "s": 4973, "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": 5329, "s": 5121, "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": 5435, "s": 5329, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Automate Entity Extraction of Reddit Subgroup using BERT Model | by Manmohan Singh | Towards Data Science
Stuck behind the paywall? Read this article with my Friend link here. Named-Entity recognition (NER) is a process to extract information from an Unstructured Text. Its also known as Entity Extraction. This method extracts information such as time, place, currency, organizations, medical codes, person names, etc. We can mark these extracted entities as tags to articles/documents. But, what do we achieve by extracting the entity from the text? Do these tags help us to reduce time in the article’s searching process? Tags on the articles or documents can save a lot of time by improving the search process. Tags help us to categorize text documents. It is one of the use-cases of NER. Some other use-cases of NER are listed below. 1. Categorize articles of NEWS agencies into the world, sports, fashion, entertainment, etc. category. 2. It helps with product searches on different online shopping websites. 3. Online courses can be categorized based on different relevant tags. We will use the BERT pre-trained model. Learn more about the BERT model here. BERT model will extract person name, organization, and location name from the Reddit subgroup. This article has divided into three parts. Part 1. Data collection and Data preparation Python program connects with Reddit API and fetches information from subreddit. Then we format data according to BERT model input. Part 2. Information Extraction We will extract entity information from the data prepared from the first part. Part 3. Data Analysis and Data Visualization In this part, we will analyze the information extracted from the second part via graphs and charts. Now, Let’s get started. We will be using Reddit subgroup r/Worldnews data. Reddit provides API access to fetch titles, comments, and other data related to posts. PRAW is a python library that helps us to connect with an API. Learn more about the PRAW library here. (https://praw.readthedocs.io/en/latest/). You need to create a Reddit account to access the information required from the API. These are the required API information. reddit = praw.Reddit(client_id=’my_client_id’, client_secret=’my_client_secret’, user_agent=’my user agent name’) Follow these steps mention in the article to get required API access information. Once you get access, we will fetch the title and comments from the r/Worldnews post. We will use the top weekly post of r/Worldnews. You can receive the data from a subgroup based on a different timeline and their popularity. def replies_of(top_level_comment, comment_list): if len(top_level_comment.replies) == 0: return else: for num, comment in enumerate(top_level_comment.replies): try: comment_list.append(str(comment.body)) except: continue replies_of(comment, comment_list)list_of_subreddit = [‘worldnews’]for j in list_of_subreddit: # get 10 hot posts from the MachineLearning subreddit top_posts = reddit.subreddit(j).top(‘week’, limit=1) comment_list = [] # save subreddit comments in dataframe for submission in top_posts: print(‘\n\n’) print(“Title :” , submission.title) submission_comm = reddit.submission(id=submission.id) comment_list.append(str(submission.title)) for count, top_level_comment in enumerate(submission_comm.comments): try: replies_of(top_level_comment, comment_list) except: continueprint(comment_list) This code will fetch the entire comment section of the subreddit post using recursion function. The data will be store into the comment_list variable. Data prepared in the first part is in the input format of the BERT Model. The output generated by the model has saved in different variables. The transformer python library from Hugging face will help us to access the BERT model trained by DBMDZ. BERT token consists of around 30k words in its library. If input text consists of words that do not present in its library, then the BERT token break that word into near know words. For example, the Hugging word will split into hu and ##gging. If an unrecognized word has considered as an entity, then each splitted word will be assigned to the same tags. For example, (‘Hu’, ‘I-ORG’), (‘##gging’, ‘I-ORG’). for sequence in comment_list: if len(sequence) > 512: continue tokens = tokenizer.tokenize(tokenizer.decode (tokenizer.encode(sequence))) inputs = tokenizer.encode(sequence, return_tensors=”tf”) outputs = model(inputs)[0] predictions = tf.argmax(outputs, axis=2) list_bert = [(token, label_list[prediction]) for token, prediction in zip(tokens, predictions[0].numpy())] I have limited the input sentence length to 512 due to BERT token limitation. I have combined these words and assigned their respective entity. This model is not 100% accurate. Because of it, wrong tags might get designated to some words. We will try to avoid these non-related words in our analysis. We have got three categories for analysis. These categories are location, person name, and organization. Title of the topic and entity extracted from the data. Title: Research finds that New Zealand beat Covid-19 by trusting leaders and following advice. Citizens had a high level of knowledge about coronavirus and how it spread, and compliance with basic hygiene practices and trust in authorities was at nearly 100%.{‘Location’: [‘UNITED STATES’, ‘ILLINOIS’, ‘GREECE’, ‘TAIWAN’, ‘NEW Z’, ‘ISLAND’, ‘PORTLAND’, ‘NSW’, ‘CANADA’, ‘QUEENSLAND’, ‘VIETNAM’, ‘CHRISTCHURCH’, ‘HAWAII’,’VICTORIA’, ‘UK’, ‘RUSSIA’, ‘WELLINGTON’, ‘INDIANA’, ‘CHUR’, ‘NZ CHINA’, ‘STATES’, ‘ARGENTINA’, ‘CALIFORNIA’, ‘IETNAM’, ‘TRUMPTOWN’, ‘TEXAS’, ‘FRANCE’, ‘AUS’, ‘NZ’, ‘NEW YORK’, ‘JAPAN’, ‘FLORIDA’, ‘QLD’, ‘AUCKLAND’, ‘KE’, ‘USA’, ‘THE’, ‘CHINA’, ‘ITALY’, ‘SWEDEN’, ‘JONESTOWN’, ‘MELBOURNE’, ‘AMERICA’, ‘NEW ZEALAND’, ‘IRAQ’,’US’, ‘AFGHANISTAN’, ‘AUSTRALIA’], ‘Organisation’: [‘YOUTUBE’, ‘FED’, ‘FACEBOOK’, ‘ALLPRESS’, ‘GNELL’, ‘VODAFONE’, ‘IRON’, ‘LIB’, ‘RESERVE BANK’, ‘LANEWAY’, ‘DEMS’, ‘ALJAZEERA’, ‘RVA’, ‘JACINDAS’, ‘CIA’, ‘LABOR’, ‘TREASURY’, ‘SMD’, ‘WHO’, ‘SENATE’, ‘LIBERALS’, ‘LIBERAL’, ‘IIRC’, ‘COVID’, ‘HS’, ‘PRC’, ‘NATIONAL’, ‘TIL’, ‘SHITREDDITSAYS’, ‘COM’, ‘FOX’, ‘EZZANZ’, ‘QLD’, ‘FAMILY FIRST’, ‘NATIONALS’, ‘NIN’, ‘DEFENCE FORCE’, ‘ZZAN’, ‘ACINDA’, ‘FOX NEWS’, ‘LABOUR’, ‘FEDERAL’, ‘HOUSE OF REPS’, ‘WORLDNEWS’, ‘MURDOCH’, ‘GREENS’], ‘Person Name’: [‘KEVIN’, ‘FATHE’, ‘KAREN’, ‘MACRON’, ‘WINSTON’, ‘LES’, ‘BUCKLEY’, ‘CHLÖE SWARBRICK’, ‘COLLINS’, ‘CLINTON’,’JUDITH COLLINS’, ‘TO’, ‘KYLER’, ‘ASHLEY’, ‘BILL GATES’, ‘THE P’, ‘SCOTTY’, ‘HITLER’, ‘TRUMP’, ‘RUPERT MURDOCH’, ‘GATES’, ‘HGO’, ‘WILLIAM CASEY’, ‘OAK’, ‘TOVA’,’JIM JONES’, ‘KEZZA’, ‘ENN’, ‘MERICA’, ‘ROF’, ‘BLOOMFIELD’, ‘GOD’, ‘KIF’, ‘CLIVE PALMER’, ‘DAVE GROHL’, ‘SHER’, ‘BLAIR’, ‘JACINDA ARDERN’, ‘DAD’, ‘JACINDA’, ‘WINS TON PETERS’, ‘LERON’, ‘BLOOMFIELDS’, ‘MURDOCH’]} Here are my observations. 1. New Zealand’s location got many mentions in comments. This location name is also mention in the title. Reddit users may prefer a short form of the country name than full form. For example, a short form of countries such as the United States, New Zealand, and the United Kingdom are the US, NZ, and the UK. 2. Users mention the country name when they know about that country. Or they belong to that country. So, we can say that maximum users who commented on this post belong to NZ, the US, Australia, or the UK. 3. Jacinda Ardern is the prime minister of NZ, which explains the mention of that name in most of the comments. As topic sentiment is positive, I can say that comment mentions the name of Jacinda Ardern is also positive. 4. We can also see the name of Trump ( President of the US) and Bill Gates (founder of Microsoft). But sentiments of comments that mention these names are not conclusive. You can analyze those comments separately. 5. Jacinda Ardern belongs to the ruling Labour party. And the opposition is the National party. Both Labour and National organization names are present in the comments. 6. You can also see the mention of COVID and WHO. Mention of Facebook in the organization tag is inconclusive unless you have the comments which mentioned it. With these entities, you can expect what type of data it is. You can categorize this data under the world news. These tags will help you to filter reading materials. The same topic will not appear if you run the same python program. So observation and tags may vary. Here is a Bar graph of Location extracted from the post. Here is a Word Cloud of Organization extracted from the post. Reddit is a great social media platform to test the accuracy of the BERT entity extraction model. This article will help you to process the output data of the BERT model and extract the entity. You will learn about its use-cases and how you use these tags to categorize the text data. Hopefully, this article will help you in the efficient search of different documents. Please find the complete code here.
[ { "code": null, "e": 241, "s": 171, "text": "Stuck behind the paywall? Read this article with my Friend link here." }, { "code": null, "e": 553, "s": 241, "text": "Named-Entity recognition (NER) is a process to extract information from an Unstructured Text. Its also known as Entity Extraction. This method extracts information such as time, place, currency, organizations, medical codes, person names, etc. We can mark these extracted entities as tags to articles/documents." }, { "code": null, "e": 690, "s": 553, "text": "But, what do we achieve by extracting the entity from the text? Do these tags help us to reduce time in the article’s searching process?" }, { "code": null, "e": 858, "s": 690, "text": "Tags on the articles or documents can save a lot of time by improving the search process. Tags help us to categorize text documents. It is one of the use-cases of NER." }, { "code": null, "e": 904, "s": 858, "text": "Some other use-cases of NER are listed below." }, { "code": null, "e": 1007, "s": 904, "text": "1. Categorize articles of NEWS agencies into the world, sports, fashion, entertainment, etc. category." }, { "code": null, "e": 1080, "s": 1007, "text": "2. It helps with product searches on different online shopping websites." }, { "code": null, "e": 1151, "s": 1080, "text": "3. Online courses can be categorized based on different relevant tags." }, { "code": null, "e": 1324, "s": 1151, "text": "We will use the BERT pre-trained model. Learn more about the BERT model here. BERT model will extract person name, organization, and location name from the Reddit subgroup." }, { "code": null, "e": 1367, "s": 1324, "text": "This article has divided into three parts." }, { "code": null, "e": 1412, "s": 1367, "text": "Part 1. Data collection and Data preparation" }, { "code": null, "e": 1543, "s": 1412, "text": "Python program connects with Reddit API and fetches information from subreddit. Then we format data according to BERT model input." }, { "code": null, "e": 1574, "s": 1543, "text": "Part 2. Information Extraction" }, { "code": null, "e": 1653, "s": 1574, "text": "We will extract entity information from the data prepared from the first part." }, { "code": null, "e": 1698, "s": 1653, "text": "Part 3. Data Analysis and Data Visualization" }, { "code": null, "e": 1798, "s": 1698, "text": "In this part, we will analyze the information extracted from the second part via graphs and charts." }, { "code": null, "e": 1822, "s": 1798, "text": "Now, Let’s get started." }, { "code": null, "e": 2190, "s": 1822, "text": "We will be using Reddit subgroup r/Worldnews data. Reddit provides API access to fetch titles, comments, and other data related to posts. PRAW is a python library that helps us to connect with an API. Learn more about the PRAW library here. (https://praw.readthedocs.io/en/latest/). You need to create a Reddit account to access the information required from the API." }, { "code": null, "e": 2230, "s": 2190, "text": "These are the required API information." }, { "code": null, "e": 2384, "s": 2230, "text": "reddit = praw.Reddit(client_id=’my_client_id’, client_secret=’my_client_secret’, user_agent=’my user agent name’)" }, { "code": null, "e": 2466, "s": 2384, "text": "Follow these steps mention in the article to get required API access information." }, { "code": null, "e": 2692, "s": 2466, "text": "Once you get access, we will fetch the title and comments from the r/Worldnews post. We will use the top weekly post of r/Worldnews. You can receive the data from a subgroup based on a different timeline and their popularity." }, { "code": null, "e": 3614, "s": 2692, "text": "def replies_of(top_level_comment, comment_list): if len(top_level_comment.replies) == 0: return else: for num, comment in enumerate(top_level_comment.replies): try: comment_list.append(str(comment.body)) except: continue replies_of(comment, comment_list)list_of_subreddit = [‘worldnews’]for j in list_of_subreddit: # get 10 hot posts from the MachineLearning subreddit top_posts = reddit.subreddit(j).top(‘week’, limit=1) comment_list = [] # save subreddit comments in dataframe for submission in top_posts: print(‘\\n\\n’) print(“Title :” , submission.title) submission_comm = reddit.submission(id=submission.id) comment_list.append(str(submission.title)) for count, top_level_comment in enumerate(submission_comm.comments): try: replies_of(top_level_comment, comment_list) except: continueprint(comment_list)" }, { "code": null, "e": 3765, "s": 3614, "text": "This code will fetch the entire comment section of the subreddit post using recursion function. The data will be store into the comment_list variable." }, { "code": null, "e": 3907, "s": 3765, "text": "Data prepared in the first part is in the input format of the BERT Model. The output generated by the model has saved in different variables." }, { "code": null, "e": 4194, "s": 3907, "text": "The transformer python library from Hugging face will help us to access the BERT model trained by DBMDZ. BERT token consists of around 30k words in its library. If input text consists of words that do not present in its library, then the BERT token break that word into near know words." }, { "code": null, "e": 4368, "s": 4194, "text": "For example, the Hugging word will split into hu and ##gging. If an unrecognized word has considered as an entity, then each splitted word will be assigned to the same tags." }, { "code": null, "e": 4420, "s": 4368, "text": "For example, (‘Hu’, ‘I-ORG’), (‘##gging’, ‘I-ORG’)." }, { "code": null, "e": 4825, "s": 4420, "text": "for sequence in comment_list: if len(sequence) > 512: continue tokens = tokenizer.tokenize(tokenizer.decode (tokenizer.encode(sequence))) inputs = tokenizer.encode(sequence, return_tensors=”tf”) outputs = model(inputs)[0] predictions = tf.argmax(outputs, axis=2) list_bert = [(token, label_list[prediction]) for token, prediction in zip(tokens, predictions[0].numpy())]" }, { "code": null, "e": 4903, "s": 4825, "text": "I have limited the input sentence length to 512 due to BERT token limitation." }, { "code": null, "e": 5126, "s": 4903, "text": "I have combined these words and assigned their respective entity. This model is not 100% accurate. Because of it, wrong tags might get designated to some words. We will try to avoid these non-related words in our analysis." }, { "code": null, "e": 5231, "s": 5126, "text": "We have got three categories for analysis. These categories are location, person name, and organization." }, { "code": null, "e": 5286, "s": 5231, "text": "Title of the topic and entity extracted from the data." }, { "code": null, "e": 7050, "s": 5286, "text": "Title: Research finds that New Zealand beat Covid-19 by trusting leaders and following advice. Citizens had a high level of knowledge about coronavirus and how it spread, and compliance with basic hygiene practices and trust in authorities was at nearly 100%.{‘Location’: [‘UNITED STATES’, ‘ILLINOIS’, ‘GREECE’, ‘TAIWAN’, ‘NEW Z’, ‘ISLAND’, ‘PORTLAND’, ‘NSW’, ‘CANADA’, ‘QUEENSLAND’, ‘VIETNAM’, ‘CHRISTCHURCH’, ‘HAWAII’,’VICTORIA’, ‘UK’, ‘RUSSIA’, ‘WELLINGTON’, ‘INDIANA’, ‘CHUR’, ‘NZ CHINA’, ‘STATES’, ‘ARGENTINA’, ‘CALIFORNIA’, ‘IETNAM’, ‘TRUMPTOWN’, ‘TEXAS’, ‘FRANCE’, ‘AUS’, ‘NZ’, ‘NEW YORK’, ‘JAPAN’, ‘FLORIDA’, ‘QLD’, ‘AUCKLAND’, ‘KE’, ‘USA’, ‘THE’, ‘CHINA’, ‘ITALY’, ‘SWEDEN’, ‘JONESTOWN’, ‘MELBOURNE’, ‘AMERICA’, ‘NEW ZEALAND’, ‘IRAQ’,’US’, ‘AFGHANISTAN’, ‘AUSTRALIA’], ‘Organisation’: [‘YOUTUBE’, ‘FED’, ‘FACEBOOK’, ‘ALLPRESS’, ‘GNELL’, ‘VODAFONE’, ‘IRON’, ‘LIB’, ‘RESERVE BANK’, ‘LANEWAY’, ‘DEMS’, ‘ALJAZEERA’, ‘RVA’, ‘JACINDAS’, ‘CIA’, ‘LABOR’, ‘TREASURY’, ‘SMD’, ‘WHO’, ‘SENATE’, ‘LIBERALS’, ‘LIBERAL’, ‘IIRC’, ‘COVID’, ‘HS’, ‘PRC’, ‘NATIONAL’, ‘TIL’, ‘SHITREDDITSAYS’, ‘COM’, ‘FOX’, ‘EZZANZ’, ‘QLD’, ‘FAMILY FIRST’, ‘NATIONALS’, ‘NIN’, ‘DEFENCE FORCE’, ‘ZZAN’, ‘ACINDA’, ‘FOX NEWS’, ‘LABOUR’, ‘FEDERAL’, ‘HOUSE OF REPS’, ‘WORLDNEWS’, ‘MURDOCH’, ‘GREENS’], ‘Person Name’: [‘KEVIN’, ‘FATHE’, ‘KAREN’, ‘MACRON’, ‘WINSTON’, ‘LES’, ‘BUCKLEY’, ‘CHLÖE SWARBRICK’, ‘COLLINS’, ‘CLINTON’,’JUDITH COLLINS’, ‘TO’, ‘KYLER’, ‘ASHLEY’, ‘BILL GATES’, ‘THE P’, ‘SCOTTY’, ‘HITLER’, ‘TRUMP’, ‘RUPERT MURDOCH’, ‘GATES’, ‘HGO’, ‘WILLIAM CASEY’, ‘OAK’, ‘TOVA’,’JIM JONES’, ‘KEZZA’, ‘ENN’, ‘MERICA’, ‘ROF’, ‘BLOOMFIELD’, ‘GOD’, ‘KIF’, ‘CLIVE PALMER’, ‘DAVE GROHL’, ‘SHER’, ‘BLAIR’, ‘JACINDA ARDERN’, ‘DAD’, ‘JACINDA’, ‘WINS TON PETERS’, ‘LERON’, ‘BLOOMFIELDS’, ‘MURDOCH’]}" }, { "code": null, "e": 7076, "s": 7050, "text": "Here are my observations." }, { "code": null, "e": 7255, "s": 7076, "text": "1. New Zealand’s location got many mentions in comments. This location name is also mention in the title. Reddit users may prefer a short form of the country name than full form." }, { "code": null, "e": 7385, "s": 7255, "text": "For example, a short form of countries such as the United States, New Zealand, and the United Kingdom are the US, NZ, and the UK." }, { "code": null, "e": 7591, "s": 7385, "text": "2. Users mention the country name when they know about that country. Or they belong to that country. So, we can say that maximum users who commented on this post belong to NZ, the US, Australia, or the UK." }, { "code": null, "e": 7812, "s": 7591, "text": "3. Jacinda Ardern is the prime minister of NZ, which explains the mention of that name in most of the comments. As topic sentiment is positive, I can say that comment mentions the name of Jacinda Ardern is also positive." }, { "code": null, "e": 8026, "s": 7812, "text": "4. We can also see the name of Trump ( President of the US) and Bill Gates (founder of Microsoft). But sentiments of comments that mention these names are not conclusive. You can analyze those comments separately." }, { "code": null, "e": 8195, "s": 8026, "text": "5. Jacinda Ardern belongs to the ruling Labour party. And the opposition is the National party. Both Labour and National organization names are present in the comments." }, { "code": null, "e": 8354, "s": 8195, "text": "6. You can also see the mention of COVID and WHO. Mention of Facebook in the organization tag is inconclusive unless you have the comments which mentioned it." }, { "code": null, "e": 8520, "s": 8354, "text": "With these entities, you can expect what type of data it is. You can categorize this data under the world news. These tags will help you to filter reading materials." }, { "code": null, "e": 8621, "s": 8520, "text": "The same topic will not appear if you run the same python program. So observation and tags may vary." }, { "code": null, "e": 8678, "s": 8621, "text": "Here is a Bar graph of Location extracted from the post." }, { "code": null, "e": 8740, "s": 8678, "text": "Here is a Word Cloud of Organization extracted from the post." }, { "code": null, "e": 9025, "s": 8740, "text": "Reddit is a great social media platform to test the accuracy of the BERT entity extraction model. This article will help you to process the output data of the BERT model and extract the entity. You will learn about its use-cases and how you use these tags to categorize the text data." }, { "code": null, "e": 9111, "s": 9025, "text": "Hopefully, this article will help you in the efficient search of different documents." } ]
Powershell - Set System Time
Set-Date cmdlet is used to set System Time. In this example, we're using Get-Date to get current date Type the following command in PowerShell ISE Console get-date -displayHint time You can see following output in PowerShell console. 10:04:18 AM In this example, we're using Set-Date to adjust to 60 minutes. Type the following commands in PowerShell ISE Console > $timeToAdd = New-TimeSpan -Minutes -60 > set-date -adjust $timeToAdd You can see following output in PowerShell console. Saturday, May 05, 2018 11:05:16 AM Now revert back to substract added time to current date. Type the following command in PowerShell ISE Console > $timeToAdd = New-TimeSpan -Minutes -60 > set-date -adjust $timeToAdd You can see following output in PowerShell console. Saturday, May 05, 2018 10:08:54 AM 15 Lectures 3.5 hours Fabrice Chrzanowski 35 Lectures 2.5 hours Vijay Saini 145 Lectures 12.5 hours Fettah Ben Print Add Notes Bookmark this page
[ { "code": null, "e": 2078, "s": 2034, "text": "Set-Date cmdlet is used to set System Time." }, { "code": null, "e": 2136, "s": 2078, "text": "In this example, we're using Get-Date to get current date" }, { "code": null, "e": 2189, "s": 2136, "text": "Type the following command in PowerShell ISE Console" }, { "code": null, "e": 2216, "s": 2189, "text": "get-date -displayHint time" }, { "code": null, "e": 2268, "s": 2216, "text": "You can see following output in PowerShell console." }, { "code": null, "e": 2281, "s": 2268, "text": "10:04:18 AM\n" }, { "code": null, "e": 2344, "s": 2281, "text": "In this example, we're using Set-Date to adjust to 60 minutes." }, { "code": null, "e": 2398, "s": 2344, "text": "Type the following commands in PowerShell ISE Console" }, { "code": null, "e": 2469, "s": 2398, "text": "> $timeToAdd = New-TimeSpan -Minutes -60\n> set-date -adjust $timeToAdd" }, { "code": null, "e": 2521, "s": 2469, "text": "You can see following output in PowerShell console." }, { "code": null, "e": 2557, "s": 2521, "text": "Saturday, May 05, 2018 11:05:16 AM\n" }, { "code": null, "e": 2614, "s": 2557, "text": "Now revert back to substract added time to current date." }, { "code": null, "e": 2667, "s": 2614, "text": "Type the following command in PowerShell ISE Console" }, { "code": null, "e": 2738, "s": 2667, "text": "> $timeToAdd = New-TimeSpan -Minutes -60\n> set-date -adjust $timeToAdd" }, { "code": null, "e": 2790, "s": 2738, "text": "You can see following output in PowerShell console." }, { "code": null, "e": 2826, "s": 2790, "text": "Saturday, May 05, 2018 10:08:54 AM\n" }, { "code": null, "e": 2861, "s": 2826, "text": "\n 15 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2882, "s": 2861, "text": " Fabrice Chrzanowski" }, { "code": null, "e": 2917, "s": 2882, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2930, "s": 2917, "text": " Vijay Saini" }, { "code": null, "e": 2967, "s": 2930, "text": "\n 145 Lectures \n 12.5 hours \n" }, { "code": null, "e": 2979, "s": 2967, "text": " Fettah Ben" }, { "code": null, "e": 2986, "s": 2979, "text": " Print" }, { "code": null, "e": 2997, "s": 2986, "text": " Add Notes" } ]
Java JDOM Parser - Create XML Document
Here is the XML file that we need to create − <?xml version = "1.0" encoding = "UTF-8"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars> import java.io.IOException; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class CreateXmlFileDemo { public static void main(String[] args) { try{ //root element Element carsElement = new Element("cars"); Document doc = new Document(carsElement); //supercars element Element supercarElement = new Element("supercars"); supercarElement.setAttribute(new Attribute("company","Ferrari")); //supercars element Element carElement1 = new Element("carname"); carElement1.setAttribute(new Attribute("type","formula one")); carElement1.setText("Ferrari 101"); Element carElement2 = new Element("carname"); carElement2.setAttribute(new Attribute("type","sports")); carElement2.setText("Ferrari 202"); supercarElement.addContent(carElement1); supercarElement.addContent(carElement2); doc.getRootElement().addContent(supercarElement); XMLOutputter xmlOutput = new XMLOutputter(); // display ml xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, System.out); } catch(IOException e) { e.printStackTrace(); } } } This would produce the following result − <?xml version = "1.0" encoding = "UTF-8"?> <cars> <supercars company = "Ferrari"> <carname type = "formula one">Ferrari 101</carname> <carname type = "sports">Ferrari 202</carname> </supercars> </cars> 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2369, "s": 2323, "text": "Here is the XML file that we need to create −" }, { "code": null, "e": 2589, "s": 2369, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n</cars>" }, { "code": null, "e": 3941, "s": 2589, "text": "import java.io.IOException;\n\nimport org.jdom2.Attribute;\nimport org.jdom2.Document;\nimport org.jdom2.Element;\nimport org.jdom2.output.Format;\nimport org.jdom2.output.XMLOutputter;\n\n\npublic class CreateXmlFileDemo {\n\n public static void main(String[] args) {\n\n try{\n //root element\n Element carsElement = new Element(\"cars\");\n Document doc = new Document(carsElement);\n\n //supercars element\n Element supercarElement = new Element(\"supercars\");\n supercarElement.setAttribute(new Attribute(\"company\",\"Ferrari\"));\n\n //supercars element\n Element carElement1 = new Element(\"carname\");\n carElement1.setAttribute(new Attribute(\"type\",\"formula one\"));\n carElement1.setText(\"Ferrari 101\");\n\n Element carElement2 = new Element(\"carname\");\n carElement2.setAttribute(new Attribute(\"type\",\"sports\"));\n carElement2.setText(\"Ferrari 202\");\n\n supercarElement.addContent(carElement1);\n supercarElement.addContent(carElement2);\n\n doc.getRootElement().addContent(supercarElement);\n\n XMLOutputter xmlOutput = new XMLOutputter();\n\n // display ml\n xmlOutput.setFormat(Format.getPrettyFormat());\n xmlOutput.output(doc, System.out); \n } catch(IOException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 3983, "s": 3941, "text": "This would produce the following result −" }, { "code": null, "e": 4204, "s": 3983, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<cars>\n <supercars company = \"Ferrari\">\n <carname type = \"formula one\">Ferrari 101</carname>\n <carname type = \"sports\">Ferrari 202</carname>\n </supercars>\n</cars>\n" }, { "code": null, "e": 4237, "s": 4204, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4253, "s": 4237, "text": " Malhar Lathkar" }, { "code": null, "e": 4286, "s": 4253, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 4302, "s": 4286, "text": " Malhar Lathkar" }, { "code": null, "e": 4337, "s": 4302, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4351, "s": 4337, "text": " Anadi Sharma" }, { "code": null, "e": 4385, "s": 4351, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4399, "s": 4385, "text": " Tushar Kale" }, { "code": null, "e": 4436, "s": 4399, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4451, "s": 4436, "text": " Monica Mittal" }, { "code": null, "e": 4484, "s": 4451, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4503, "s": 4484, "text": " Arnab Chakraborty" }, { "code": null, "e": 4510, "s": 4503, "text": " Print" }, { "code": null, "e": 4521, "s": 4510, "text": " Add Notes" } ]
How to pick an image from image gallery in Android?
This example demonstrates how do I pick an image from image gallery in android app Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/imageView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"/> <Button android:id="@+id/buttonLoadPicture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:text="Load Picture" android:layout_gravity="center"/> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { ImageView imageView; Button button; private static final int PICK_IMAGE = 100; Uri imageUri; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView)findViewById(R.id.imageView); button = (Button)findViewById(R.id.buttonLoadPicture); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openGallery(); } }); } private void openGallery() { Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI); startActivityForResult(gallery, PICK_IMAGE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){ imageUri = data.getData(); imageView.setImageURI(imageUri); } } } Step 4 − Add the following code to androidManifest.xm <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1145, "s": 1062, "text": "This example demonstrates how do I pick an image from image gallery in android app" }, { "code": null, "e": 1274, "s": 1145, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1338, "s": 1274, "text": "Step 2 − Add the following code to res/layout/activity_main.xml" }, { "code": null, "e": 1991, "s": 1338, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"vertical\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_weight=\"1\"/>\n <Button\n android:id=\"@+id/buttonLoadPicture\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_weight=\"0\"\n android:text=\"Load Picture\"\n android:layout_gravity=\"center\"/>\n</LinearLayout>" }, { "code": null, "e": 2048, "s": 1991, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3382, "s": 2048, "text": "import android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.provider.MediaStore;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\npublic class MainActivity extends Activity {\n ImageView imageView;\n Button button;\n private static final int PICK_IMAGE = 100;\n Uri imageUri;\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n imageView = (ImageView)findViewById(R.id.imageView);\n button = (Button)findViewById(R.id.buttonLoadPicture);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n openGallery();\n }\n });\n }\n private void openGallery() {\n Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);\n startActivityForResult(gallery, PICK_IMAGE);\n }\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data){\n super.onActivityResult(requestCode, resultCode, data);\n if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){\n imageUri = data.getData();\n imageView.setImageURI(imageUri);\n }\n }\n}" }, { "code": null, "e": 3436, "s": 3382, "text": "Step 4 − Add the following code to androidManifest.xm" }, { "code": null, "e": 4184, "s": 3436, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4531, "s": 4184, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4572, "s": 4531, "text": "Click here to download the project code." } ]
Change Fill and Border Color of ggplot2 Plot in R - GeeksforGeeks
17 Jun, 2021 In this article, we are going to see various methods to add color into a ggplot2 in the R programming language. We will select a bar plot as an example to see how we can change the color of the fill of the bar as well as the borders. First, you need to install the ggplot2 package if it is not previously installed in R Studio. For creating a simple bar plot we will use the function geom_bar( ). Syntax: geom_bar(stat, fill, color, width) Parameters : stat : Set the stat parameter to identify the mode. fill : Represents color inside the bars. color : Represents color of outlines of the bars. width : Represents width of the bars. Data in use: Let us first draw a regular plot so that the difference can be apparent. Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) # Basic vertical barplotperf <-ggplot(data=ODI, aes(x=match, y=runs))+ geom_bar(stat="identity")perf Output: Now let us discuss colors that can be added to this plot. Adding colors not only make the charts appealing but also gives makes them descriptive for better understanding. Different fill color Use the command fill to add color inside the bars. Since the bars are in the different x-axis, values we need to assign the x-axis variable to the fill. Syntax fill=attribute You need to write this command inside the aes() also known as the quoting function or aesthetic function under the ggplot2 library. Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) # Assigning default and different colors to bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat="identity")perf Output: Same fill color Use the same fill. But this time since we have to assign a single color we will use it inside the geom_bar( ). Assign the color of your choice to the fill as shown below. The theme is changed because some color plots might not be visible to the default theme in R. Syntax: theme_[theme_name]( ) Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) # Assigning default and same colors to bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs))+ geom_bar(stat="identity",fill="lightblue")+ theme_dark()perf Output: Same outline Here we need a command color for assigning colors to the outline. Outline colors look good when the fill color is white. It is the property of color because some colors overshadow other colors or if we assign the same color to fill and outline both. Since we need the same fill and the same outline we will write these commands inside the geom_bar( ). Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) # Assigning default and same outline # colors to bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs))+ geom_bar(stat="identity",color="red",fill="white")+ theme_classic()perf Output: Different Outline Here we need to provide different outlines. The fill will be the same which is white. The fill will be inside the geom_bar( ). The color will be inside aes( ) under ggplot( ) as it is variable in this case. Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) Assigning default and different outline colors to bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,color=match))+ geom_bar(stat="identity",fill="white")+ theme_classic()perf Output: 1) For Fill color To manually change the color of a bar plot we will use the following function : scale_fill_manual( ) : It is used to provide custom colors. We can either write the color code as “#XXXXXX” or we can directly write the color name as “color_name”. Syntax: scale_fill_manual( values ) scale_fill_brewer( ) : It uses a range of colors from set of palettes in RColorBrewer package. Syntax: scale_fill_brewer( palette) scale_fill_grey( ) : To fill the bars using gray scale colors. Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) perf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match)) + geom_bar(stat="identity") # Assigning fill colors manually # Assigning custom colorperf+scale_fill_manual(values=c("#9933FF", "#33FFFF", "red", "darkblue")) # Assigning brewer palette perf+scale_fill_brewer(palette=""PrGN"") # Assigning gray scaleperf+scale_fill_grey() Output: 2) For Borders or outlines To manually change the color of borders of a bar plot we will use the following function : scale_color_manual( ): It is used to provide custom colors. We can either write the color code as “#XXXXXX” or we can directly write the color name as “color_name”. Syntax: scale_color_manual( values ) scale_color_brewer( ): It uses a range of colors from set of palettes in RColorBrewer package. Syntax: scale_color_brewer( palette) scale_color_grey( ): Gives outlines from the gray scale colors. Since, we need to fill the borders, better to make all the bars fill color as white for better blending of colors and also add a suitable theme of your choice. Example: R library(ggplot2) # Inserting dataODI <- data.frame(match=c("M-1","M-2","M-3","M-4"), runs=c(67,37,74,10)) perf <-ggplot(data=ODI, aes(x=match, y=runs,color=match))+ geom_bar(stat="identity",fill="white") # Assigning border colors manually # Assigning custom colorsperf+scale_color_manual(values=c("#9933FF", "#33FFFF", "red", "darkblue"))+theme_classic() # Assigning brewer palette perf+scale_color_brewer(palette="Dark2")+theme_classic() # Assigning gray scaleperf+scale_color_grey()+theme_classic() Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement
[ { "code": null, "e": 24783, "s": 24755, "text": "\n17 Jun, 2021" }, { "code": null, "e": 25017, "s": 24783, "text": "In this article, we are going to see various methods to add color into a ggplot2 in the R programming language. We will select a bar plot as an example to see how we can change the color of the fill of the bar as well as the borders." }, { "code": null, "e": 25180, "s": 25017, "text": "First, you need to install the ggplot2 package if it is not previously installed in R Studio. For creating a simple bar plot we will use the function geom_bar( )." }, { "code": null, "e": 25188, "s": 25180, "text": "Syntax:" }, { "code": null, "e": 25223, "s": 25188, "text": "geom_bar(stat, fill, color, width)" }, { "code": null, "e": 25238, "s": 25223, "text": "Parameters : " }, { "code": null, "e": 25290, "s": 25238, "text": "stat : Set the stat parameter to identify the mode." }, { "code": null, "e": 25331, "s": 25290, "text": "fill : Represents color inside the bars." }, { "code": null, "e": 25381, "s": 25331, "text": "color : Represents color of outlines of the bars." }, { "code": null, "e": 25419, "s": 25381, "text": "width : Represents width of the bars." }, { "code": null, "e": 25432, "s": 25419, "text": "Data in use:" }, { "code": null, "e": 25505, "s": 25432, "text": "Let us first draw a regular plot so that the difference can be apparent." }, { "code": null, "e": 25514, "s": 25505, "text": "Example:" }, { "code": null, "e": 25516, "s": 25514, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) # Basic vertical barplotperf <-ggplot(data=ODI, aes(x=match, y=runs))+ geom_bar(stat=\"identity\")perf", "e": 25742, "s": 25516, "text": null }, { "code": null, "e": 25750, "s": 25742, "text": "Output:" }, { "code": null, "e": 25921, "s": 25750, "text": "Now let us discuss colors that can be added to this plot. Adding colors not only make the charts appealing but also gives makes them descriptive for better understanding." }, { "code": null, "e": 25942, "s": 25921, "text": "Different fill color" }, { "code": null, "e": 26096, "s": 25942, "text": "Use the command fill to add color inside the bars. Since the bars are in the different x-axis, values we need to assign the x-axis variable to the fill. " }, { "code": null, "e": 26103, "s": 26096, "text": "Syntax" }, { "code": null, "e": 26118, "s": 26103, "text": "fill=attribute" }, { "code": null, "e": 26250, "s": 26118, "text": "You need to write this command inside the aes() also known as the quoting function or aesthetic function under the ggplot2 library." }, { "code": null, "e": 26259, "s": 26250, "text": "Example:" }, { "code": null, "e": 26261, "s": 26259, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) # Assigning default and different colors to bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match))+ geom_bar(stat=\"identity\")perf", "e": 26526, "s": 26261, "text": null }, { "code": null, "e": 26534, "s": 26526, "text": "Output:" }, { "code": null, "e": 26550, "s": 26534, "text": "Same fill color" }, { "code": null, "e": 26816, "s": 26550, "text": "Use the same fill. But this time since we have to assign a single color we will use it inside the geom_bar( ). Assign the color of your choice to the fill as shown below. The theme is changed because some color plots might not be visible to the default theme in R. " }, { "code": null, "e": 26824, "s": 26816, "text": "Syntax:" }, { "code": null, "e": 26846, "s": 26824, "text": "theme_[theme_name]( )" }, { "code": null, "e": 26855, "s": 26846, "text": "Example:" }, { "code": null, "e": 26857, "s": 26855, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) # Assigning default and same colors to bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs))+ geom_bar(stat=\"identity\",fill=\"lightblue\")+ theme_dark()perf", "e": 27137, "s": 26857, "text": null }, { "code": null, "e": 27145, "s": 27137, "text": "Output:" }, { "code": null, "e": 27158, "s": 27145, "text": "Same outline" }, { "code": null, "e": 27511, "s": 27158, "text": " Here we need a command color for assigning colors to the outline. Outline colors look good when the fill color is white. It is the property of color because some colors overshadow other colors or if we assign the same color to fill and outline both. Since we need the same fill and the same outline we will write these commands inside the geom_bar( )." }, { "code": null, "e": 27520, "s": 27511, "text": "Example:" }, { "code": null, "e": 27522, "s": 27520, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) # Assigning default and same outline # colors to bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs))+ geom_bar(stat=\"identity\",color=\"red\",fill=\"white\")+ theme_classic()perf", "e": 27823, "s": 27522, "text": null }, { "code": null, "e": 27831, "s": 27823, "text": "Output:" }, { "code": null, "e": 27849, "s": 27831, "text": "Different Outline" }, { "code": null, "e": 28056, "s": 27849, "text": "Here we need to provide different outlines. The fill will be the same which is white. The fill will be inside the geom_bar( ). The color will be inside aes( ) under ggplot( ) as it is variable in this case." }, { "code": null, "e": 28065, "s": 28056, "text": "Example:" }, { "code": null, "e": 28067, "s": 28065, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) Assigning default and different outline colors to bar plotperf <-ggplot(data=ODI, aes(x=match, y=runs,color=match))+ geom_bar(stat=\"identity\",fill=\"white\")+ theme_classic()perf", "e": 28369, "s": 28067, "text": null }, { "code": null, "e": 28377, "s": 28369, "text": "Output:" }, { "code": null, "e": 28395, "s": 28377, "text": "1) For Fill color" }, { "code": null, "e": 28475, "s": 28395, "text": "To manually change the color of a bar plot we will use the following function :" }, { "code": null, "e": 28640, "s": 28475, "text": "scale_fill_manual( ) : It is used to provide custom colors. We can either write the color code as “#XXXXXX” or we can directly write the color name as “color_name”." }, { "code": null, "e": 28648, "s": 28640, "text": "Syntax:" }, { "code": null, "e": 28677, "s": 28648, "text": "scale_fill_manual( values ) " }, { "code": null, "e": 28772, "s": 28677, "text": "scale_fill_brewer( ) : It uses a range of colors from set of palettes in RColorBrewer package." }, { "code": null, "e": 28780, "s": 28772, "text": "Syntax:" }, { "code": null, "e": 28808, "s": 28780, "text": "scale_fill_brewer( palette)" }, { "code": null, "e": 28871, "s": 28808, "text": "scale_fill_grey( ) : To fill the bars using gray scale colors." }, { "code": null, "e": 28880, "s": 28871, "text": "Example:" }, { "code": null, "e": 28882, "s": 28880, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) perf <-ggplot(data=ODI, aes(x=match, y=runs,fill=match)) + geom_bar(stat=\"identity\") # Assigning fill colors manually # Assigning custom colorperf+scale_fill_manual(values=c(\"#9933FF\", \"#33FFFF\", \"red\", \"darkblue\")) # Assigning brewer palette perf+scale_fill_brewer(palette=\"\"PrGN\"\") # Assigning gray scaleperf+scale_fill_grey()", "e": 29424, "s": 28882, "text": null }, { "code": null, "e": 29432, "s": 29424, "text": "Output:" }, { "code": null, "e": 29460, "s": 29432, "text": "2) For Borders or outlines " }, { "code": null, "e": 29551, "s": 29460, "text": "To manually change the color of borders of a bar plot we will use the following function :" }, { "code": null, "e": 29716, "s": 29551, "text": "scale_color_manual( ): It is used to provide custom colors. We can either write the color code as “#XXXXXX” or we can directly write the color name as “color_name”." }, { "code": null, "e": 29724, "s": 29716, "text": "Syntax:" }, { "code": null, "e": 29754, "s": 29724, "text": "scale_color_manual( values ) " }, { "code": null, "e": 29849, "s": 29754, "text": "scale_color_brewer( ): It uses a range of colors from set of palettes in RColorBrewer package." }, { "code": null, "e": 29857, "s": 29849, "text": "Syntax:" }, { "code": null, "e": 29886, "s": 29857, "text": "scale_color_brewer( palette)" }, { "code": null, "e": 29950, "s": 29886, "text": "scale_color_grey( ): Gives outlines from the gray scale colors." }, { "code": null, "e": 30110, "s": 29950, "text": "Since, we need to fill the borders, better to make all the bars fill color as white for better blending of colors and also add a suitable theme of your choice." }, { "code": null, "e": 30119, "s": 30110, "text": "Example:" }, { "code": null, "e": 30121, "s": 30119, "text": "R" }, { "code": "library(ggplot2) # Inserting dataODI <- data.frame(match=c(\"M-1\",\"M-2\",\"M-3\",\"M-4\"), runs=c(67,37,74,10)) perf <-ggplot(data=ODI, aes(x=match, y=runs,color=match))+ geom_bar(stat=\"identity\",fill=\"white\") # Assigning border colors manually # Assigning custom colorsperf+scale_color_manual(values=c(\"#9933FF\", \"#33FFFF\", \"red\", \"darkblue\"))+theme_classic() # Assigning brewer palette perf+scale_color_brewer(palette=\"Dark2\")+theme_classic() # Assigning gray scaleperf+scale_color_grey()+theme_classic()", "e": 30729, "s": 30121, "text": null }, { "code": null, "e": 30737, "s": 30729, "text": "Output:" }, { "code": null, "e": 30744, "s": 30737, "text": "Picked" }, { "code": null, "e": 30753, "s": 30744, "text": "R-ggplot" }, { "code": null, "e": 30764, "s": 30753, "text": "R Language" }, { "code": null, "e": 30862, "s": 30764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30871, "s": 30862, "text": "Comments" }, { "code": null, "e": 30884, "s": 30871, "text": "Old Comments" }, { "code": null, "e": 30936, "s": 30884, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 30988, "s": 30936, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 31026, "s": 30988, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 31061, "s": 31026, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 31119, "s": 31061, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 31155, "s": 31119, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 31204, "s": 31155, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 31247, "s": 31204, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 31297, "s": 31247, "text": "How to filter R dataframe by multiple conditions?" } ]
Exploratory Data Analysis ...A topic that is neglected in Data Science Projects | by sunil kumar | Towards Data Science
Exploratory Data Analysis The topics that we are going to discuss as part of Exploratory Data Analysis are: What is Exploratory Data Analysis? Why do we do EDA? What are the steps in EDA? What are the tools used for EDA? What happens if we don’t do EDA? What is Exploratory Data Analysis? Exploratory Data Analysis (EDA) is the first step in your data analysis process developed by “John Tukey” in the 1970s. In statistics, exploratory data analysis is an approach to analyzing data sets to summarize their main characteristics, often with visual methods. By the name itself, we can get to know that it is a step in which we need to explore the data set. For Example, You are planning to go on a trip to the “X” location. Things you do before taking a decision: You will explore the location on what all places, waterfalls, trekking, beaches, restaurants that location has in Google, Instagram, Facebook, and other social Websites. Calculate whether it is in your budget or not. Check for the time to cover all the places. Type of Travel method. Similarly, when you are trying to build a machine learning model you need to be pretty sure whether your data is making sense or not. The main aim of exploratory data analysis is to obtain confidence in your data to an extent where you’re ready to engage a machine learning algorithm. Why do we do EDA? Exploratory Data Analysis is a crucial step before you jump to machine learning or modeling your data. By doing this you can get to know whether the selected features are good enough to model, are all the features required, are there any correlations based on which we can either go back to the Data Preprocessing step or move on to modeling. Once EDA is complete and insights are drawn, its feature can be used for supervised and unsupervised machine learning modeling. In every machine learning workflow, the last step is Reporting or Providing the insights to the Stake Holders and as a Data Scientist you can explain every bit of code but you need to keep in mind the audience. By completing the EDA you will have many plots,heat-maps, frequency distribution, graphs, correlation matrix along with the hypothesis by which any individual can understand what your data is all about and what insights you got from exploring your data set. We have a saying “A picture is worth a thousand words”. I want to modify it for data scientist as “A Plot is worth a thousand rows” In our Trip Example, we do all the exploration of the selected place based on which we will get the confidence to plan the trip and even share with our friends the insights we got regarding the place so that they can also join. What are the steps in EDA? There are many steps for conducting Exploratory data analysis. I want to discuss regarding the below few steps Description of data Handling missing data Handling outliers Understanding relationships and new insights through plots a) Description of data: We need to know the different kinds of data and other statistics of our data before we can move on to the other steps. A good one is to start with the describe() function in python. In Pandas, we can apply function describe on a data frame which helps in generating descriptive statistics that summarize the central tendency, dispersion, and shape of a dataset’s distribution, excluding “NaN” values. For numeric data, the result’s index will include count, mean, std, min, max as well as lower, 50 and upper percentiles. By default, the lower percentile is 25 and the upper percentile is 75. The 50 percentile is the same as the median. For object data (e.g. strings or timestamps), the result’s index will include count, unique, top, and freq. The top is the most common value. Freq is the most common value frequency. Timestamps also include the first and last items. b) Handling missing data: Data in the real world are rarely clean and homogeneous. Data can either be missing during data extraction or collection due to several reasons. Missing values need to be handled carefully because they reduce the quality of any of our performance metrics. It can also lead to wrong prediction or classification and can also cause a high bias for any given model being used. There are several options for handling missing values. However, the choice of what should be done is largely dependent on the nature of our data and the missing values. Below are some of the techniques: Drop NULL or missing values Fill Missing Values Predict Missing values with an ML Algorithm (i) Drop NULL or missing values: This is the fastest and easiest step to handle missing values. However, it is not generally advised. This method reduces the quality of our model as it reduces sample size because it works by deleting all other observations where any of the variables are missing. Python code : dataset.dropna() (ii) Fill Missing Values: This is the most common method of handling missing values. This is a process whereby missing values are replaced with a test statistic like mean, median or mode of the particular feature the missing value belongs to. Python code : dataset[‘Column_name’]=dataset[‘Column_name’].fillna(mean_value). (iii)Predict Missing values with an ML Algorithm: This is by far one of the best and most efficient methods for handling missing data. Depending on the class of data that is missing, one can either use a regression or classification model to predict missing data. c) Handling outliers: An outlier is something separate or different from the crowd. Outliers can be a result of a mistake during data collection or it can be just an indication of variance in your data. Some of the methods for detecting and handling outliers: Box Plot Scatter plot Z-score IQR(Inter-Quartile Range) (i) Box Plot: A box plot is a method for graphically depicting groups of numerical data through their quartiles. The box extends from the Q1 to Q3 quartile values of the data, with a line at the median (Q2). The whiskers extend from the edges of the box to show the range of the data. Outlier points are those past the end of the whiskers. Box plots show robust measures of location and spread as well as providing information about symmetry and outliers. (ii) Scatter plot: A scatter plot is a mathematical diagram using Cartesian coordinates to display values for two variables for a set of data. The data are displayed as a collection of points, each having the value of one variable determining the position on the horizontal axis and the value of the other variable determining the position on the vertical axis. The points that are far from the population can be termed as an outlier. (iii) Z-score: The Z-score is the signed number of standard deviations by which the value of an observation or data point is above the mean value of what is being observed or measured. While calculating the Z-score we re-scale and center the data and look for data points that are too far from zero. These data points which are way too far from zero will be treated as the outliers. In most of the cases, a threshold of 3 or -3 is used i.e if the Z-score value is greater than or less than 3 or -3 respectively, that data point will be identified as outliers. Python Code: z = np.abs(stats.zscore(dataset)) Once we get the z-score we can fit our datset base on that. Python Code: dataset = dataset[(z < 3).all(axis=1)] (iv) IQR: The interquartile range (IQR) is a measure of statistical dispersion, being equal to the difference between 75th and 25th percentiles, or between upper and lower quartiles. IQR = Q3 − Q1. Python Code: Q1 = dataset.quantile(0.25)Q3 = dataset.quantile(0.75)IQR = Q3 — Q1 Once we have IQR scores below code will give an output with some true and false values. The data point where we have False means values are valid and True indicates the presence of an outlier. Python Code: print(boston_df_o1 < (Q1–1.5 * IQR)) |(boston_df_o1 > (Q3 + 1.5 * IQR)) d) Understanding relationships and new insights through plots : We can get many relations in our data by visualizing our data set.Let’s go through some techniques in-order to see the insights. Histogram Heat Maps (i) Histogram: A histogram is a great tool for quickly assessing a probability distribution that is easily understood by almost any audience. Python offers a handful of different options for building and plotting histograms. (ii) Heat Maps: The Heat Map procedure shows the distribution of a quantitative variable over all combinations of 2 categorical factors. If one of the 2 factors represents time, then the evolution of the variable can be easily viewed using the map. A gradient color scale is used to represent the values of the quantitative variable. The correlation between two random variables is a number that runs from -1 through 0 to +1 and indicates a strong inverse relationship, no relationship, and a strong direct relationship, respectively. What are the tools used for EDA? There are plenty of open-source tools exist which automate the steps of predictive modeling like data cleaning, data visualization. Some of them are also quite popular like Excel, Tableau, Qlikview, Weka and many more apart from the programming. In programming, we can accomplish EDA using Python, R, SAS. Some of the important packages in Python are: Pandas Numpy Matplotlib Seaborn Bokeh What happens if we don’t do EDA? Many Data Scientists will be in a hurry to get to the machine learning stage, some either entirely skip exploratory process or do a very minimal job. This is a mistake with many implications, including generating inaccurate models, generating accurate models but on the wrong data, not creating the right types of variables in data preparation, and using resources inefficiently because of realizing only after generating models that perhaps the data is skewed, or has outliers, or has too many missing values, or finding that some values are inconsistent. In our Trip example, without any prior exploration of the place you will be facing many problems like directions, cost, travel in the trip which can be reduced by EDA the same applies to the machine learning problem.
[ { "code": null, "e": 198, "s": 172, "text": "Exploratory Data Analysis" }, { "code": null, "e": 280, "s": 198, "text": "The topics that we are going to discuss as part of Exploratory Data Analysis are:" }, { "code": null, "e": 315, "s": 280, "text": "What is Exploratory Data Analysis?" }, { "code": null, "e": 333, "s": 315, "text": "Why do we do EDA?" }, { "code": null, "e": 360, "s": 333, "text": "What are the steps in EDA?" }, { "code": null, "e": 393, "s": 360, "text": "What are the tools used for EDA?" }, { "code": null, "e": 426, "s": 393, "text": "What happens if we don’t do EDA?" }, { "code": null, "e": 461, "s": 426, "text": "What is Exploratory Data Analysis?" }, { "code": null, "e": 827, "s": 461, "text": "Exploratory Data Analysis (EDA) is the first step in your data analysis process developed by “John Tukey” in the 1970s. In statistics, exploratory data analysis is an approach to analyzing data sets to summarize their main characteristics, often with visual methods. By the name itself, we can get to know that it is a step in which we need to explore the data set." }, { "code": null, "e": 934, "s": 827, "text": "For Example, You are planning to go on a trip to the “X” location. Things you do before taking a decision:" }, { "code": null, "e": 1104, "s": 934, "text": "You will explore the location on what all places, waterfalls, trekking, beaches, restaurants that location has in Google, Instagram, Facebook, and other social Websites." }, { "code": null, "e": 1151, "s": 1104, "text": "Calculate whether it is in your budget or not." }, { "code": null, "e": 1195, "s": 1151, "text": "Check for the time to cover all the places." }, { "code": null, "e": 1218, "s": 1195, "text": "Type of Travel method." }, { "code": null, "e": 1503, "s": 1218, "text": "Similarly, when you are trying to build a machine learning model you need to be pretty sure whether your data is making sense or not. The main aim of exploratory data analysis is to obtain confidence in your data to an extent where you’re ready to engage a machine learning algorithm." }, { "code": null, "e": 1521, "s": 1503, "text": "Why do we do EDA?" }, { "code": null, "e": 1864, "s": 1521, "text": "Exploratory Data Analysis is a crucial step before you jump to machine learning or modeling your data. By doing this you can get to know whether the selected features are good enough to model, are all the features required, are there any correlations based on which we can either go back to the Data Preprocessing step or move on to modeling." }, { "code": null, "e": 1992, "s": 1864, "text": "Once EDA is complete and insights are drawn, its feature can be used for supervised and unsupervised machine learning modeling." }, { "code": null, "e": 2461, "s": 1992, "text": "In every machine learning workflow, the last step is Reporting or Providing the insights to the Stake Holders and as a Data Scientist you can explain every bit of code but you need to keep in mind the audience. By completing the EDA you will have many plots,heat-maps, frequency distribution, graphs, correlation matrix along with the hypothesis by which any individual can understand what your data is all about and what insights you got from exploring your data set." }, { "code": null, "e": 2517, "s": 2461, "text": "We have a saying “A picture is worth a thousand words”." }, { "code": null, "e": 2593, "s": 2517, "text": "I want to modify it for data scientist as “A Plot is worth a thousand rows”" }, { "code": null, "e": 2821, "s": 2593, "text": "In our Trip Example, we do all the exploration of the selected place based on which we will get the confidence to plan the trip and even share with our friends the insights we got regarding the place so that they can also join." }, { "code": null, "e": 2848, "s": 2821, "text": "What are the steps in EDA?" }, { "code": null, "e": 2959, "s": 2848, "text": "There are many steps for conducting Exploratory data analysis. I want to discuss regarding the below few steps" }, { "code": null, "e": 2979, "s": 2959, "text": "Description of data" }, { "code": null, "e": 3001, "s": 2979, "text": "Handling missing data" }, { "code": null, "e": 3019, "s": 3001, "text": "Handling outliers" }, { "code": null, "e": 3078, "s": 3019, "text": "Understanding relationships and new insights through plots" }, { "code": null, "e": 3102, "s": 3078, "text": "a) Description of data:" }, { "code": null, "e": 3503, "s": 3102, "text": "We need to know the different kinds of data and other statistics of our data before we can move on to the other steps. A good one is to start with the describe() function in python. In Pandas, we can apply function describe on a data frame which helps in generating descriptive statistics that summarize the central tendency, dispersion, and shape of a dataset’s distribution, excluding “NaN” values." }, { "code": null, "e": 3740, "s": 3503, "text": "For numeric data, the result’s index will include count, mean, std, min, max as well as lower, 50 and upper percentiles. By default, the lower percentile is 25 and the upper percentile is 75. The 50 percentile is the same as the median." }, { "code": null, "e": 3973, "s": 3740, "text": "For object data (e.g. strings or timestamps), the result’s index will include count, unique, top, and freq. The top is the most common value. Freq is the most common value frequency. Timestamps also include the first and last items." }, { "code": null, "e": 3999, "s": 3973, "text": "b) Handling missing data:" }, { "code": null, "e": 4576, "s": 3999, "text": "Data in the real world are rarely clean and homogeneous. Data can either be missing during data extraction or collection due to several reasons. Missing values need to be handled carefully because they reduce the quality of any of our performance metrics. It can also lead to wrong prediction or classification and can also cause a high bias for any given model being used. There are several options for handling missing values. However, the choice of what should be done is largely dependent on the nature of our data and the missing values. Below are some of the techniques:" }, { "code": null, "e": 4604, "s": 4576, "text": "Drop NULL or missing values" }, { "code": null, "e": 4624, "s": 4604, "text": "Fill Missing Values" }, { "code": null, "e": 4668, "s": 4624, "text": "Predict Missing values with an ML Algorithm" }, { "code": null, "e": 4701, "s": 4668, "text": "(i) Drop NULL or missing values:" }, { "code": null, "e": 4965, "s": 4701, "text": "This is the fastest and easiest step to handle missing values. However, it is not generally advised. This method reduces the quality of our model as it reduces sample size because it works by deleting all other observations where any of the variables are missing." }, { "code": null, "e": 4979, "s": 4965, "text": "Python code :" }, { "code": null, "e": 4997, "s": 4979, "text": " dataset.dropna()" }, { "code": null, "e": 5023, "s": 4997, "text": "(ii) Fill Missing Values:" }, { "code": null, "e": 5240, "s": 5023, "text": "This is the most common method of handling missing values. This is a process whereby missing values are replaced with a test statistic like mean, median or mode of the particular feature the missing value belongs to." }, { "code": null, "e": 5254, "s": 5240, "text": "Python code :" }, { "code": null, "e": 5320, "s": 5254, "text": "dataset[‘Column_name’]=dataset[‘Column_name’].fillna(mean_value)." }, { "code": null, "e": 5370, "s": 5320, "text": "(iii)Predict Missing values with an ML Algorithm:" }, { "code": null, "e": 5584, "s": 5370, "text": "This is by far one of the best and most efficient methods for handling missing data. Depending on the class of data that is missing, one can either use a regression or classification model to predict missing data." }, { "code": null, "e": 5606, "s": 5584, "text": "c) Handling outliers:" }, { "code": null, "e": 5844, "s": 5606, "text": "An outlier is something separate or different from the crowd. Outliers can be a result of a mistake during data collection or it can be just an indication of variance in your data. Some of the methods for detecting and handling outliers:" }, { "code": null, "e": 5853, "s": 5844, "text": "Box Plot" }, { "code": null, "e": 5866, "s": 5853, "text": "Scatter plot" }, { "code": null, "e": 5874, "s": 5866, "text": "Z-score" }, { "code": null, "e": 5900, "s": 5874, "text": "IQR(Inter-Quartile Range)" }, { "code": null, "e": 5914, "s": 5900, "text": "(i) Box Plot:" }, { "code": null, "e": 6356, "s": 5914, "text": "A box plot is a method for graphically depicting groups of numerical data through their quartiles. The box extends from the Q1 to Q3 quartile values of the data, with a line at the median (Q2). The whiskers extend from the edges of the box to show the range of the data. Outlier points are those past the end of the whiskers. Box plots show robust measures of location and spread as well as providing information about symmetry and outliers." }, { "code": null, "e": 6375, "s": 6356, "text": "(ii) Scatter plot:" }, { "code": null, "e": 6791, "s": 6375, "text": "A scatter plot is a mathematical diagram using Cartesian coordinates to display values for two variables for a set of data. The data are displayed as a collection of points, each having the value of one variable determining the position on the horizontal axis and the value of the other variable determining the position on the vertical axis. The points that are far from the population can be termed as an outlier." }, { "code": null, "e": 6806, "s": 6791, "text": "(iii) Z-score:" }, { "code": null, "e": 7351, "s": 6806, "text": "The Z-score is the signed number of standard deviations by which the value of an observation or data point is above the mean value of what is being observed or measured. While calculating the Z-score we re-scale and center the data and look for data points that are too far from zero. These data points which are way too far from zero will be treated as the outliers. In most of the cases, a threshold of 3 or -3 is used i.e if the Z-score value is greater than or less than 3 or -3 respectively, that data point will be identified as outliers." }, { "code": null, "e": 7364, "s": 7351, "text": "Python Code:" }, { "code": null, "e": 7398, "s": 7364, "text": "z = np.abs(stats.zscore(dataset))" }, { "code": null, "e": 7458, "s": 7398, "text": "Once we get the z-score we can fit our datset base on that." }, { "code": null, "e": 7471, "s": 7458, "text": "Python Code:" }, { "code": null, "e": 7510, "s": 7471, "text": "dataset = dataset[(z < 3).all(axis=1)]" }, { "code": null, "e": 7520, "s": 7510, "text": "(iv) IQR:" }, { "code": null, "e": 7693, "s": 7520, "text": "The interquartile range (IQR) is a measure of statistical dispersion, being equal to the difference between 75th and 25th percentiles, or between upper and lower quartiles." }, { "code": null, "e": 7708, "s": 7693, "text": "IQR = Q3 − Q1." }, { "code": null, "e": 7721, "s": 7708, "text": "Python Code:" }, { "code": null, "e": 7789, "s": 7721, "text": "Q1 = dataset.quantile(0.25)Q3 = dataset.quantile(0.75)IQR = Q3 — Q1" }, { "code": null, "e": 7982, "s": 7789, "text": "Once we have IQR scores below code will give an output with some true and false values. The data point where we have False means values are valid and True indicates the presence of an outlier." }, { "code": null, "e": 7995, "s": 7982, "text": "Python Code:" }, { "code": null, "e": 8067, "s": 7995, "text": "print(boston_df_o1 < (Q1–1.5 * IQR)) |(boston_df_o1 > (Q3 + 1.5 * IQR))" }, { "code": null, "e": 8131, "s": 8067, "text": "d) Understanding relationships and new insights through plots :" }, { "code": null, "e": 8260, "s": 8131, "text": "We can get many relations in our data by visualizing our data set.Let’s go through some techniques in-order to see the insights." }, { "code": null, "e": 8270, "s": 8260, "text": "Histogram" }, { "code": null, "e": 8280, "s": 8270, "text": "Heat Maps" }, { "code": null, "e": 8295, "s": 8280, "text": "(i) Histogram:" }, { "code": null, "e": 8505, "s": 8295, "text": "A histogram is a great tool for quickly assessing a probability distribution that is easily understood by almost any audience. Python offers a handful of different options for building and plotting histograms." }, { "code": null, "e": 8521, "s": 8505, "text": "(ii) Heat Maps:" }, { "code": null, "e": 9040, "s": 8521, "text": "The Heat Map procedure shows the distribution of a quantitative variable over all combinations of 2 categorical factors. If one of the 2 factors represents time, then the evolution of the variable can be easily viewed using the map. A gradient color scale is used to represent the values of the quantitative variable. The correlation between two random variables is a number that runs from -1 through 0 to +1 and indicates a strong inverse relationship, no relationship, and a strong direct relationship, respectively." }, { "code": null, "e": 9073, "s": 9040, "text": "What are the tools used for EDA?" }, { "code": null, "e": 9319, "s": 9073, "text": "There are plenty of open-source tools exist which automate the steps of predictive modeling like data cleaning, data visualization. Some of them are also quite popular like Excel, Tableau, Qlikview, Weka and many more apart from the programming." }, { "code": null, "e": 9425, "s": 9319, "text": "In programming, we can accomplish EDA using Python, R, SAS. Some of the important packages in Python are:" }, { "code": null, "e": 9432, "s": 9425, "text": "Pandas" }, { "code": null, "e": 9438, "s": 9432, "text": "Numpy" }, { "code": null, "e": 9449, "s": 9438, "text": "Matplotlib" }, { "code": null, "e": 9457, "s": 9449, "text": "Seaborn" }, { "code": null, "e": 9463, "s": 9457, "text": "Bokeh" }, { "code": null, "e": 9496, "s": 9463, "text": "What happens if we don’t do EDA?" }, { "code": null, "e": 10053, "s": 9496, "text": "Many Data Scientists will be in a hurry to get to the machine learning stage, some either entirely skip exploratory process or do a very minimal job. This is a mistake with many implications, including generating inaccurate models, generating accurate models but on the wrong data, not creating the right types of variables in data preparation, and using resources inefficiently because of realizing only after generating models that perhaps the data is skewed, or has outliers, or has too many missing values, or finding that some values are inconsistent." } ]
SQLAlchemy ORM - Eager Loading
Eager load reduces the number of queries. SQLAlchemy offers eager loading functions invoked via query options which give additional instructions to the Query. These options determine how to load various attributes via the Query.options() method. We want that Customer.invoices should load eagerly. The orm.subqueryload() option gives a second SELECT statement that fully loads the collections associated with the results just loaded. The name “subquery” causes the SELECT statement to be constructed directly via the Query re-used and embedded as a subquery into a SELECT against the related table. from sqlalchemy.orm import subqueryload c1 = session.query(Customer).options(subqueryload(Customer.invoices)).filter_by(name = 'Govind Pant').one() This results in the following two SQL expressions − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE customers.name = ? ('Govind Pant',) SELECT invoices.id AS invoices_id, invoices.custid AS invoices_custid, invoices.invno AS invoices_invno, invoices.amount AS invoices_amount, anon_1.customers_id AS anon_1_customers_id FROM ( SELECT customers.id AS customers_id FROM customers WHERE customers.name = ?) AS anon_1 JOIN invoices ON anon_1.customers_id = invoices.custid ORDER BY anon_1.customers_id, invoices.id 2018-06-25 18:24:47,479 INFO sqlalchemy.engine.base.Engine ('Govind Pant',) To access the data from two tables, we can use the below program − print (c1.name, c1.address, c1.email) for x in c1.invoices: print ("Invoice no : {}, Amount : {}".format(x.invno, x.amount)) The output of the above program is as follows − Govind Pant Gulmandi Aurangabad gpant@gmail.com Invoice no : 3, Amount : 10000 Invoice no : 4, Amount : 5000 The other function is called orm.joinedload(). This emits a LEFT OUTER JOIN. Lead object as well as the related object or collection is loaded in one step. from sqlalchemy.orm import joinedload c1 = session.query(Customer).options(joinedload(Customer.invoices)).filter_by(name='Govind Pant').one() This emits following expression giving same output as above − SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email, invoices_1.id AS invoices_1_id, invoices_1.custid AS invoices_1_custid, invoices_1.invno AS invoices_1_invno, invoices_1.amount AS invoices_1_amount FROM customers LEFT OUTER JOIN invoices AS invoices_1 ON customers.id = invoices_1.custid WHERE customers.name = ? ORDER BY invoices_1.id ('Govind Pant',) The OUTER JOIN resulted in two rows, but it gives one instance of Customer back. This is because Query applies a “uniquing” strategy, based on object identity, to the returned entities. Joined eager loading can be applied without affecting the query results. The subqueryload() is more appropriate for loading related collections while joinedload() is better suited for many-to-one relationship. 21 Lectures 1.5 hours Jack Chan Print Add Notes Bookmark this page
[ { "code": null, "e": 2586, "s": 2340, "text": "Eager load reduces the number of queries. SQLAlchemy offers eager loading functions invoked via query options which give additional instructions to the Query. These options determine how to load various attributes via the Query.options() method." }, { "code": null, "e": 2939, "s": 2586, "text": "We want that Customer.invoices should load eagerly. The orm.subqueryload() option gives a second SELECT statement that fully loads the collections associated with the results just loaded. The name “subquery” causes the SELECT statement to be constructed directly via the Query re-used and embedded as a subquery into a SELECT against the related table." }, { "code": null, "e": 3087, "s": 2939, "text": "from sqlalchemy.orm import subqueryload\nc1 = session.query(Customer).options(subqueryload(Customer.invoices)).filter_by(name = 'Govind Pant').one()" }, { "code": null, "e": 3139, "s": 3087, "text": "This results in the following two SQL expressions −" }, { "code": null, "e": 3825, "s": 3139, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email\nFROM customers\nWHERE customers.name = ?\n('Govind Pant',)\n\nSELECT invoices.id \nAS invoices_id, invoices.custid \nAS invoices_custid, invoices.invno \nAS invoices_invno, invoices.amount \nAS invoices_amount, anon_1.customers_id \nAS anon_1_customers_id\nFROM (\n SELECT customers.id \n AS customers_id\n FROM customers\n WHERE customers.name = ?) \n \nAS anon_1 \nJOIN invoices \nON anon_1.customers_id = invoices.custid \nORDER BY anon_1.customers_id, invoices.id 2018-06-25 18:24:47,479 \nINFO sqlalchemy.engine.base.Engine ('Govind Pant',)" }, { "code": null, "e": 3892, "s": 3825, "text": "To access the data from two tables, we can use the below program −" }, { "code": null, "e": 4021, "s": 3892, "text": "print (c1.name, c1.address, c1.email)\n\nfor x in c1.invoices:\n print (\"Invoice no : {}, Amount : {}\".format(x.invno, x.amount))" }, { "code": null, "e": 4069, "s": 4021, "text": "The output of the above program is as follows −" }, { "code": null, "e": 4179, "s": 4069, "text": "Govind Pant Gulmandi Aurangabad gpant@gmail.com\nInvoice no : 3, Amount : 10000\nInvoice no : 4, Amount : 5000\n" }, { "code": null, "e": 4335, "s": 4179, "text": "The other function is called orm.joinedload(). This emits a LEFT OUTER JOIN. Lead object as well as the related object or collection is loaded in one step." }, { "code": null, "e": 4477, "s": 4335, "text": "from sqlalchemy.orm import joinedload\nc1 = session.query(Customer).options(joinedload(Customer.invoices)).filter_by(name='Govind Pant').one()" }, { "code": null, "e": 4539, "s": 4477, "text": "This emits following expression giving same output as above −" }, { "code": null, "e": 5003, "s": 4539, "text": "SELECT customers.id \nAS customers_id, customers.name \nAS customers_name, customers.address \nAS customers_address, customers.email \nAS customers_email, invoices_1.id \nAS invoices_1_id, invoices_1.custid \nAS invoices_1_custid, invoices_1.invno \nAS invoices_1_invno, invoices_1.amount \nAS invoices_1_amount\n\nFROM customers \nLEFT OUTER JOIN invoices \nAS invoices_1 \nON customers.id = invoices_1.custid\n\nWHERE customers.name = ? ORDER BY invoices_1.id\n('Govind Pant',)" }, { "code": null, "e": 5262, "s": 5003, "text": "The OUTER JOIN resulted in two rows, but it gives one instance of Customer back. This is because Query applies a “uniquing” strategy, based on object identity, to the returned entities. Joined eager loading can be applied without affecting the query results." }, { "code": null, "e": 5399, "s": 5262, "text": "The subqueryload() is more appropriate for loading related collections while joinedload() is better suited for many-to-one relationship." }, { "code": null, "e": 5434, "s": 5399, "text": "\n 21 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5445, "s": 5434, "text": " Jack Chan" }, { "code": null, "e": 5452, "s": 5445, "text": " Print" }, { "code": null, "e": 5463, "s": 5452, "text": " Add Notes" } ]
Handling Big Datasets for Machine Learning | by Matthew Stewart, PhD Researcher | Towards Data Science
More than 2.5 quintillion bytes of data are created each day. 90% of the data in the world was generated in the past two years. The prevalence of data will only increase, so we need to learn how to deal with such large data. “Big Data is like teenage sex: everyone talks about it, nobody really knows how to do it, everyone thinks everyone else is doing it, so everyone claims they are doing it.” — Dan Ariely Imagine downloading a dataset full of all the Tweets ever written, or the data of all the 2.3 billion people on Facebook, or even, the data for every webpage that exists on the Internet. How do you analyze such a dataset? This is not an isolated problem that only hits the largest tech companies. In the current age, datasets are already becoming larger than most computers can handle. I regularly work with satellite data and this can easily be in the Terabyte range — too large to even fit on the hard drive of my computer, let alone to process it in a reasonable amount of time. Here are some eye-opening statistics regarding big data: More than 16 million text messages are sent every minute More than 100 million spam emails are sent every minute Every minute, there are more than a million tinder swipes Every day, more than a billion photos are uploaded to Google Photos Storing this data is one thing, but what about processing it and developing machine learning algorithms to work with it? In this article, we will discuss how to easily create a scalable and parallelized machine learning platform on the cloud to process large-scale data. This can be used for research, commercial, or non-commercial purposes and can be done with minimal cost compared to developing your own supercomputer. To develop a very robust and high-performance parallel cluster on the cloud (this can also be used on a local machine for performance enhancement) we will delve into the following topics: Environment Setup Parallelization with Dask and Kubernetes Dask Cloud Deployment Example Cloud Deployment on AWS This post will be based on the contents of the following GitHub repository, that can be found here. All of the commands required for setting up the machine learning platform on the cloud can be found in the markdown file here. This is based on a tutorial by the Institute for Applied Computational Science at Harvard University. Environment Setup — Dockers and Containers If you only read one part of this post, let it be this part. When people set up their machine learning environment, typically they install everything on the directly on their operating system. Oftentimes, this is fine, and then you try to download something like PyTorch, TensorFlow, or Keras and everything explodes and you spend hours on Stack Overflow trying to get things to work. I implore you not to work like this, for your own sake. This problem typically occurs from dependencies or co-dependencies of certain packages on specific versions of other packages. Often, you do not need half of these packages for your work. It would make more sense to start from a clean slate and only install the versions and dependencies that are required for the task at hand. This will ultimately save you time and stress. If you are using Anaconda, it is very easy and efficient to separate these into isolated ‘containers’ such that they can all run without causing problems. These containers are called Conda environments. Conda is a package manager for Python You can think of these environments as different computers that do not know about the existence of each other. When I create a new environment, I start with a blank slate and need to install packages again. The great part about this is that you do not actually download the packages twice when doing this, a pointer is created which points to the specific version of the package you want to install that is already downloaded on your computer. This may seem pointless unless you have had dependency issues before on your computer, but I can promise you it is worth knowing about this. Another useful feature is that you can install all the packages you like in just one line by using a YAML (.yml) file. This is a file that tells the environment what packages you want to install and what dependencies are required to be downloaded. You do not need to write this file, it can be exported with one line of code from an environment where you already have all the required packages — pretty neat right? All of the required commands are shown in the Gist below. Here is an example of what the YAML file looks like when the conda env export > environment.yml command is run. There is another good reason for separating things into environments like this. If I want to get reproducible results for data analysis that I am doing, it can widely depend on the versions of different packages and also the operating system that you are working on. By creating environment.yml files that contain all of the dependencies, it is easier for someone to reproduce your results. So what did we do when we created our Conda environment? We essentially isolated it from the rest of our system. However, what if we have additional things that we want to work with the environments that are not just Python packages. In this case, we use Docker to create containers. If your application: uses a server (for example a database server with preloaded data), AND you want to distribute this server and its data together with your application and its Python environment to others (for instance to a fellow developer or to a client), you can “containerize” the whole thing using Docker. In this case, all these components will be encapsulated in a Docker container: The application itself, The Conda environment that can run your application (so a compatible Python version and packages), The local server or service (for example: a database server and a web server) required to run the application I admit the concept behind Docker and containers is a bit confusing. Building a docker image is not a trivial task. Fortunately, however, the Jupyter folks created repo2docker for this. repo2docker takes a GitHub repository and automatically makes a docker image and uploads it to the docker image repository for you. This can be done using one line of code. After running the above code, you should have some code pop up in the terminal that looks like the following: Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://0.0.0.0:36511/?token=f94f8fabb92e22f5bfab116c382b4707fc2cade56ad1ace0 Simply copy and paste the URL in your browser and you then have access to your docker image and can get going! You can read more about using repo2docker here. Another really useful thing to use is binder. Binder builds on repo2docker to provide a service where you provide a GitHub repository, and it gives you a working JupyterHub where you can “publish” your project, demo, etc. The GitHub repository associated with this tutorial can be run on binder by clicking on the link in the ReadMe section. You can read more about using Binder here. Parallelization with Dask and Kubernetes It has taken us quite a while to get to the parallelization part of the tutorial, but the previous steps were necessary to get here. Let’s now dive into using Dask and Kubernetes. Dask - a library for parallel computing in Python Kubernetes - an open-source container orchestration system for automating application deployment, scaling, and management. Dask has two parts associated with it: [1] Dynamic task scheduling optimized for computation like Airflow. [2] “Big Data” collections like parallel (Numpy) arrays, (Pandas) dataframes, and lists. Dask has only been around for a couple of years but is gradually growing momentum due to the popularity of Python for machine learning applications. Dask allows scaling up (1000 core cluster) of Python applications so that they can be processed much faster than on a regular laptop. I would refer anyone who is interested in working with Dask to the GitHub repository by Tom Augspurger (one of the main creators of Dask), which can be found here. So we have talked about Dask, where does Kubernetes come in here? If we run Dask on our laptop, it allows us to distribute our code to multiple cores at once, but it does not help us run the code on multiple systems at the same time. We have run it locally. Ideally, we want to run on a cloud provisioned cluster, and we’d like this cluster to be self-repairing — that is, we’d like our code to respond to failures and expand onto more machines if we need them. We need a cluster manager. Kubernetes is a cluster manager. We can think of it like being an operating system for the cluster. It provides service discovery, scaling, load-balancing, and is self-healing. Kubernetes think of applications as stateless, and movable from one machine to another to enable better resource utilization. There is a controlling master node on which the cluster operating system runs, and worker nodes which perform the bulk of the work. If a node (computer associated with the cluster) loses connection or breaks, the master node will assign the work to someone new, just like your boss would if you stopped working. The master and worker nodes consist of several pieces of software which allow it to perform its task. It gets pretty complicated so I will quickly give a high-level overview. Master Node: API server, communication between master node and user (using kubectl) Scheduler, assigns a worker node to each application Controller Manager, performs cluster level functions, such as replicating components, keeping track of worker nodes, handling node failures etcd, a reliable distributed data store that persistently stores the cluster configuration (which worker node is doing what at a given time). Worker Node: Docker, to run your containers Package your app's components into 1 or more docker images, and push them to a registry Kubelet, which talks to the API server and manages containers on its node kube-proxy, which load-balances network traffic between application components Doing all of this is great, but it isn’t particularly helpful unless we have 100 computers at our disposal to make use of the power that Kubernetes and Dask afford us. Enter the cloud. Dask Cloud Deployment If you want to run Dask to speed up your machine learning code in Python, Kubernetes is the recommended cluster manager. This can be done on your local machine using Minikube or on any of the 3 major cloud providers, Microsoft Azure, Google Compute Cloud, or Amazon Web Services. You are probably familiar with cloud computing since it is pretty much everywhere these days. It is now very common for companies to have all of their computing infrastructure on the cloud, since this reduces their capital expenditure on computing equipment and moves it to operational expenditure, requires less maintenance and also significantly reduces the running cost. Unless you are working with classified information or have very strict regulatory requirements, you can probably get away with running things on the cloud. Using the cloud allows you to leverage the collective performance of several machines to perform the same task. For example, if you are performing hyperparameter optimization on a neural network and it will need to rerun the model 10,000 times to get the best parameter selection (a fairly common problem) then it would be nonsensical to run it on one computer if it will take 2 weeks. If you can run this same model on 100 computers you will likely finish the task in a few hours. I hope I have made a good case for why you should make use of the cloud, but be aware that it can get quite expensive if you use very powerful machines (especially if you do not turn them off after using them!) To set up the environment on the cloud, you must do the following: Set up a Kubernetes clusterSet up Helm (a package manager for Kubernetes, it is like a Homebrew for Kubernetes cluster)Install Dask. Set up a Kubernetes cluster Set up Helm (a package manager for Kubernetes, it is like a Homebrew for Kubernetes cluster) Install Dask. First run the following helm repo update and then helm install stable/dask See https://docs.dask.org/en/latest/setup/kubernetes-helm.html for all the details. Deep Learning on the Cloud There are several useful tools which are available for building deep learning algorithms with Kubernetes and Dask. For example, TensorFlow can be put on the cloud using tf.distributed of kubeflow. The parallelism can be trivially used during grid optimization since different models can be run on each worker node. Examples can be found on the GitHub repository here. What do you use? For my own research (I am an environmental scientist) and in my consulting work (machine learning consultant) I regularly use either JupyterHub, a Kubernetes cluster with Dask on Harvard’s supercomputer Odyssey, or I will run the same infrastructure on AWS (no real prejudice against Azure or the Google Cloud, I was just taught how to use AWS first). Example Cloud Deployment on AWS In this section, I will run through the setup of a Kubernetes Cluster running Dask on AWS. The first thing you need to do is set up an account on AWS, you will not be able to run the following lines of code unless you already have an account. First, we download the AWS command line interface and configure it with our private key supplied by AWS. We then install Amazon’s Elastic Container Service (EKS) for Kubernetes using the brew commands. pip install awscliaws configurebrew tap weaveworks/tapbrew install weaveworks/tap/eksctl Creating a Kubernetes cluster is now ludicrously simple, we only need to run one command, but you should specify the cluster name, the number of nodes, and the region you are in (in this case I am in Boston so I choose us-east-1 ) and then run the command. eksctl create cluster --name=cluster-1 --nodes=4 --region=us-east-1 Now we must configure the cluster with the following commands: kubectl get nodeskubectl --namespace kube-system create sa tillerkubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tiller Now we set up Helm and Dask on the cluster helm init --service-account tiller Wait two minutes for this to complete and then we can install Dask. helm versionhelm repo updatehelm install stable/daskhelm status agile-newthelm listhelm upgrade agile-newt stable/dask -f config.yamlhelm status agile-newt A few more Kubernetes commands. kubectl get podskubectl get services For more details and a shell, you will need a command like this. Your exact pod names will be different. kubectl get pod agile-newt-dask-jupyter-54f86bfdd7-jdb5pkubectl exec -it agile-newt-dask-jupyter-54f86bfdd7-jdb5p -- /bin/bash Once you are in the cluster, you can clone the GitHub repository and watch Dask go! Kaggle Rossman Competition I recommend that once you have got the Dask cloud deployment up and running you try running the rossman_kaggle.ipynb . This is example code from the Kaggle Rossman competition, which allowed users to use any data they wanted to try and predict pharmacy sales in Europe. The competition was run in 2015. The steps in this notebook run you through how to set up your coding environment for a multilayer perceptron in order to apply it to a parallel cluster and then perform hyperparameter optimization. All of the steps in this code are split into functions which are then run in an sklearn pipeline (this is the recommended way to run large machine learning programs). There are several other examples on the repository that you can run on the parallel cluster and play with. Also, feel free to clone the repository and tinker with it as much as you like. Where can I learn more? To learn more about Dask, check out the following links: github.com docs.dask.org To learn more about Dask with Kubernetes: github.com kubernetes.dask.org To learn more about Helm: docs.dask.org If you are struggling to work through any of the above steps, there are multiple other walkthroughs that go through the specifics in more detail: ramhiser.com zonca.github.io For setting up the cluster on the Google Cloud (sadly could not find one for Microsoft Azure) check these links out: github.com github.com Now you should have a working parallel cluster on which to perform machine learning on big data or for big compute tasks! Thanks for reading! 🙏 For updates on new blog posts and extra content, sign up for my newsletter.
[ { "code": null, "e": 397, "s": 172, "text": "More than 2.5 quintillion bytes of data are created each day. 90% of the data in the world was generated in the past two years. The prevalence of data will only increase, so we need to learn how to deal with such large data." }, { "code": null, "e": 582, "s": 397, "text": "“Big Data is like teenage sex: everyone talks about it, nobody really knows how to do it, everyone thinks everyone else is doing it, so everyone claims they are doing it.” — Dan Ariely" }, { "code": null, "e": 804, "s": 582, "text": "Imagine downloading a dataset full of all the Tweets ever written, or the data of all the 2.3 billion people on Facebook, or even, the data for every webpage that exists on the Internet. How do you analyze such a dataset?" }, { "code": null, "e": 1221, "s": 804, "text": "This is not an isolated problem that only hits the largest tech companies. In the current age, datasets are already becoming larger than most computers can handle. I regularly work with satellite data and this can easily be in the Terabyte range — too large to even fit on the hard drive of my computer, let alone to process it in a reasonable amount of time. Here are some eye-opening statistics regarding big data:" }, { "code": null, "e": 1278, "s": 1221, "text": "More than 16 million text messages are sent every minute" }, { "code": null, "e": 1334, "s": 1278, "text": "More than 100 million spam emails are sent every minute" }, { "code": null, "e": 1392, "s": 1334, "text": "Every minute, there are more than a million tinder swipes" }, { "code": null, "e": 1460, "s": 1392, "text": "Every day, more than a billion photos are uploaded to Google Photos" }, { "code": null, "e": 1731, "s": 1460, "text": "Storing this data is one thing, but what about processing it and developing machine learning algorithms to work with it? In this article, we will discuss how to easily create a scalable and parallelized machine learning platform on the cloud to process large-scale data." }, { "code": null, "e": 1882, "s": 1731, "text": "This can be used for research, commercial, or non-commercial purposes and can be done with minimal cost compared to developing your own supercomputer." }, { "code": null, "e": 2070, "s": 1882, "text": "To develop a very robust and high-performance parallel cluster on the cloud (this can also be used on a local machine for performance enhancement) we will delve into the following topics:" }, { "code": null, "e": 2088, "s": 2070, "text": "Environment Setup" }, { "code": null, "e": 2129, "s": 2088, "text": "Parallelization with Dask and Kubernetes" }, { "code": null, "e": 2151, "s": 2129, "text": "Dask Cloud Deployment" }, { "code": null, "e": 2183, "s": 2151, "text": "Example Cloud Deployment on AWS" }, { "code": null, "e": 2512, "s": 2183, "text": "This post will be based on the contents of the following GitHub repository, that can be found here. All of the commands required for setting up the machine learning platform on the cloud can be found in the markdown file here. This is based on a tutorial by the Institute for Applied Computational Science at Harvard University." }, { "code": null, "e": 2555, "s": 2512, "text": "Environment Setup — Dockers and Containers" }, { "code": null, "e": 2616, "s": 2555, "text": "If you only read one part of this post, let it be this part." }, { "code": null, "e": 2996, "s": 2616, "text": "When people set up their machine learning environment, typically they install everything on the directly on their operating system. Oftentimes, this is fine, and then you try to download something like PyTorch, TensorFlow, or Keras and everything explodes and you spend hours on Stack Overflow trying to get things to work. I implore you not to work like this, for your own sake." }, { "code": null, "e": 3371, "s": 2996, "text": "This problem typically occurs from dependencies or co-dependencies of certain packages on specific versions of other packages. Often, you do not need half of these packages for your work. It would make more sense to start from a clean slate and only install the versions and dependencies that are required for the task at hand. This will ultimately save you time and stress." }, { "code": null, "e": 3612, "s": 3371, "text": "If you are using Anaconda, it is very easy and efficient to separate these into isolated ‘containers’ such that they can all run without causing problems. These containers are called Conda environments. Conda is a package manager for Python" }, { "code": null, "e": 4056, "s": 3612, "text": "You can think of these environments as different computers that do not know about the existence of each other. When I create a new environment, I start with a blank slate and need to install packages again. The great part about this is that you do not actually download the packages twice when doing this, a pointer is created which points to the specific version of the package you want to install that is already downloaded on your computer." }, { "code": null, "e": 4670, "s": 4056, "text": "This may seem pointless unless you have had dependency issues before on your computer, but I can promise you it is worth knowing about this. Another useful feature is that you can install all the packages you like in just one line by using a YAML (.yml) file. This is a file that tells the environment what packages you want to install and what dependencies are required to be downloaded. You do not need to write this file, it can be exported with one line of code from an environment where you already have all the required packages — pretty neat right? All of the required commands are shown in the Gist below." }, { "code": null, "e": 4782, "s": 4670, "text": "Here is an example of what the YAML file looks like when the conda env export > environment.yml command is run." }, { "code": null, "e": 5173, "s": 4782, "text": "There is another good reason for separating things into environments like this. If I want to get reproducible results for data analysis that I am doing, it can widely depend on the versions of different packages and also the operating system that you are working on. By creating environment.yml files that contain all of the dependencies, it is easier for someone to reproduce your results." }, { "code": null, "e": 5457, "s": 5173, "text": "So what did we do when we created our Conda environment? We essentially isolated it from the rest of our system. However, what if we have additional things that we want to work with the environments that are not just Python packages. In this case, we use Docker to create containers." }, { "code": null, "e": 5478, "s": 5457, "text": "If your application:" }, { "code": null, "e": 5549, "s": 5478, "text": "uses a server (for example a database server with preloaded data), AND" }, { "code": null, "e": 5718, "s": 5549, "text": "you want to distribute this server and its data together with your application and its Python environment to others (for instance to a fellow developer or to a client)," }, { "code": null, "e": 5771, "s": 5718, "text": "you can “containerize” the whole thing using Docker." }, { "code": null, "e": 5850, "s": 5771, "text": "In this case, all these components will be encapsulated in a Docker container:" }, { "code": null, "e": 5874, "s": 5850, "text": "The application itself," }, { "code": null, "e": 5973, "s": 5874, "text": "The Conda environment that can run your application (so a compatible Python version and packages)," }, { "code": null, "e": 6083, "s": 5973, "text": "The local server or service (for example: a database server and a web server) required to run the application" }, { "code": null, "e": 6442, "s": 6083, "text": "I admit the concept behind Docker and containers is a bit confusing. Building a docker image is not a trivial task. Fortunately, however, the Jupyter folks created repo2docker for this. repo2docker takes a GitHub repository and automatically makes a docker image and uploads it to the docker image repository for you. This can be done using one line of code." }, { "code": null, "e": 6552, "s": 6442, "text": "After running the above code, you should have some code pop up in the terminal that looks like the following:" }, { "code": null, "e": 6737, "s": 6552, "text": "Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://0.0.0.0:36511/?token=f94f8fabb92e22f5bfab116c382b4707fc2cade56ad1ace0" }, { "code": null, "e": 6896, "s": 6737, "text": "Simply copy and paste the URL in your browser and you then have access to your docker image and can get going! You can read more about using repo2docker here." }, { "code": null, "e": 7238, "s": 6896, "text": "Another really useful thing to use is binder. Binder builds on repo2docker to provide a service where you provide a GitHub repository, and it gives you a working JupyterHub where you can “publish” your project, demo, etc. The GitHub repository associated with this tutorial can be run on binder by clicking on the link in the ReadMe section." }, { "code": null, "e": 7281, "s": 7238, "text": "You can read more about using Binder here." }, { "code": null, "e": 7322, "s": 7281, "text": "Parallelization with Dask and Kubernetes" }, { "code": null, "e": 7502, "s": 7322, "text": "It has taken us quite a while to get to the parallelization part of the tutorial, but the previous steps were necessary to get here. Let’s now dive into using Dask and Kubernetes." }, { "code": null, "e": 7552, "s": 7502, "text": "Dask - a library for parallel computing in Python" }, { "code": null, "e": 7675, "s": 7552, "text": "Kubernetes - an open-source container orchestration system for automating application deployment, scaling, and management." }, { "code": null, "e": 7714, "s": 7675, "text": "Dask has two parts associated with it:" }, { "code": null, "e": 7782, "s": 7714, "text": "[1] Dynamic task scheduling optimized for computation like Airflow." }, { "code": null, "e": 7871, "s": 7782, "text": "[2] “Big Data” collections like parallel (Numpy) arrays, (Pandas) dataframes, and lists." }, { "code": null, "e": 8154, "s": 7871, "text": "Dask has only been around for a couple of years but is gradually growing momentum due to the popularity of Python for machine learning applications. Dask allows scaling up (1000 core cluster) of Python applications so that they can be processed much faster than on a regular laptop." }, { "code": null, "e": 8318, "s": 8154, "text": "I would refer anyone who is interested in working with Dask to the GitHub repository by Tom Augspurger (one of the main creators of Dask), which can be found here." }, { "code": null, "e": 8807, "s": 8318, "text": "So we have talked about Dask, where does Kubernetes come in here? If we run Dask on our laptop, it allows us to distribute our code to multiple cores at once, but it does not help us run the code on multiple systems at the same time. We have run it locally. Ideally, we want to run on a cloud provisioned cluster, and we’d like this cluster to be self-repairing — that is, we’d like our code to respond to failures and expand onto more machines if we need them. We need a cluster manager." }, { "code": null, "e": 9422, "s": 8807, "text": "Kubernetes is a cluster manager. We can think of it like being an operating system for the cluster. It provides service discovery, scaling, load-balancing, and is self-healing. Kubernetes think of applications as stateless, and movable from one machine to another to enable better resource utilization. There is a controlling master node on which the cluster operating system runs, and worker nodes which perform the bulk of the work. If a node (computer associated with the cluster) loses connection or breaks, the master node will assign the work to someone new, just like your boss would if you stopped working." }, { "code": null, "e": 9597, "s": 9422, "text": "The master and worker nodes consist of several pieces of software which allow it to perform its task. It gets pretty complicated so I will quickly give a high-level overview." }, { "code": null, "e": 9610, "s": 9597, "text": "Master Node:" }, { "code": null, "e": 9681, "s": 9610, "text": "API server, communication between master node and user (using kubectl)" }, { "code": null, "e": 9734, "s": 9681, "text": "Scheduler, assigns a worker node to each application" }, { "code": null, "e": 9874, "s": 9734, "text": "Controller Manager, performs cluster level functions, such as replicating components, keeping track of worker nodes, handling node failures" }, { "code": null, "e": 10016, "s": 9874, "text": "etcd, a reliable distributed data store that persistently stores the cluster configuration (which worker node is doing what at a given time)." }, { "code": null, "e": 10029, "s": 10016, "text": "Worker Node:" }, { "code": null, "e": 10060, "s": 10029, "text": "Docker, to run your containers" }, { "code": null, "e": 10148, "s": 10060, "text": "Package your app's components into 1 or more docker images, and push them to a registry" }, { "code": null, "e": 10222, "s": 10148, "text": "Kubelet, which talks to the API server and manages containers on its node" }, { "code": null, "e": 10301, "s": 10222, "text": "kube-proxy, which load-balances network traffic between application components" }, { "code": null, "e": 10469, "s": 10301, "text": "Doing all of this is great, but it isn’t particularly helpful unless we have 100 computers at our disposal to make use of the power that Kubernetes and Dask afford us." }, { "code": null, "e": 10486, "s": 10469, "text": "Enter the cloud." }, { "code": null, "e": 10508, "s": 10486, "text": "Dask Cloud Deployment" }, { "code": null, "e": 10788, "s": 10508, "text": "If you want to run Dask to speed up your machine learning code in Python, Kubernetes is the recommended cluster manager. This can be done on your local machine using Minikube or on any of the 3 major cloud providers, Microsoft Azure, Google Compute Cloud, or Amazon Web Services." }, { "code": null, "e": 11318, "s": 10788, "text": "You are probably familiar with cloud computing since it is pretty much everywhere these days. It is now very common for companies to have all of their computing infrastructure on the cloud, since this reduces their capital expenditure on computing equipment and moves it to operational expenditure, requires less maintenance and also significantly reduces the running cost. Unless you are working with classified information or have very strict regulatory requirements, you can probably get away with running things on the cloud." }, { "code": null, "e": 11800, "s": 11318, "text": "Using the cloud allows you to leverage the collective performance of several machines to perform the same task. For example, if you are performing hyperparameter optimization on a neural network and it will need to rerun the model 10,000 times to get the best parameter selection (a fairly common problem) then it would be nonsensical to run it on one computer if it will take 2 weeks. If you can run this same model on 100 computers you will likely finish the task in a few hours." }, { "code": null, "e": 12011, "s": 11800, "text": "I hope I have made a good case for why you should make use of the cloud, but be aware that it can get quite expensive if you use very powerful machines (especially if you do not turn them off after using them!)" }, { "code": null, "e": 12078, "s": 12011, "text": "To set up the environment on the cloud, you must do the following:" }, { "code": null, "e": 12211, "s": 12078, "text": "Set up a Kubernetes clusterSet up Helm (a package manager for Kubernetes, it is like a Homebrew for Kubernetes cluster)Install Dask." }, { "code": null, "e": 12239, "s": 12211, "text": "Set up a Kubernetes cluster" }, { "code": null, "e": 12332, "s": 12239, "text": "Set up Helm (a package manager for Kubernetes, it is like a Homebrew for Kubernetes cluster)" }, { "code": null, "e": 12346, "s": 12332, "text": "Install Dask." }, { "code": null, "e": 12370, "s": 12346, "text": "First run the following" }, { "code": null, "e": 12387, "s": 12370, "text": "helm repo update" }, { "code": null, "e": 12396, "s": 12387, "text": "and then" }, { "code": null, "e": 12421, "s": 12396, "text": "helm install stable/dask" }, { "code": null, "e": 12505, "s": 12421, "text": "See https://docs.dask.org/en/latest/setup/kubernetes-helm.html for all the details." }, { "code": null, "e": 12532, "s": 12505, "text": "Deep Learning on the Cloud" }, { "code": null, "e": 12900, "s": 12532, "text": "There are several useful tools which are available for building deep learning algorithms with Kubernetes and Dask. For example, TensorFlow can be put on the cloud using tf.distributed of kubeflow. The parallelism can be trivially used during grid optimization since different models can be run on each worker node. Examples can be found on the GitHub repository here." }, { "code": null, "e": 12917, "s": 12900, "text": "What do you use?" }, { "code": null, "e": 13269, "s": 12917, "text": "For my own research (I am an environmental scientist) and in my consulting work (machine learning consultant) I regularly use either JupyterHub, a Kubernetes cluster with Dask on Harvard’s supercomputer Odyssey, or I will run the same infrastructure on AWS (no real prejudice against Azure or the Google Cloud, I was just taught how to use AWS first)." }, { "code": null, "e": 13301, "s": 13269, "text": "Example Cloud Deployment on AWS" }, { "code": null, "e": 13544, "s": 13301, "text": "In this section, I will run through the setup of a Kubernetes Cluster running Dask on AWS. The first thing you need to do is set up an account on AWS, you will not be able to run the following lines of code unless you already have an account." }, { "code": null, "e": 13746, "s": 13544, "text": "First, we download the AWS command line interface and configure it with our private key supplied by AWS. We then install Amazon’s Elastic Container Service (EKS) for Kubernetes using the brew commands." }, { "code": null, "e": 13836, "s": 13746, "text": "pip install awscliaws configurebrew tap weaveworks/tapbrew install weaveworks/tap/eksctl " }, { "code": null, "e": 14093, "s": 13836, "text": "Creating a Kubernetes cluster is now ludicrously simple, we only need to run one command, but you should specify the cluster name, the number of nodes, and the region you are in (in this case I am in Boston so I choose us-east-1 ) and then run the command." }, { "code": null, "e": 14161, "s": 14093, "text": "eksctl create cluster --name=cluster-1 --nodes=4 --region=us-east-1" }, { "code": null, "e": 14224, "s": 14161, "text": "Now we must configure the cluster with the following commands:" }, { "code": null, "e": 14394, "s": 14224, "text": "kubectl get nodeskubectl --namespace kube-system create sa tillerkubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tiller" }, { "code": null, "e": 14437, "s": 14394, "text": "Now we set up Helm and Dask on the cluster" }, { "code": null, "e": 14472, "s": 14437, "text": "helm init --service-account tiller" }, { "code": null, "e": 14540, "s": 14472, "text": "Wait two minutes for this to complete and then we can install Dask." }, { "code": null, "e": 14696, "s": 14540, "text": "helm versionhelm repo updatehelm install stable/daskhelm status agile-newthelm listhelm upgrade agile-newt stable/dask -f config.yamlhelm status agile-newt" }, { "code": null, "e": 14728, "s": 14696, "text": "A few more Kubernetes commands." }, { "code": null, "e": 14765, "s": 14728, "text": "kubectl get podskubectl get services" }, { "code": null, "e": 14870, "s": 14765, "text": "For more details and a shell, you will need a command like this. Your exact pod names will be different." }, { "code": null, "e": 14997, "s": 14870, "text": "kubectl get pod agile-newt-dask-jupyter-54f86bfdd7-jdb5pkubectl exec -it agile-newt-dask-jupyter-54f86bfdd7-jdb5p -- /bin/bash" }, { "code": null, "e": 15081, "s": 14997, "text": "Once you are in the cluster, you can clone the GitHub repository and watch Dask go!" }, { "code": null, "e": 15108, "s": 15081, "text": "Kaggle Rossman Competition" }, { "code": null, "e": 15411, "s": 15108, "text": "I recommend that once you have got the Dask cloud deployment up and running you try running the rossman_kaggle.ipynb . This is example code from the Kaggle Rossman competition, which allowed users to use any data they wanted to try and predict pharmacy sales in Europe. The competition was run in 2015." }, { "code": null, "e": 15776, "s": 15411, "text": "The steps in this notebook run you through how to set up your coding environment for a multilayer perceptron in order to apply it to a parallel cluster and then perform hyperparameter optimization. All of the steps in this code are split into functions which are then run in an sklearn pipeline (this is the recommended way to run large machine learning programs)." }, { "code": null, "e": 15963, "s": 15776, "text": "There are several other examples on the repository that you can run on the parallel cluster and play with. Also, feel free to clone the repository and tinker with it as much as you like." }, { "code": null, "e": 15987, "s": 15963, "text": "Where can I learn more?" }, { "code": null, "e": 16044, "s": 15987, "text": "To learn more about Dask, check out the following links:" }, { "code": null, "e": 16055, "s": 16044, "text": "github.com" }, { "code": null, "e": 16069, "s": 16055, "text": "docs.dask.org" }, { "code": null, "e": 16111, "s": 16069, "text": "To learn more about Dask with Kubernetes:" }, { "code": null, "e": 16122, "s": 16111, "text": "github.com" }, { "code": null, "e": 16142, "s": 16122, "text": "kubernetes.dask.org" }, { "code": null, "e": 16168, "s": 16142, "text": "To learn more about Helm:" }, { "code": null, "e": 16182, "s": 16168, "text": "docs.dask.org" }, { "code": null, "e": 16328, "s": 16182, "text": "If you are struggling to work through any of the above steps, there are multiple other walkthroughs that go through the specifics in more detail:" }, { "code": null, "e": 16341, "s": 16328, "text": "ramhiser.com" }, { "code": null, "e": 16357, "s": 16341, "text": "zonca.github.io" }, { "code": null, "e": 16474, "s": 16357, "text": "For setting up the cluster on the Google Cloud (sadly could not find one for Microsoft Azure) check these links out:" }, { "code": null, "e": 16485, "s": 16474, "text": "github.com" }, { "code": null, "e": 16496, "s": 16485, "text": "github.com" }, { "code": null, "e": 16618, "s": 16496, "text": "Now you should have a working parallel cluster on which to perform machine learning on big data or for big compute tasks!" }, { "code": null, "e": 16640, "s": 16618, "text": "Thanks for reading! 🙏" } ]
var keyword in C#
22 Jun, 2020 Keywords are the words in a language that are used for some internal process or represent some predefined actions. var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value. Syntax: var variable_name = value; Example: Input: a = 637 b = -9721087085262 Output: value of a 637, type System.Int32 value of b -9721087085262, type System.Int64 Input: c = 120.23f d = 150.23m e = G f = Geeks Output: value of c 120.23, type System.Single value of d 150.23, type System.Decimal value of e G, type System.Char value of f Geeks, type System.String Example 1: // C# program for var keywordusing System;using System.Text; class GFG { static void Main(string[] args) { var a = 637; var b = -9721087085262; // to print their type of variables Console.WriteLine("value of a {0}, type {1}", a, a.GetType()); Console.WriteLine("value of b {0}, type {1}", b, b.GetType()); }} Output: value of a 637, type System.Int32 value of b -9721087085262, type System.Int64 Example 2: // C# program for var keywordusing System;using System.Text; namespace Test { class GFG { static void Main(string[] args) { var c = 120.23f; var d = 150.23m; var e = 'G'; var f = "Geeks"; // to print their type of variables Console.WriteLine("value of c {0}, type {1}", c, c.GetType()); Console.WriteLine("value of d {0}, type {1}", d, d.GetType()); Console.WriteLine("value of e {0}, type {1}", e, e.GetType()); Console.WriteLine("value of f {0}, type {1}", f, f.GetType()); // hit ENTER to exit Console.ReadLine(); }}} Output: value of c 120.23, type System.Single value of d 150.23, type System.Decimal value of e G, type System.Char value of f Geeks, type System.String CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class C# | .NET Framework (Basic Architecture and Component Stack) HashSet in C# with Examples Lambda Expressions in C# Switch Statement in C# Partial Classes in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2020" }, { "code": null, "e": 272, "s": 28, "text": "Keywords are the words in a language that are used for some internal process or represent some predefined actions. var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value." }, { "code": null, "e": 280, "s": 272, "text": "Syntax:" }, { "code": null, "e": 307, "s": 280, "text": "var variable_name = value;" }, { "code": null, "e": 316, "s": 307, "text": "Example:" }, { "code": null, "e": 700, "s": 316, "text": "Input: a = 637\n b = -9721087085262\n\nOutput: value of a 637, type System.Int32\n value of b -9721087085262, type System.Int64\n\nInput: c = 120.23f\n d = 150.23m\n e = G\n f = Geeks\nOutput: value of c 120.23, type System.Single\n value of d 150.23, type System.Decimal\n value of e G, type System.Char\n value of f Geeks, type System.String\n" }, { "code": null, "e": 711, "s": 700, "text": "Example 1:" }, { "code": "// C# program for var keywordusing System;using System.Text; class GFG { static void Main(string[] args) { var a = 637; var b = -9721087085262; // to print their type of variables Console.WriteLine(\"value of a {0}, type {1}\", a, a.GetType()); Console.WriteLine(\"value of b {0}, type {1}\", b, b.GetType()); }}", "e": 1071, "s": 711, "text": null }, { "code": null, "e": 1079, "s": 1071, "text": "Output:" }, { "code": null, "e": 1159, "s": 1079, "text": "value of a 637, type System.Int32\nvalue of b -9721087085262, type System.Int64\n" }, { "code": null, "e": 1170, "s": 1159, "text": "Example 2:" }, { "code": "// C# program for var keywordusing System;using System.Text; namespace Test { class GFG { static void Main(string[] args) { var c = 120.23f; var d = 150.23m; var e = 'G'; var f = \"Geeks\"; // to print their type of variables Console.WriteLine(\"value of c {0}, type {1}\", c, c.GetType()); Console.WriteLine(\"value of d {0}, type {1}\", d, d.GetType()); Console.WriteLine(\"value of e {0}, type {1}\", e, e.GetType()); Console.WriteLine(\"value of f {0}, type {1}\", f, f.GetType()); // hit ENTER to exit Console.ReadLine(); }}}", "e": 1787, "s": 1170, "text": null }, { "code": null, "e": 1795, "s": 1787, "text": "Output:" }, { "code": null, "e": 1941, "s": 1795, "text": "value of c 120.23, type System.Single\nvalue of d 150.23, type System.Decimal\nvalue of e G, type System.Char\nvalue of f Geeks, type System.String\n" }, { "code": null, "e": 1956, "s": 1941, "text": "CSharp-keyword" }, { "code": null, "e": 1959, "s": 1956, "text": "C#" }, { "code": null, "e": 2057, "s": 1959, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2100, "s": 2057, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2149, "s": 2100, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 2172, "s": 2149, "text": "Extension Method in C#" }, { "code": null, "e": 2188, "s": 2172, "text": "C# | List Class" }, { "code": null, "e": 2249, "s": 2188, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 2277, "s": 2249, "text": "HashSet in C# with Examples" }, { "code": null, "e": 2302, "s": 2277, "text": "Lambda Expressions in C#" }, { "code": null, "e": 2325, "s": 2302, "text": "Switch Statement in C#" }, { "code": null, "e": 2347, "s": 2325, "text": "Partial Classes in C#" } ]
Python program to update a dictionary with the values from a dictionary list
03 Sep, 2021 Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {“Gfg” : 2, “is” : 1, “Best” : 3}, dict_list = [{‘for’ : 3, ‘all’ : 7}, {‘and’ : 1, ‘CS’ : 9}] Output : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7, ‘and’: 1, ‘CS’: 9} Explanation : All dictionary keys updated in single dictionary. Input : test_dict = {“Gfg” : 2, “is” : 1, “Best” : 3}, dict_list = [{‘for’ : 3, ‘all’ : 7}] Output : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7} Explanation : All dictionary keys updated in single dictionary. Method #1 : Using update() + loop In this, we iterate through all the elements in loop, and perform update to update all the keys in dictionary to original dictionary. Python3 # Python3 code to demonstrate working of# Update dictionary with dictionary list# Using update() + loop # initializing dictionarytest_dict = {"Gfg" : 2, "is" : 1, "Best" : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing dictionary listdict_list = [{'for' : 3, 'all' : 7}, {'geeks' : 10}, {'and' : 1, 'CS' : 9}] for dicts in dict_list: # updating using update() test_dict.update(dicts) # printing resultprint("The updated dictionary : " + str(test_dict)) Output: The original dictionary is : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3} The updated dictionary : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7, ‘geeks’: 10, ‘and’: 1, ‘CS’: 9} Method #2 : Using ChainMap + ** operator In this, we perform task of merging all list dictionaries into 1 using ChainMap and ** operator is used to merge target dictionary to merged dictionary. Python3 # Python3 code to demonstrate working of# Update dictionary with dictionary list# Using ChainMap + ** operatorfrom collections import ChainMap # initializing dictionarytest_dict = {"Gfg" : 2, "is" : 1, "Best" : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing dictionary listdict_list = [{'for' : 3, 'all' : 7}, {'geeks' : 10}, {'and' : 1, 'CS' : 9}] # ** operator extracts keys and re initiates.# ChainMap is used to merge dictionary listres = {**test_dict, **dict(ChainMap(*dict_list))} # printing resultprint("The updated dictionary : " + str(res)) Output: The original dictionary is : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3} The updated dictionary : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7, ‘geeks’: 10, ‘and’: 1, ‘CS’: 9} rajeev0719singh clintra Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Sep, 2021" }, { "code": null, "e": 144, "s": 53, "text": "Given a dictionary and dictionary list, update the dictionary with dictionary list values." }, { "code": null, "e": 402, "s": 144, "text": "Input : test_dict = {“Gfg” : 2, “is” : 1, “Best” : 3}, dict_list = [{‘for’ : 3, ‘all’ : 7}, {‘and’ : 1, ‘CS’ : 9}] Output : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7, ‘and’: 1, ‘CS’: 9} Explanation : All dictionary keys updated in single dictionary." }, { "code": null, "e": 619, "s": 402, "text": "Input : test_dict = {“Gfg” : 2, “is” : 1, “Best” : 3}, dict_list = [{‘for’ : 3, ‘all’ : 7}] Output : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7} Explanation : All dictionary keys updated in single dictionary. " }, { "code": null, "e": 653, "s": 619, "text": "Method #1 : Using update() + loop" }, { "code": null, "e": 787, "s": 653, "text": "In this, we iterate through all the elements in loop, and perform update to update all the keys in dictionary to original dictionary." }, { "code": null, "e": 795, "s": 787, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Update dictionary with dictionary list# Using update() + loop # initializing dictionarytest_dict = {\"Gfg\" : 2, \"is\" : 1, \"Best\" : 3} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing dictionary listdict_list = [{'for' : 3, 'all' : 7}, {'geeks' : 10}, {'and' : 1, 'CS' : 9}] for dicts in dict_list: # updating using update() test_dict.update(dicts) # printing resultprint(\"The updated dictionary : \" + str(test_dict))", "e": 1316, "s": 795, "text": null }, { "code": null, "e": 1324, "s": 1316, "text": "Output:" }, { "code": null, "e": 1386, "s": 1324, "text": "The original dictionary is : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3} " }, { "code": null, "e": 1494, "s": 1386, "text": "The updated dictionary : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7, ‘geeks’: 10, ‘and’: 1, ‘CS’: 9}" }, { "code": null, "e": 1535, "s": 1494, "text": "Method #2 : Using ChainMap + ** operator" }, { "code": null, "e": 1688, "s": 1535, "text": "In this, we perform task of merging all list dictionaries into 1 using ChainMap and ** operator is used to merge target dictionary to merged dictionary." }, { "code": null, "e": 1696, "s": 1688, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Update dictionary with dictionary list# Using ChainMap + ** operatorfrom collections import ChainMap # initializing dictionarytest_dict = {\"Gfg\" : 2, \"is\" : 1, \"Best\" : 3} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing dictionary listdict_list = [{'for' : 3, 'all' : 7}, {'geeks' : 10}, {'and' : 1, 'CS' : 9}] # ** operator extracts keys and re initiates.# ChainMap is used to merge dictionary listres = {**test_dict, **dict(ChainMap(*dict_list))} # printing resultprint(\"The updated dictionary : \" + str(res))", "e": 2303, "s": 1696, "text": null }, { "code": null, "e": 2311, "s": 2303, "text": "Output:" }, { "code": null, "e": 2371, "s": 2311, "text": "The original dictionary is : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3}" }, { "code": null, "e": 2479, "s": 2371, "text": "The updated dictionary : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7, ‘geeks’: 10, ‘and’: 1, ‘CS’: 9}" }, { "code": null, "e": 2495, "s": 2479, "text": "rajeev0719singh" }, { "code": null, "e": 2503, "s": 2495, "text": "clintra" }, { "code": null, "e": 2530, "s": 2503, "text": "Python dictionary-programs" }, { "code": null, "e": 2537, "s": 2530, "text": "Python" }, { "code": null, "e": 2553, "s": 2537, "text": "Python Programs" } ]
Explain Chosen and Select2 with examples
31 Jul, 2020 The two jQuery plugins, Chosen and Select2 are used to style the select boxes. It improves the look of select boxes, enhances its behavior, thus making them much more user-friendly. They can be used for both single select boxes and multiple select boxes. These jQuery libraries need to be added: select2.min.js select2.min.css chosen.jquery.min.js chosen.min.css Activate the plugin on the select boxes: $(“.chosen-select”).chosen() $(“.chosen-select”).chosen() $(“.chosen-select”).select2() $(“.chosen-select”).select2() Differences between Select2 and Chosen: Selection and DeselectionSelect2 can deselect the options that are selected previously by just clicking the selected option from the dropdown list. But chosen does not has this feature as the selected options get faded.<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!--These jQuery libraries for chosen need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css" /> <!--These jQuery libraries for select2 need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" /> <script> $(document).ready(function () { //Select2 $(".country").select2({ maximumSelectionLength: 2, }); //Chosen $(".country1").chosen({ max_selected_options: 2, }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class="country" multiple="true" style="width: 200px;"> <option value="1">India</option> <option value="2">Japan</option> <option value="3">France</option> </select> <h4>Selections using Chosen</h4> <select class="country1" multiple="true" style="width: 200px;"> <option value="1">India</option> <option value="2">Japan</option> <option value="3">France</option> </select> </form> </body></html>Output: Selection and Deselection Select2 can deselect the options that are selected previously by just clicking the selected option from the dropdown list. But chosen does not has this feature as the selected options get faded. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!--These jQuery libraries for chosen need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css" /> <!--These jQuery libraries for select2 need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" /> <script> $(document).ready(function () { //Select2 $(".country").select2({ maximumSelectionLength: 2, }); //Chosen $(".country1").chosen({ max_selected_options: 2, }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class="country" multiple="true" style="width: 200px;"> <option value="1">India</option> <option value="2">Japan</option> <option value="3">France</option> </select> <h4>Selections using Chosen</h4> <select class="country1" multiple="true" style="width: 200px;"> <option value="1">India</option> <option value="2">Japan</option> <option value="3">France</option> </select> </form> </body></html> Output: Programmatic AccessIf some of the options have some link with each other and these linked options have a high probability to be selected, then it can be done by single click using Select2. It is very useful in multiple selections. While Chosen can’t perform this logical linking.<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!--These jQuery libraries for chosen need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css" /> <!--These jQuery libraries for select2 need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" /> <script> $(document).ready(function () { //Select2 var $prog = $(".progLang").select2(); $(".Front-end").on("click", function () { $prog.val(["ht", "js"]).trigger("change"); }); //Chosen var $prog1 = $(".progLang1").chosen(); $(".Front-end1").on("click", function () { $prog1.val(["ht", "js"]).trigger("change"); }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class="progLang" multiple="true" style="width: 200px;"> <option value="py">Python</option> <option value="ja">Java</option> <option value="ht">HTML</option> <option value="js">Javascript</option> <option value="c">C++</option> </select> <input type="button" class="Front-end" value="set Front-end Technologies" /> <h4>Selections using Chosen</h4> <select class="progLang1" multiple="true" style="width: 200px;"> <option value="py">Python</option> <option value="ja">Java</option> <option value="ht">HTML</option> <option value="js">Javascript</option> <option value="c">C++</option> </select> <input type="button" class="Front-end1" value="set Front-end Technologies" /> </form> </body></html>Output:After clicking set Front-end Technologies button: Programmatic Access If some of the options have some link with each other and these linked options have a high probability to be selected, then it can be done by single click using Select2. It is very useful in multiple selections. While Chosen can’t perform this logical linking. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!--These jQuery libraries for chosen need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css" /> <!--These jQuery libraries for select2 need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" /> <script> $(document).ready(function () { //Select2 var $prog = $(".progLang").select2(); $(".Front-end").on("click", function () { $prog.val(["ht", "js"]).trigger("change"); }); //Chosen var $prog1 = $(".progLang1").chosen(); $(".Front-end1").on("click", function () { $prog1.val(["ht", "js"]).trigger("change"); }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class="progLang" multiple="true" style="width: 200px;"> <option value="py">Python</option> <option value="ja">Java</option> <option value="ht">HTML</option> <option value="js">Javascript</option> <option value="c">C++</option> </select> <input type="button" class="Front-end" value="set Front-end Technologies" /> <h4>Selections using Chosen</h4> <select class="progLang1" multiple="true" style="width: 200px;"> <option value="py">Python</option> <option value="ja">Java</option> <option value="ht">HTML</option> <option value="js">Javascript</option> <option value="c">C++</option> </select> <input type="button" class="Front-end1" value="set Front-end Technologies" /> </form> </body></html> Output: After clicking set Front-end Technologies button: TaggingWhen you have a wide range of choices and you can’t include all choices then enable tags option. This will make the user add a new choice if not already present in the options. This can be done by setting the tags option to “true”.This option is available in Select2 while in Chosen user can’t add new choices to the list.<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!--These jQuery libraries for chosen need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css" /> <!--These jQuery libraries for select2 need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" /> <script> $(document).ready(function () { //Select2 $(".progLang").select2({ tags: true, }); //Chosen $(".progLang1").chosen({ tags: true, }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class="progLang" multiple="true" style="width: 200px; position: relative;"> <option value="py">Python</option> <option value="ja">Java</option> <option value="ht">HTML</option> </select> <h4>Selections using Chosen</h4> <select class="progLang1" multiple="true" style="width: 200px;"> <option value="py">Python</option> <option value="ja">Java</option> <option value="ht">HTML</option> </select> </form> </body></html>Output: Tagging When you have a wide range of choices and you can’t include all choices then enable tags option. This will make the user add a new choice if not already present in the options. This can be done by setting the tags option to “true”. This option is available in Select2 while in Chosen user can’t add new choices to the list. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!--These jQuery libraries for chosen need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css" /> <!--These jQuery libraries for select2 need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" /> <script> $(document).ready(function () { //Select2 $(".progLang").select2({ tags: true, }); //Chosen $(".progLang1").chosen({ tags: true, }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class="progLang" multiple="true" style="width: 200px; position: relative;"> <option value="py">Python</option> <option value="ja">Java</option> <option value="ht">HTML</option> </select> <h4>Selections using Chosen</h4> <select class="progLang1" multiple="true" style="width: 200px;"> <option value="py">Python</option> <option value="ja">Java</option> <option value="ht">HTML</option> </select> </form> </body></html> Output: TokenizationTokenization is used after the tags option is set to “true”. It provides token separators that are used as a shortcut for creating tags. This can be done by typing any token separator which is specified in the list, after the name of the tag. Any character can be created as a token separator with the help of Select2.As mentioned previously, since Chosen don’t have tagging feature, therefore, the tokenization feature is also not available.<!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!--These jQuery libraries for chosen need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css" /> <!--These jQuery libraries for select2 need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" /> <script> $(document).ready(function () { //Select2 $(".progLang").select2({ tags: true, maximumSelectionLength: 2, tokenSeparators: [ "/", ", ", ";", " ", "#"], }); //Chosen $(".progLang1").chosen({ tags: true, max_selected_options: 2, tokenSeparators: [ "/", ", ", ";", " ", "#"], }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class="progLang" multiple="true" style="width: 200px;"> <option value="py">Python</option> <option value="ja">Java</option> <option value="ht">HTML</option> </select> <h4>Selections using Chosen</h4> <select class="progLang1" multiple="true" style="width: 200px;"> <option value="py">Python</option> <option value="ja">Java</option> <option value="ht">HTML</option> </select> </form> </body></html>Output: Tokenization Tokenization is used after the tags option is set to “true”. It provides token separators that are used as a shortcut for creating tags. This can be done by typing any token separator which is specified in the list, after the name of the tag. Any character can be created as a token separator with the help of Select2. As mentioned previously, since Chosen don’t have tagging feature, therefore, the tokenization feature is also not available. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!--These jQuery libraries for chosen need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css" /> <!--These jQuery libraries for select2 need to be included--> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" /> <script> $(document).ready(function () { //Select2 $(".progLang").select2({ tags: true, maximumSelectionLength: 2, tokenSeparators: [ "/", ", ", ";", " ", "#"], }); //Chosen $(".progLang1").chosen({ tags: true, max_selected_options: 2, tokenSeparators: [ "/", ", ", ";", " ", "#"], }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class="progLang" multiple="true" style="width: 200px;"> <option value="py">Python</option> <option value="ja">Java</option> <option value="ht">HTML</option> </select> <h4>Selections using Chosen</h4> <select class="progLang1" multiple="true" style="width: 200px;"> <option value="py">Python</option> <option value="ja">Java</option> <option value="ht">HTML</option> </select> </form> </body></html> Output: JavaScript-Misc Picked JavaScript JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2020" }, { "code": null, "e": 283, "s": 28, "text": "The two jQuery plugins, Chosen and Select2 are used to style the select boxes. It improves the look of select boxes, enhances its behavior, thus making them much more user-friendly. They can be used for both single select boxes and multiple select boxes." }, { "code": null, "e": 324, "s": 283, "text": "These jQuery libraries need to be added:" }, { "code": null, "e": 339, "s": 324, "text": "select2.min.js" }, { "code": null, "e": 355, "s": 339, "text": "select2.min.css" }, { "code": null, "e": 376, "s": 355, "text": "chosen.jquery.min.js" }, { "code": null, "e": 391, "s": 376, "text": "chosen.min.css" }, { "code": null, "e": 432, "s": 391, "text": "Activate the plugin on the select boxes:" }, { "code": null, "e": 462, "s": 432, "text": " $(“.chosen-select”).chosen()" }, { "code": null, "e": 492, "s": 462, "text": " $(“.chosen-select”).chosen()" }, { "code": null, "e": 523, "s": 492, "text": " $(“.chosen-select”).select2()" }, { "code": null, "e": 554, "s": 523, "text": " $(“.chosen-select”).select2()" }, { "code": null, "e": 594, "s": 554, "text": "Differences between Select2 and Chosen:" }, { "code": null, "e": 2649, "s": 594, "text": "Selection and DeselectionSelect2 can deselect the options that are selected previously by just clicking the selected option from the dropdown list. But chosen does not has this feature as the selected options get faded.<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!--These jQuery libraries for chosen need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css\" /> <!--These jQuery libraries for select2 need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css\" /> <script> $(document).ready(function () { //Select2 $(\".country\").select2({ maximumSelectionLength: 2, }); //Chosen $(\".country1\").chosen({ max_selected_options: 2, }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class=\"country\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"1\">India</option> <option value=\"2\">Japan</option> <option value=\"3\">France</option> </select> <h4>Selections using Chosen</h4> <select class=\"country1\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"1\">India</option> <option value=\"2\">Japan</option> <option value=\"3\">France</option> </select> </form> </body></html>Output:" }, { "code": null, "e": 2675, "s": 2649, "text": "Selection and Deselection" }, { "code": null, "e": 2870, "s": 2675, "text": "Select2 can deselect the options that are selected previously by just clicking the selected option from the dropdown list. But chosen does not has this feature as the selected options get faded." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!--These jQuery libraries for chosen need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css\" /> <!--These jQuery libraries for select2 need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css\" /> <script> $(document).ready(function () { //Select2 $(\".country\").select2({ maximumSelectionLength: 2, }); //Chosen $(\".country1\").chosen({ max_selected_options: 2, }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class=\"country\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"1\">India</option> <option value=\"2\">Japan</option> <option value=\"3\">France</option> </select> <h4>Selections using Chosen</h4> <select class=\"country1\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"1\">India</option> <option value=\"2\">Japan</option> <option value=\"3\">France</option> </select> </form> </body></html>", "e": 4699, "s": 2870, "text": null }, { "code": null, "e": 4707, "s": 4699, "text": "Output:" }, { "code": null, "e": 7504, "s": 4707, "text": "Programmatic AccessIf some of the options have some link with each other and these linked options have a high probability to be selected, then it can be done by single click using Select2. It is very useful in multiple selections. While Chosen can’t perform this logical linking.<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!--These jQuery libraries for chosen need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css\" /> <!--These jQuery libraries for select2 need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css\" /> <script> $(document).ready(function () { //Select2 var $prog = $(\".progLang\").select2(); $(\".Front-end\").on(\"click\", function () { $prog.val([\"ht\", \"js\"]).trigger(\"change\"); }); //Chosen var $prog1 = $(\".progLang1\").chosen(); $(\".Front-end1\").on(\"click\", function () { $prog1.val([\"ht\", \"js\"]).trigger(\"change\"); }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class=\"progLang\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"py\">Python</option> <option value=\"ja\">Java</option> <option value=\"ht\">HTML</option> <option value=\"js\">Javascript</option> <option value=\"c\">C++</option> </select> <input type=\"button\" class=\"Front-end\" value=\"set Front-end Technologies\" /> <h4>Selections using Chosen</h4> <select class=\"progLang1\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"py\">Python</option> <option value=\"ja\">Java</option> <option value=\"ht\">HTML</option> <option value=\"js\">Javascript</option> <option value=\"c\">C++</option> </select> <input type=\"button\" class=\"Front-end1\" value=\"set Front-end Technologies\" /> </form> </body></html>Output:After clicking set Front-end Technologies button:" }, { "code": null, "e": 7524, "s": 7504, "text": "Programmatic Access" }, { "code": null, "e": 7785, "s": 7524, "text": "If some of the options have some link with each other and these linked options have a high probability to be selected, then it can be done by single click using Select2. It is very useful in multiple selections. While Chosen can’t perform this logical linking." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!--These jQuery libraries for chosen need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css\" /> <!--These jQuery libraries for select2 need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css\" /> <script> $(document).ready(function () { //Select2 var $prog = $(\".progLang\").select2(); $(\".Front-end\").on(\"click\", function () { $prog.val([\"ht\", \"js\"]).trigger(\"change\"); }); //Chosen var $prog1 = $(\".progLang1\").chosen(); $(\".Front-end1\").on(\"click\", function () { $prog1.val([\"ht\", \"js\"]).trigger(\"change\"); }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class=\"progLang\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"py\">Python</option> <option value=\"ja\">Java</option> <option value=\"ht\">HTML</option> <option value=\"js\">Javascript</option> <option value=\"c\">C++</option> </select> <input type=\"button\" class=\"Front-end\" value=\"set Front-end Technologies\" /> <h4>Selections using Chosen</h4> <select class=\"progLang1\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"py\">Python</option> <option value=\"ja\">Java</option> <option value=\"ht\">HTML</option> <option value=\"js\">Javascript</option> <option value=\"c\">C++</option> </select> <input type=\"button\" class=\"Front-end1\" value=\"set Front-end Technologies\" /> </form> </body></html>", "e": 10247, "s": 7785, "text": null }, { "code": null, "e": 10255, "s": 10247, "text": "Output:" }, { "code": null, "e": 10305, "s": 10255, "text": "After clicking set Front-end Technologies button:" }, { "code": null, "e": 12467, "s": 10305, "text": "TaggingWhen you have a wide range of choices and you can’t include all choices then enable tags option. This will make the user add a new choice if not already present in the options. This can be done by setting the tags option to “true”.This option is available in Select2 while in Chosen user can’t add new choices to the list.<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!--These jQuery libraries for chosen need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css\" /> <!--These jQuery libraries for select2 need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css\" /> <script> $(document).ready(function () { //Select2 $(\".progLang\").select2({ tags: true, }); //Chosen $(\".progLang1\").chosen({ tags: true, }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class=\"progLang\" multiple=\"true\" style=\"width: 200px; position: relative;\"> <option value=\"py\">Python</option> <option value=\"ja\">Java</option> <option value=\"ht\">HTML</option> </select> <h4>Selections using Chosen</h4> <select class=\"progLang1\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"py\">Python</option> <option value=\"ja\">Java</option> <option value=\"ht\">HTML</option> </select> </form> </body></html>Output:" }, { "code": null, "e": 12475, "s": 12467, "text": "Tagging" }, { "code": null, "e": 12707, "s": 12475, "text": "When you have a wide range of choices and you can’t include all choices then enable tags option. This will make the user add a new choice if not already present in the options. This can be done by setting the tags option to “true”." }, { "code": null, "e": 12799, "s": 12707, "text": "This option is available in Select2 while in Chosen user can’t add new choices to the list." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!--These jQuery libraries for chosen need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css\" /> <!--These jQuery libraries for select2 need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css\" /> <script> $(document).ready(function () { //Select2 $(\".progLang\").select2({ tags: true, }); //Chosen $(\".progLang1\").chosen({ tags: true, }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class=\"progLang\" multiple=\"true\" style=\"width: 200px; position: relative;\"> <option value=\"py\">Python</option> <option value=\"ja\">Java</option> <option value=\"ht\">HTML</option> </select> <h4>Selections using Chosen</h4> <select class=\"progLang1\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"py\">Python</option> <option value=\"ja\">Java</option> <option value=\"ht\">HTML</option> </select> </form> </body></html>", "e": 14625, "s": 12799, "text": null }, { "code": null, "e": 14633, "s": 14625, "text": "Output:" }, { "code": null, "e": 17148, "s": 14633, "text": "TokenizationTokenization is used after the tags option is set to “true”. It provides token separators that are used as a shortcut for creating tags. This can be done by typing any token separator which is specified in the list, after the name of the tag. Any character can be created as a token separator with the help of Select2.As mentioned previously, since Chosen don’t have tagging feature, therefore, the tokenization feature is also not available.<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!--These jQuery libraries for chosen need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css\" /> <!--These jQuery libraries for select2 need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css\" /> <script> $(document).ready(function () { //Select2 $(\".progLang\").select2({ tags: true, maximumSelectionLength: 2, tokenSeparators: [ \"/\", \", \", \";\", \" \", \"#\"], }); //Chosen $(\".progLang1\").chosen({ tags: true, max_selected_options: 2, tokenSeparators: [ \"/\", \", \", \";\", \" \", \"#\"], }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class=\"progLang\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"py\">Python</option> <option value=\"ja\">Java</option> <option value=\"ht\">HTML</option> </select> <h4>Selections using Chosen</h4> <select class=\"progLang1\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"py\">Python</option> <option value=\"ja\">Java</option> <option value=\"ht\">HTML</option> </select> </form> </body></html>Output:" }, { "code": null, "e": 17161, "s": 17148, "text": "Tokenization" }, { "code": null, "e": 17480, "s": 17161, "text": "Tokenization is used after the tags option is set to “true”. It provides token separators that are used as a shortcut for creating tags. This can be done by typing any token separator which is specified in the list, after the name of the tag. Any character can be created as a token separator with the help of Select2." }, { "code": null, "e": 17605, "s": 17480, "text": "As mentioned previously, since Chosen don’t have tagging feature, therefore, the tokenization feature is also not available." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!--These jQuery libraries for chosen need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css\" /> <!--These jQuery libraries for select2 need to be included--> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css\" /> <script> $(document).ready(function () { //Select2 $(\".progLang\").select2({ tags: true, maximumSelectionLength: 2, tokenSeparators: [ \"/\", \", \", \";\", \" \", \"#\"], }); //Chosen $(\".progLang1\").chosen({ tags: true, max_selected_options: 2, tokenSeparators: [ \"/\", \", \", \";\", \" \", \"#\"], }); }); </script> </head> <body> <form> <h4>Selections using Select2</h4> <select class=\"progLang\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"py\">Python</option> <option value=\"ja\">Java</option> <option value=\"ht\">HTML</option> </select> <h4>Selections using Chosen</h4> <select class=\"progLang1\" multiple=\"true\" style=\"width: 200px;\"> <option value=\"py\">Python</option> <option value=\"ja\">Java</option> <option value=\"ht\">HTML</option> </select> </form> </body></html>", "e": 19659, "s": 17605, "text": null }, { "code": null, "e": 19667, "s": 19659, "text": "Output:" }, { "code": null, "e": 19683, "s": 19667, "text": "JavaScript-Misc" }, { "code": null, "e": 19690, "s": 19683, "text": "Picked" }, { "code": null, "e": 19701, "s": 19690, "text": "JavaScript" }, { "code": null, "e": 19708, "s": 19701, "text": "JQuery" }, { "code": null, "e": 19725, "s": 19708, "text": "Web Technologies" } ]
TimeZone getDefault() Method in Java with Examples
02 Jan, 2019 The getDefault() method of TimeZone class in Java is used to know the default TimeZone for this system or host. This may vary in according to the implementation in different environment. Syntax: public static TimeZone getDefault() Parameters: The method does not take any parameters. Return Value: The method returns the default TimeZone of the host. Below program illustrates the working of getDefault() Method of TimeZone: // Java code to illustrate getDefault() method import java.util.*; public class TimeZoneDemo { public static void main(String args[]) { // Creating an object of TimeZone class. TimeZone time_zone_default = TimeZone.getDefault(); // Displaying the default TimeZone System.out.println("Default TimeZone: " + time_zone_default); }} Default TimeZone: sun.util.calendar.ZoneInfo[id="Etc/UTC", offset=0, dstSavings=0, useDaylight=false, transitions=0, lastRule=null] Java - util package Java-Functions Java-TimeZone Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Virtualization In Cloud Computing and Types Association Rule Software Engineering | Prototyping Model std::unique in C++ Distributed Database System Find maximum (or minimum) sum of a subarray of size k Introduction to Electronic Mail Advantages and Disadvantages of OOP Set add() method in Java with Examples Zigzag (or diagonal) traversal of Matrix
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jan, 2019" }, { "code": null, "e": 215, "s": 28, "text": "The getDefault() method of TimeZone class in Java is used to know the default TimeZone for this system or host. This may vary in according to the implementation in different environment." }, { "code": null, "e": 223, "s": 215, "text": "Syntax:" }, { "code": null, "e": 259, "s": 223, "text": "public static TimeZone getDefault()" }, { "code": null, "e": 312, "s": 259, "text": "Parameters: The method does not take any parameters." }, { "code": null, "e": 379, "s": 312, "text": "Return Value: The method returns the default TimeZone of the host." }, { "code": null, "e": 453, "s": 379, "text": "Below program illustrates the working of getDefault() Method of TimeZone:" }, { "code": "// Java code to illustrate getDefault() method import java.util.*; public class TimeZoneDemo { public static void main(String args[]) { // Creating an object of TimeZone class. TimeZone time_zone_default = TimeZone.getDefault(); // Displaying the default TimeZone System.out.println(\"Default TimeZone: \" + time_zone_default); }}", "e": 860, "s": 453, "text": null }, { "code": null, "e": 993, "s": 860, "text": "Default TimeZone: sun.util.calendar.ZoneInfo[id=\"Etc/UTC\",\noffset=0, dstSavings=0, useDaylight=false, transitions=0, lastRule=null]\n" }, { "code": null, "e": 1013, "s": 993, "text": "Java - util package" }, { "code": null, "e": 1028, "s": 1013, "text": "Java-Functions" }, { "code": null, "e": 1042, "s": 1028, "text": "Java-TimeZone" }, { "code": null, "e": 1047, "s": 1042, "text": "Misc" }, { "code": null, "e": 1052, "s": 1047, "text": "Misc" }, { "code": null, "e": 1057, "s": 1052, "text": "Misc" }, { "code": null, "e": 1155, "s": 1057, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1199, "s": 1155, "text": "Virtualization In Cloud Computing and Types" }, { "code": null, "e": 1216, "s": 1199, "text": "Association Rule" }, { "code": null, "e": 1257, "s": 1216, "text": "Software Engineering | Prototyping Model" }, { "code": null, "e": 1276, "s": 1257, "text": "std::unique in C++" }, { "code": null, "e": 1304, "s": 1276, "text": "Distributed Database System" }, { "code": null, "e": 1358, "s": 1304, "text": "Find maximum (or minimum) sum of a subarray of size k" }, { "code": null, "e": 1390, "s": 1358, "text": "Introduction to Electronic Mail" }, { "code": null, "e": 1426, "s": 1390, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 1465, "s": 1426, "text": "Set add() method in Java with Examples" } ]
How to get the current year using JavaScript ?
11 Nov, 2021 In this article, we will know how to get the current year using the build-in method in Javascript. The purpose is to get the current year by using JavaScript getFullYear() method that will return the full year in 4-digit format for some specified date. This method is used to fetch the year from a given Date object. Syntax: DateObject.getFullYear(); Parameter: This function does not accept any parameters. Return Values: It returns the year for the given date. Example: This example describes getting the current year. Generally, it is used to validate the input year in the 4-digit format on the website. HTML <!DOCTYPE html><html> <body style="text-align:center;"> <h1>GeeksforGeeks</h1> <h2> How to get the current year in JavaScript? </h2> <button onclick="geeks()"> click me </button> <h4 id="myID"></h4> <script> function geeks() { // Creating Date Object var dateobj = new Date(); // Year from above object // is being fetched using getFullYear() var dateObject = dateobj.getFullYear(); // Printing current year document.getElementById("myID").innerHTML = "The Current Year is : " + dateObject; } </script></body> </html> Output: getting the current year bhaskargeeksforgeeks JavaScript-Questions HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Nov, 2021" }, { "code": null, "e": 345, "s": 28, "text": "In this article, we will know how to get the current year using the build-in method in Javascript. The purpose is to get the current year by using JavaScript getFullYear() method that will return the full year in 4-digit format for some specified date. This method is used to fetch the year from a given Date object." }, { "code": null, "e": 353, "s": 345, "text": "Syntax:" }, { "code": null, "e": 380, "s": 353, "text": "DateObject.getFullYear(); " }, { "code": null, "e": 437, "s": 380, "text": "Parameter: This function does not accept any parameters." }, { "code": null, "e": 492, "s": 437, "text": "Return Values: It returns the year for the given date." }, { "code": null, "e": 637, "s": 492, "text": "Example: This example describes getting the current year. Generally, it is used to validate the input year in the 4-digit format on the website." }, { "code": null, "e": 642, "s": 637, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body style=\"text-align:center;\"> <h1>GeeksforGeeks</h1> <h2> How to get the current year in JavaScript? </h2> <button onclick=\"geeks()\"> click me </button> <h4 id=\"myID\"></h4> <script> function geeks() { // Creating Date Object var dateobj = new Date(); // Year from above object // is being fetched using getFullYear() var dateObject = dateobj.getFullYear(); // Printing current year document.getElementById(\"myID\").innerHTML = \"The Current Year is : \" + dateObject; } </script></body> </html>", "e": 1289, "s": 642, "text": null }, { "code": null, "e": 1297, "s": 1289, "text": "Output:" }, { "code": null, "e": 1323, "s": 1297, "text": " getting the current year" }, { "code": null, "e": 1344, "s": 1323, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 1365, "s": 1344, "text": "JavaScript-Questions" }, { "code": null, "e": 1370, "s": 1365, "text": "HTML" }, { "code": null, "e": 1381, "s": 1370, "text": "JavaScript" }, { "code": null, "e": 1398, "s": 1381, "text": "Web Technologies" }, { "code": null, "e": 1425, "s": 1398, "text": "Web technologies Questions" }, { "code": null, "e": 1430, "s": 1425, "text": "HTML" } ]
Matplotlib.axes.Axes.axhline() in Python
13 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.axhline() function in axes module of matplotlib library is used to add a horizontal line across the axis. Syntax: Axes.axhline(self, y=0, xmin=0, xmax=1, **kwargs) Parameters: This method accept the following parameters that are described below: y: This parameter is the y position in data coordinates of the horizontal line with default value of 0. xmin: This parameter should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot.Its default value of 0. xmax: This parameter should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot. Its default value of 1. Returns: This returns the following: lines:This returns the list of Line2D objects representing the plotted data. Below examples illustrate the matplotlib.axes.Axes.axhline() function in matplotlib.axes: Example-1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.collections as collections t = np.arange(0.0, 2, 0.01)s1 = np.sin(4 * np.pi * t)s2 = 0.75 * np.sin(8 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s1, color ='black')ax.axhline(0, color ='green', lw = 2)ax.set_title('matplotlib.axes.Axes.axhline() Example')plt.show() Output: Example-2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as mtriimport numpy as np fig, ax = plt.subplots()x = np.arange(0, 8 * np.pi, 0.01)y = np.sin(x)ax.plot(x, y, color ='black') threshold = 0.35ax.axhline(threshold, color ='green', lw = 3, alpha = 0.7) ax.fill_between(x, 0, 1, where = y > threshold, color ='green', alpha = 0.8, transform = ax.get_xaxis_transform()) ax.set_title('matplotlib.axes.Axes.axhline() Example')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 443, "s": 328, "text": "The Axes.axhline() function in axes module of matplotlib library is used to add a horizontal line across the axis." }, { "code": null, "e": 451, "s": 443, "text": "Syntax:" }, { "code": null, "e": 501, "s": 451, "text": "Axes.axhline(self, y=0, xmin=0, xmax=1, **kwargs)" }, { "code": null, "e": 583, "s": 501, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 687, "s": 583, "text": "y: This parameter is the y position in data coordinates of the horizontal line with default value of 0." }, { "code": null, "e": 821, "s": 687, "text": "xmin: This parameter should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot.Its default value of 0." }, { "code": null, "e": 956, "s": 821, "text": "xmax: This parameter should be between 0 and 1, 0 being the far left of the plot, 1 the far right of the plot. Its default value of 1." }, { "code": null, "e": 993, "s": 956, "text": "Returns: This returns the following:" }, { "code": null, "e": 1070, "s": 993, "text": "lines:This returns the list of Line2D objects representing the plotted data." }, { "code": null, "e": 1160, "s": 1070, "text": "Below examples illustrate the matplotlib.axes.Axes.axhline() function in matplotlib.axes:" }, { "code": null, "e": 1171, "s": 1160, "text": "Example-1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npimport matplotlib.collections as collections t = np.arange(0.0, 2, 0.01)s1 = np.sin(4 * np.pi * t)s2 = 0.75 * np.sin(8 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s1, color ='black')ax.axhline(0, color ='green', lw = 2)ax.set_title('matplotlib.axes.Axes.axhline() Example')plt.show()", "e": 1551, "s": 1171, "text": null }, { "code": null, "e": 1559, "s": 1551, "text": "Output:" }, { "code": null, "e": 1570, "s": 1559, "text": "Example-2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as mtriimport numpy as np fig, ax = plt.subplots()x = np.arange(0, 8 * np.pi, 0.01)y = np.sin(x)ax.plot(x, y, color ='black') threshold = 0.35ax.axhline(threshold, color ='green', lw = 3, alpha = 0.7) ax.fill_between(x, 0, 1, where = y > threshold, color ='green', alpha = 0.8, transform = ax.get_xaxis_transform()) ax.set_title('matplotlib.axes.Axes.axhline() Example')plt.show()", "e": 2088, "s": 1570, "text": null }, { "code": null, "e": 2096, "s": 2088, "text": "Output:" }, { "code": null, "e": 2114, "s": 2096, "text": "Python-matplotlib" }, { "code": null, "e": 2121, "s": 2114, "text": "Python" } ]
React Native FlatList Component
28 Apr, 2021 In this article, We are going to see how to create a FlatList in react-native. For this, we are going to use FlatList component. It is used to render the items in a scrollable list view. Syntax: <FlatList data={} renderItem={} /> Props in FlatList: renderItem: It is used to render the data into the list. data: It is basically an array of data. ItemSeparatorComponent: It is used to render in between each item. ListEmptyComponent: It is rendered when the list is empty. ListFooterComponent: It is rendered at the bottom of all items. ListFooterComponentStyle: It is used to style the internal view for ListFooterComponent. ListHeaderComponent: It is rendered at the top of all the items. ListHeaderComponentStyle: It is used to style the internal view ListHeaderComponent. columnWrapperStyle: It is an optional custom style for multi-item rows. extraData: It is the property that tells the list to re-render. getItemLayout: It is an optional optimization that allows skipping the measurement of dynamic content if you know the size of items. horizontal: If this is true then the items will be rendered horizontally instead of vertically. initialNumToRender: It tells how many items to render in the initial batch. initialScrollIndex: If it is provided then instead of starting from the top item, it will start from the initialScrollIndex item. inverted: It reverses the direction of the scroll. keyExtractor: It is used to extract the unique key for the given item. numColumns: It is used to render multiple columns. onEndReached: It is called once when the scroll position gets within the rendered content. onEndReachedThreshold: It tells us how far we are from the end. onRefresh: If provided, a standard RefreshControl will be added. onViewableItemsChanged: It is called when the visibility of row changes. progressViewOffset: It set when the offset for loading is needed. It is only available on android. refreshing: Set true, while waiting for new data from a refresh. removeClippedSubviews: This may improve scroll performance for large lists. On Android the default value is true. viewabilityConfigCallbackPairs: It shows the list of pairs. Methods in FlatList: flashScrollIndicators(): It displays the scroll indicators momentarily. getNativeScrollRef(): It provides a reference to the underlying scroll component. getScrollResponder(): It provides a handle to the underlying scroll responder. getScrollableNode(): It provides a handle to the underlying scroll node. recordInteraction(): It tells the list of an interaction that has occurred. scrollToEnd(): It scrolls to the end of the content. scrollToIndex(): It scrolls to a particular item whose index is provided. scrollToItem(): It scrolls to a provided item. It requires a linear scan through data. scrollToOffset(): It scrolls to a specific content pixel offset in the list. Now let’s start with the implementation: Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli Step 1: Open your terminal and install expo-cli by the following command. npm install -g expo-cli Step 2: Now create a project by the following command.expo init myapp Step 2: Now create a project by the following command. expo init myapp Step 3: Now go into your project folder i.e. myappcd myapp Step 3: Now go into your project folder i.e. myapp cd myapp Project Structure: Example: Now let’s implement the FlatList. Here we created a FlatList of courses. App.js import React from 'react';import{ StyleSheet, Text, View, FlatList, } from 'react-native';const DATA = [ { id:"1", title:"Data Structures" }, { id:"2", title:"STL" }, { id:"3", title:"C++" }, { id:"4", title:"Java" }, { id:"5", title:"Python" }, { id:"6", title:"CP" }, { id:"7", title:"ReactJs" }, { id:"8", title:"NodeJs" }, { id:"9", title:"MongoDb" }, { id:"10", title:"ExpressJs" }, { id:"11", title:"PHP" }, { id:"12", title:"MySql" },]; const Item = ({title}) => { return( <View style={styles.item}> <Text>{title}</Text> </View> );} export default function App() { const renderItem = ({item})=>( <Item title={item.title}/>);return ( <View style={styles.container}> <FlatList data={DATA} renderItem={renderItem} keyExtractor={item => item.id} /> </View> );} const styles = StyleSheet.create({ container: { marginTop:30, padding:2, }, item: { backgroundColor: '#f5f520', padding: 20, marginVertical: 8, marginHorizontal: 16, },}); Start the server by using the following command. npm run android Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. Reference: https://reactnative.dev/docs/flatlist Picked React-Native 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) Roadmap to Learn JavaScript For Beginners How to float three div side by side using CSS? Difference Between PUT and PATCH Request ReactJS | Router Axios in React: A Guide for Beginners
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2021" }, { "code": null, "e": 215, "s": 28, "text": "In this article, We are going to see how to create a FlatList in react-native. For this, we are going to use FlatList component. It is used to render the items in a scrollable list view." }, { "code": null, "e": 223, "s": 215, "text": "Syntax:" }, { "code": null, "e": 265, "s": 223, "text": "<FlatList\n data={}\n renderItem={}\n/> " }, { "code": null, "e": 284, "s": 265, "text": "Props in FlatList:" }, { "code": null, "e": 341, "s": 284, "text": "renderItem: It is used to render the data into the list." }, { "code": null, "e": 381, "s": 341, "text": "data: It is basically an array of data." }, { "code": null, "e": 448, "s": 381, "text": "ItemSeparatorComponent: It is used to render in between each item." }, { "code": null, "e": 507, "s": 448, "text": "ListEmptyComponent: It is rendered when the list is empty." }, { "code": null, "e": 571, "s": 507, "text": "ListFooterComponent: It is rendered at the bottom of all items." }, { "code": null, "e": 660, "s": 571, "text": "ListFooterComponentStyle: It is used to style the internal view for ListFooterComponent." }, { "code": null, "e": 725, "s": 660, "text": "ListHeaderComponent: It is rendered at the top of all the items." }, { "code": null, "e": 810, "s": 725, "text": "ListHeaderComponentStyle: It is used to style the internal view ListHeaderComponent." }, { "code": null, "e": 882, "s": 810, "text": "columnWrapperStyle: It is an optional custom style for multi-item rows." }, { "code": null, "e": 946, "s": 882, "text": "extraData: It is the property that tells the list to re-render." }, { "code": null, "e": 1079, "s": 946, "text": "getItemLayout: It is an optional optimization that allows skipping the measurement of dynamic content if you know the size of items." }, { "code": null, "e": 1175, "s": 1079, "text": "horizontal: If this is true then the items will be rendered horizontally instead of vertically." }, { "code": null, "e": 1251, "s": 1175, "text": "initialNumToRender: It tells how many items to render in the initial batch." }, { "code": null, "e": 1381, "s": 1251, "text": "initialScrollIndex: If it is provided then instead of starting from the top item, it will start from the initialScrollIndex item." }, { "code": null, "e": 1432, "s": 1381, "text": "inverted: It reverses the direction of the scroll." }, { "code": null, "e": 1503, "s": 1432, "text": "keyExtractor: It is used to extract the unique key for the given item." }, { "code": null, "e": 1554, "s": 1503, "text": "numColumns: It is used to render multiple columns." }, { "code": null, "e": 1645, "s": 1554, "text": "onEndReached: It is called once when the scroll position gets within the rendered content." }, { "code": null, "e": 1709, "s": 1645, "text": "onEndReachedThreshold: It tells us how far we are from the end." }, { "code": null, "e": 1774, "s": 1709, "text": "onRefresh: If provided, a standard RefreshControl will be added." }, { "code": null, "e": 1847, "s": 1774, "text": "onViewableItemsChanged: It is called when the visibility of row changes." }, { "code": null, "e": 1946, "s": 1847, "text": "progressViewOffset: It set when the offset for loading is needed. It is only available on android." }, { "code": null, "e": 2011, "s": 1946, "text": "refreshing: Set true, while waiting for new data from a refresh." }, { "code": null, "e": 2125, "s": 2011, "text": "removeClippedSubviews: This may improve scroll performance for large lists. On Android the default value is true." }, { "code": null, "e": 2185, "s": 2125, "text": "viewabilityConfigCallbackPairs: It shows the list of pairs." }, { "code": null, "e": 2206, "s": 2185, "text": "Methods in FlatList:" }, { "code": null, "e": 2278, "s": 2206, "text": "flashScrollIndicators(): It displays the scroll indicators momentarily." }, { "code": null, "e": 2360, "s": 2278, "text": "getNativeScrollRef(): It provides a reference to the underlying scroll component." }, { "code": null, "e": 2439, "s": 2360, "text": "getScrollResponder(): It provides a handle to the underlying scroll responder." }, { "code": null, "e": 2512, "s": 2439, "text": "getScrollableNode(): It provides a handle to the underlying scroll node." }, { "code": null, "e": 2588, "s": 2512, "text": "recordInteraction(): It tells the list of an interaction that has occurred." }, { "code": null, "e": 2641, "s": 2588, "text": "scrollToEnd(): It scrolls to the end of the content." }, { "code": null, "e": 2715, "s": 2641, "text": "scrollToIndex(): It scrolls to a particular item whose index is provided." }, { "code": null, "e": 2802, "s": 2715, "text": "scrollToItem(): It scrolls to a provided item. It requires a linear scan through data." }, { "code": null, "e": 2879, "s": 2802, "text": "scrollToOffset(): It scrolls to a specific content pixel offset in the list." }, { "code": null, "e": 2920, "s": 2879, "text": "Now let’s start with the implementation:" }, { "code": null, "e": 3017, "s": 2920, "text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli" }, { "code": null, "e": 3091, "s": 3017, "text": "Step 1: Open your terminal and install expo-cli by the following command." }, { "code": null, "e": 3115, "s": 3091, "text": "npm install -g expo-cli" }, { "code": null, "e": 3185, "s": 3115, "text": "Step 2: Now create a project by the following command.expo init myapp" }, { "code": null, "e": 3240, "s": 3185, "text": "Step 2: Now create a project by the following command." }, { "code": null, "e": 3256, "s": 3240, "text": "expo init myapp" }, { "code": null, "e": 3315, "s": 3256, "text": "Step 3: Now go into your project folder i.e. myappcd myapp" }, { "code": null, "e": 3366, "s": 3315, "text": "Step 3: Now go into your project folder i.e. myapp" }, { "code": null, "e": 3375, "s": 3366, "text": "cd myapp" }, { "code": null, "e": 3394, "s": 3375, "text": "Project Structure:" }, { "code": null, "e": 3476, "s": 3394, "text": "Example: Now let’s implement the FlatList. Here we created a FlatList of courses." }, { "code": null, "e": 3483, "s": 3476, "text": "App.js" }, { "code": "import React from 'react';import{ StyleSheet, Text, View, FlatList, } from 'react-native';const DATA = [ { id:\"1\", title:\"Data Structures\" }, { id:\"2\", title:\"STL\" }, { id:\"3\", title:\"C++\" }, { id:\"4\", title:\"Java\" }, { id:\"5\", title:\"Python\" }, { id:\"6\", title:\"CP\" }, { id:\"7\", title:\"ReactJs\" }, { id:\"8\", title:\"NodeJs\" }, { id:\"9\", title:\"MongoDb\" }, { id:\"10\", title:\"ExpressJs\" }, { id:\"11\", title:\"PHP\" }, { id:\"12\", title:\"MySql\" },]; const Item = ({title}) => { return( <View style={styles.item}> <Text>{title}</Text> </View> );} export default function App() { const renderItem = ({item})=>( <Item title={item.title}/>);return ( <View style={styles.container}> <FlatList data={DATA} renderItem={renderItem} keyExtractor={item => item.id} /> </View> );} const styles = StyleSheet.create({ container: { marginTop:30, padding:2, }, item: { backgroundColor: '#f5f520', padding: 20, marginVertical: 8, marginHorizontal: 16, },});", "e": 4615, "s": 3483, "text": null }, { "code": null, "e": 4664, "s": 4615, "text": "Start the server by using the following command." }, { "code": null, "e": 4680, "s": 4664, "text": "npm run android" }, { "code": null, "e": 4849, "s": 4680, "text": "Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. " }, { "code": null, "e": 4898, "s": 4849, "text": "Reference: https://reactnative.dev/docs/flatlist" }, { "code": null, "e": 4905, "s": 4898, "text": "Picked" }, { "code": null, "e": 4918, "s": 4905, "text": "React-Native" }, { "code": null, "e": 4935, "s": 4918, "text": "Web Technologies" }, { "code": null, "e": 5033, "s": 4935, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5094, "s": 5033, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5137, "s": 5094, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 5209, "s": 5137, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5249, "s": 5209, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5273, "s": 5249, "text": "REST API (Introduction)" }, { "code": null, "e": 5315, "s": 5273, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 5362, "s": 5315, "text": "How to float three div side by side using CSS?" }, { "code": null, "e": 5403, "s": 5362, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5420, "s": 5403, "text": "ReactJS | Router" } ]
Count of total Heads and Tails after N flips in a coin
14 Jun, 2021 Given character C and an integer N representing N number of coins in C position where C can be either head or tail. We can flip the coins N times, wherein the ith round the player will flip the face of all the coins whose number is less than or equal to i. The task is to determine the total number of head and tail after flipping N possible times. Examples: Input: C = ‘H’, N = 5 Output: Head = 2, Tail = 3 Explanation: H means initially all the coins are facing in head direction, N means the total number of coins. So initially for i = 0, we have: H H H H H After the first round that is i = 1: T H H H H After the second round that is i = 2: H T H H H After the third round that is i = 3: T H T H H After the fourth round that is i = 4: H T H T H After the fifth round that is i = 5: T H T H T Hence the total count of the head is 2 and tail is 3. Input: C = ‘T’, N = 7 Output: Head = 4, Tail = 3 Explanation: After all the possible flips the head and tail count is 4 and 3. Approach: To solve the problem mentioned above we have to follow the steps given below: In the question above if we observe then there is a pattern that if initially, all the coins are facing towards head direction then the total number of heads after N rounds will be the floor value of (n / 2) and tails will be the cell value of (n / 2). Otherwise, if all the coins are facing towards tail direction then a total number of tails after N rounds will be a floor value of (n / 2) and heads will be ceil value of (n / 2). Below is the implementation: C++ Java Python3 C# Javascript // C++ program to count total heads// and tails after N flips in a coin#include<bits/stdc++.h>using namespace std; // Function to find count of head and tailpair<int, int> count_ht(char s, int N){ // Check if initially all the // coins are facing towards head pair<int, int>p; if(s == 'H') { p.first = floor(N / 2.0); p.second = ceil(N / 2.0); } // Check if initially all the coins // are facing towards tail else if(s == 'T') { p.first = ceil(N / 2.0); p.second = floor(N / 2.0); } return p;} // Driver codeint main(){ char C = 'H'; int N = 5; pair<int, int> p = count_ht(C, N); cout << "Head = " << (p.first) << "\n"; cout << "Tail = " << (p.second) << "\n";} // This code is contributed by virusbuddah_ // Java program to count// total heads and tails// after N flips in a coinimport javafx.util.Pair;public class Main{// Function to find count of head and tail public static Pair <Integer, Integer> count_ht(char s, int N){ // Check if initially all the // coins are facing towards head Pair <Integer, Integer> p = new Pair <Integer, Integer> (0, 0); if(s == 'H') { p = new Pair <Integer, Integer> ((int)Math.floor(N / 2.0), (int)Math.ceil(N / 2.0)); } // Check if initially all the coins // are facing towards tail else if(s == 'T') { p = new Pair <Integer, Integer> ((int)Math.ceil(N / 2.0), (int)Math.floor(N / 2.0)); } return p;} public static void main(String[] args){ char C = 'H'; int N = 5; Pair <Integer, Integer> p = count_ht(C, N); System.out.println("Head = " + p.getKey()); System.out.println("Tail = " + p.getValue());}} // This code is contributed by divyeshrabadiya07 # Python3 program to Count total heads# and tails after N flips in a coin # Function to find count of head and tailimport mathdef count_ht( s, N ): # Check if initially all the # coins are facing towards head if s == "H": h = math.floor( N / 2 ) t = math.ceil( N / 2 ) # Check if initially all the coins # are facing towards tail elif s == "T": h = math.ceil( N / 2 ) t = math.floor( N / 2 ) return [h, t] # Driver Codeif __name__ == "__main__": C = "H" N = 5 l = count_ht(C, n) print("Head = ", l[0]) print("Tail = ", l[1]) // C# program to count total heads// and tails after N flips in a coinusing System; class GFG{ // Function to find count of head and tail public static Tuple<int, int> count_ht(char s, int N){ // Check if initially all the // coins are facing towards head Tuple<int, int> p = Tuple.Create(0, 0); if (s == 'H') { p = Tuple.Create((int)Math.Floor(N / 2.0), (int)Math.Ceiling(N / 2.0)); } // Check if initially all the coins // are facing towards tail else if (s == 'T') { p = Tuple.Create((int)Math.Ceiling(N / 2.0), (int)Math.Floor(N / 2.0)); } return p;} // Driver Codestatic void Main(){ char C = 'H'; int N = 5; Tuple<int, int> p = count_ht(C, N); Console.WriteLine("Head = " + p.Item1); Console.WriteLine("Tail = " + p.Item2);}} // This code is contributed by divyesh072019 <script> // JavaScript program to count total heads// and tails after N flips in a coin // Function to find count of head and tailfunction count_ht(s, N){ // Check if initially all the // coins are facing towards head var p = [0,0]; if(s == 'H') { p[0] = Math.floor(N / 2.0); p[1] = Math.ceil(N / 2.0); } // Check if initially all the coins // are facing towards tail else if(s == 'T') { p[0] = Math.ceil(N / 2.0); p[1] = Math.floor(N / 2.0); } return p;} // Driver codevar C = 'H';var N = 5; var p = count_ht(C, N); document.write( "Head = " + (p[0]) + "<br>");document.write( "Tail = " + (p[1]) + "<br>"); </script> Head = 2 Tail = 3 Time complexity: O(1) virusbuddha divyeshrabadiya07 divyesh072019 rutvik_56 Mathematical Pattern Searching Mathematical Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Jun, 2021" }, { "code": null, "e": 403, "s": 54, "text": "Given character C and an integer N representing N number of coins in C position where C can be either head or tail. We can flip the coins N times, wherein the ith round the player will flip the face of all the coins whose number is less than or equal to i. The task is to determine the total number of head and tail after flipping N possible times." }, { "code": null, "e": 413, "s": 403, "text": "Examples:" }, { "code": null, "e": 906, "s": 413, "text": "Input: C = ‘H’, N = 5 Output: Head = 2, Tail = 3 Explanation: H means initially all the coins are facing in head direction, N means the total number of coins. So initially for i = 0, we have: H H H H H After the first round that is i = 1: T H H H H After the second round that is i = 2: H T H H H After the third round that is i = 3: T H T H H After the fourth round that is i = 4: H T H T H After the fifth round that is i = 5: T H T H T Hence the total count of the head is 2 and tail is 3." }, { "code": null, "e": 1035, "s": 906, "text": "Input: C = ‘T’, N = 7 Output: Head = 4, Tail = 3 Explanation: After all the possible flips the head and tail count is 4 and 3. " }, { "code": null, "e": 1125, "s": 1035, "text": "Approach: To solve the problem mentioned above we have to follow the steps given below: " }, { "code": null, "e": 1378, "s": 1125, "text": "In the question above if we observe then there is a pattern that if initially, all the coins are facing towards head direction then the total number of heads after N rounds will be the floor value of (n / 2) and tails will be the cell value of (n / 2)." }, { "code": null, "e": 1558, "s": 1378, "text": "Otherwise, if all the coins are facing towards tail direction then a total number of tails after N rounds will be a floor value of (n / 2) and heads will be ceil value of (n / 2)." }, { "code": null, "e": 1588, "s": 1558, "text": "Below is the implementation: " }, { "code": null, "e": 1592, "s": 1588, "text": "C++" }, { "code": null, "e": 1597, "s": 1592, "text": "Java" }, { "code": null, "e": 1605, "s": 1597, "text": "Python3" }, { "code": null, "e": 1608, "s": 1605, "text": "C#" }, { "code": null, "e": 1619, "s": 1608, "text": "Javascript" }, { "code": "// C++ program to count total heads// and tails after N flips in a coin#include<bits/stdc++.h>using namespace std; // Function to find count of head and tailpair<int, int> count_ht(char s, int N){ // Check if initially all the // coins are facing towards head pair<int, int>p; if(s == 'H') { p.first = floor(N / 2.0); p.second = ceil(N / 2.0); } // Check if initially all the coins // are facing towards tail else if(s == 'T') { p.first = ceil(N / 2.0); p.second = floor(N / 2.0); } return p;} // Driver codeint main(){ char C = 'H'; int N = 5; pair<int, int> p = count_ht(C, N); cout << \"Head = \" << (p.first) << \"\\n\"; cout << \"Tail = \" << (p.second) << \"\\n\";} // This code is contributed by virusbuddah_", "e": 2429, "s": 1619, "text": null }, { "code": "// Java program to count// total heads and tails// after N flips in a coinimport javafx.util.Pair;public class Main{// Function to find count of head and tail public static Pair <Integer, Integer> count_ht(char s, int N){ // Check if initially all the // coins are facing towards head Pair <Integer, Integer> p = new Pair <Integer, Integer> (0, 0); if(s == 'H') { p = new Pair <Integer, Integer> ((int)Math.floor(N / 2.0), (int)Math.ceil(N / 2.0)); } // Check if initially all the coins // are facing towards tail else if(s == 'T') { p = new Pair <Integer, Integer> ((int)Math.ceil(N / 2.0), (int)Math.floor(N / 2.0)); } return p;} public static void main(String[] args){ char C = 'H'; int N = 5; Pair <Integer, Integer> p = count_ht(C, N); System.out.println(\"Head = \" + p.getKey()); System.out.println(\"Tail = \" + p.getValue());}} // This code is contributed by divyeshrabadiya07", "e": 3547, "s": 2429, "text": null }, { "code": "# Python3 program to Count total heads# and tails after N flips in a coin # Function to find count of head and tailimport mathdef count_ht( s, N ): # Check if initially all the # coins are facing towards head if s == \"H\": h = math.floor( N / 2 ) t = math.ceil( N / 2 ) # Check if initially all the coins # are facing towards tail elif s == \"T\": h = math.ceil( N / 2 ) t = math.floor( N / 2 ) return [h, t] # Driver Codeif __name__ == \"__main__\": C = \"H\" N = 5 l = count_ht(C, n) print(\"Head = \", l[0]) print(\"Tail = \", l[1])", "e": 4159, "s": 3547, "text": null }, { "code": "// C# program to count total heads// and tails after N flips in a coinusing System; class GFG{ // Function to find count of head and tail public static Tuple<int, int> count_ht(char s, int N){ // Check if initially all the // coins are facing towards head Tuple<int, int> p = Tuple.Create(0, 0); if (s == 'H') { p = Tuple.Create((int)Math.Floor(N / 2.0), (int)Math.Ceiling(N / 2.0)); } // Check if initially all the coins // are facing towards tail else if (s == 'T') { p = Tuple.Create((int)Math.Ceiling(N / 2.0), (int)Math.Floor(N / 2.0)); } return p;} // Driver Codestatic void Main(){ char C = 'H'; int N = 5; Tuple<int, int> p = count_ht(C, N); Console.WriteLine(\"Head = \" + p.Item1); Console.WriteLine(\"Tail = \" + p.Item2);}} // This code is contributed by divyesh072019", "e": 5116, "s": 4159, "text": null }, { "code": "<script> // JavaScript program to count total heads// and tails after N flips in a coin // Function to find count of head and tailfunction count_ht(s, N){ // Check if initially all the // coins are facing towards head var p = [0,0]; if(s == 'H') { p[0] = Math.floor(N / 2.0); p[1] = Math.ceil(N / 2.0); } // Check if initially all the coins // are facing towards tail else if(s == 'T') { p[0] = Math.ceil(N / 2.0); p[1] = Math.floor(N / 2.0); } return p;} // Driver codevar C = 'H';var N = 5; var p = count_ht(C, N); document.write( \"Head = \" + (p[0]) + \"<br>\");document.write( \"Tail = \" + (p[1]) + \"<br>\"); </script>", "e": 5813, "s": 5116, "text": null }, { "code": null, "e": 5833, "s": 5813, "text": "Head = 2\nTail = 3" }, { "code": null, "e": 5857, "s": 5835, "text": "Time complexity: O(1)" }, { "code": null, "e": 5869, "s": 5857, "text": "virusbuddha" }, { "code": null, "e": 5887, "s": 5869, "text": "divyeshrabadiya07" }, { "code": null, "e": 5901, "s": 5887, "text": "divyesh072019" }, { "code": null, "e": 5911, "s": 5901, "text": "rutvik_56" }, { "code": null, "e": 5924, "s": 5911, "text": "Mathematical" }, { "code": null, "e": 5942, "s": 5924, "text": "Pattern Searching" }, { "code": null, "e": 5955, "s": 5942, "text": "Mathematical" }, { "code": null, "e": 5973, "s": 5955, "text": "Pattern Searching" } ]
Robot Framework in Python
23 Sep, 2021 In this article, we will see the robot framework and we will cover standard libraries and underlying functions, and going forward we will also cover test cases, keywords, variables, and finally organizing the test cases. Robot Framework is a common open-source automation framework for Acceptance Testing, Acceptance Test-Driven Development (ATTD), and Robotic Process Automation (RPA). It uses a keyword-driven testing technology approach and the capabilities can be extended by testing libraries that can be implemented in Python or Java. Let’s talk about the Acceptance Technique in which the capability of the system is tested and the purpose of the Acceptance Technique is to evaluate the capabilities of the system in accordance with the business requirement. This is an advanced method rooted in business communication between customers, developers, and testers. They work in coordination and do acceptance testing before implementing the functionality. It is a process of conveniently reduces human efforts in resonance with software that uses machine learning and artificial intelligence capabilities. RPA handles high-level repeatable tasks. The test data is simple to edit the table format when the robot framework is started. It executes the process data and generates logs and reports. The core framework does not know anything about the target under test and the intersection with it is handled by the libraries. Libraries can either directly use the application interface or use low-level testing tools as drivers. Robot Framework has a modular architecture that can be bundled and expanded with self-declared libraries. When execution begins, the framework parses the data before it. It then uses the keywords provided by the libraries to interact with the destination system. Libraries can intercommunicate orderly with the system or use other tools as drivers. Test or task execution starts from the command line. As an outcome, we get a report and log in HTML format as well as an XML output. Step 1: Python Installation Check if Python is installed on your system. python --version pip --version Step 2: Install Robot Framework The suggested route to install the robot framework on Python is to use pip. We can use the undermentioned command to install the framework. pip install robotframework Step 3: Verifying Installation After the well-turned installation, we should be able to see both interpreter and robot framework versions using the –version option. robot --version rebot --version Step 4: Check robot framework is installed properly pip show robotframework There are a bunch of standard libraries in the robot framework. Let’s discuss one by one Builtin is a Robot Framework standard library that provides a set of common keywords that are needed very often so are automatically imported and always available. Collection is a standard library that provides a set of keywords to handle python lists and dictionaries. The library has keywords to modify and derive values from lists and dictionaries. DateTime is a robot framework that supports the creation and transformation of date and time values. Dialogs is a Robot Framework standard library that provides a means to pause execution and receive input from users. The dialogs are a bit inconsistent depending on whether the tests are running or not. OperatingSystem enables the various operating system-related tasks which are going to perform in the system when the robot framework is running. It can among other things executing commands, can also create and remove files directly as well. Process is used for running processes, this library utilizes python submodules and its open class. The main use of the library is to wait for the running process in the system and compile using the run process keyword. we have start process on the background using start process and then we start the process or end process or terminate all process using wait for the process. Screenshot is a test library for taking screenshots on the machine where the tests are being run. String is a library used for string manipulations and verification. Telnet provides communication over a telnet connection. The telnet library makes it possible to connect to a telnet server and execute commands over an open connection. XML is also a robot framework text library for verifying and modifying XML documents. There are mainly four built-in tools that are used in robot framework that are: Testdoc – Robot Framework generates high-level HTML documentation based on test cases. Rebot – Tools to generate logs and reports based on XML output and merge multiple outputs simultaneously. Tidy – Robot Framework Tools for cleaning and changing the format of data files. Libdoc – Tools for generating keyword documentation for libraries and resource files. The test cases in the robot framework are allowed to write in simple English language rather than automated test cases. It follows a Keyword Test driven approach that resonates with natural language in terms of action rather than expectations. Test cases are created from available keywords in test case table and keywords can be imported from test library or resource file or we can also create a keywords table for test case file. The first column in a test case table has the test names and the test case starts with something in the column and is continuous with the next test case name or the end of the table. The second column usually contains a keyword name and the exception to this rule is to set variables with keyword written values. Data-driven testing allows test data to be isolated without mimicking workflows. The [template] setting in the robot framework sets the test case for a data-driven test. Test cases in Robot Framework are created with keywords coming from two sources. Library Keywords: All the lowest level keywords are defined in the standard library which can be implemented using programming languages like Java, Python, etc. Robot Framework comes with test libraries that can be divided into standard and custom libraries, so the standard libraries are in the main framework such as built-in screenshots and external libraries are installed separately like the Selenium library. User Keywords: One of the powerful features of robot framework is that we can create custom high-level keywords using other keywords. Robot test cases are created in test case files, but we can organize them in directories that make up the test suite hierarchy. A collection of test cases is called a test suite. Each file containing test cases also forms a test suite. It is possible to organize test cases into a hierarchy by using directories, all of which form a higher-level test suite that derives their names from directory names. Step 1: Check robot framework is installed Step 2: Go to the project Eclipse > Robot project >New Test Suite A simple test of the robot: *** Test Cases *** MyFirstTest Log Hello World!!! To run our Test Case, simply right click on the screen and select Run tests: ‘MyFirstTest‘, and the console will open As we can see all the details about the test and we can see the output, log, and report by following the given address link Here we can clearly see the project report, it gives the time of the report creation. It gives some summary information about the test like Status, Start Time, End Time, Elapsed Time, and Log File. And we visit the Log File by clicking on the link given: Here, we can see the statistics and also check the pass/fail/skip number of test cases. We can check the test execution log and test suite status. It is convenient to use and install.It is an open-source framework, anyone with or without programming experience can drive.It is suited to various operating systems and external libraries such as the Selenium library.The Robot framework supports behavior-driven, keyword-driven, and data-driven styles of building test cases.We can use any Robot Integrated Development Environment (RIDE) or any text editor to write the test cases. It is convenient to use and install. It is an open-source framework, anyone with or without programming experience can drive. It is suited to various operating systems and external libraries such as the Selenium library. The Robot framework supports behavior-driven, keyword-driven, and data-driven styles of building test cases. We can use any Robot Integrated Development Environment (RIDE) or any text editor to write the test cases. Scarcity of parallel test execution.Customizing HTML reports is not straightforward. Scarcity of parallel test execution. Customizing HTML reports is not straightforward. Robot lacks support for if-else, nested loops, which are required when the code gets complex. The Robot Framework is an open-source test automation framework for acceptance testing and acceptance test-driven development. The test cases in the robot framework are based on keywords written in a tabular format, which makes it clear and readable, and reveals true information about the intent of the test case. For example, to open a browser, the keyword used is “open browser”. Blogathon-2021 Python Framework Blogathon Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Sep, 2021" }, { "code": null, "e": 276, "s": 54, "text": "In this article, we will see the robot framework and we will cover standard libraries and underlying functions, and going forward we will also cover test cases, keywords, variables, and finally organizing the test cases." }, { "code": null, "e": 598, "s": 276, "text": "Robot Framework is a common open-source automation framework for Acceptance Testing, Acceptance Test-Driven Development (ATTD), and Robotic Process Automation (RPA). It uses a keyword-driven testing technology approach and the capabilities can be extended by testing libraries that can be implemented in Python or Java. " }, { "code": null, "e": 823, "s": 598, "text": "Let’s talk about the Acceptance Technique in which the capability of the system is tested and the purpose of the Acceptance Technique is to evaluate the capabilities of the system in accordance with the business requirement." }, { "code": null, "e": 1018, "s": 823, "text": "This is an advanced method rooted in business communication between customers, developers, and testers. They work in coordination and do acceptance testing before implementing the functionality." }, { "code": null, "e": 1209, "s": 1018, "text": "It is a process of conveniently reduces human efforts in resonance with software that uses machine learning and artificial intelligence capabilities. RPA handles high-level repeatable tasks." }, { "code": null, "e": 2070, "s": 1209, "text": "The test data is simple to edit the table format when the robot framework is started. It executes the process data and generates logs and reports. The core framework does not know anything about the target under test and the intersection with it is handled by the libraries. Libraries can either directly use the application interface or use low-level testing tools as drivers. Robot Framework has a modular architecture that can be bundled and expanded with self-declared libraries. When execution begins, the framework parses the data before it. It then uses the keywords provided by the libraries to interact with the destination system. Libraries can intercommunicate orderly with the system or use other tools as drivers. Test or task execution starts from the command line. As an outcome, we get a report and log in HTML format as well as an XML output. " }, { "code": null, "e": 2098, "s": 2070, "text": "Step 1: Python Installation" }, { "code": null, "e": 2143, "s": 2098, "text": "Check if Python is installed on your system." }, { "code": null, "e": 2174, "s": 2143, "text": "python --version\npip --version" }, { "code": null, "e": 2206, "s": 2174, "text": "Step 2: Install Robot Framework" }, { "code": null, "e": 2346, "s": 2206, "text": "The suggested route to install the robot framework on Python is to use pip. We can use the undermentioned command to install the framework." }, { "code": null, "e": 2373, "s": 2346, "text": "pip install robotframework" }, { "code": null, "e": 2404, "s": 2373, "text": "Step 3: Verifying Installation" }, { "code": null, "e": 2538, "s": 2404, "text": "After the well-turned installation, we should be able to see both interpreter and robot framework versions using the –version option." }, { "code": null, "e": 2570, "s": 2538, "text": "robot --version\nrebot --version" }, { "code": null, "e": 2622, "s": 2570, "text": "Step 4: Check robot framework is installed properly" }, { "code": null, "e": 2646, "s": 2622, "text": "pip show robotframework" }, { "code": null, "e": 2735, "s": 2646, "text": "There are a bunch of standard libraries in the robot framework. Let’s discuss one by one" }, { "code": null, "e": 2899, "s": 2735, "text": "Builtin is a Robot Framework standard library that provides a set of common keywords that are needed very often so are automatically imported and always available." }, { "code": null, "e": 3087, "s": 2899, "text": "Collection is a standard library that provides a set of keywords to handle python lists and dictionaries. The library has keywords to modify and derive values from lists and dictionaries." }, { "code": null, "e": 3188, "s": 3087, "text": "DateTime is a robot framework that supports the creation and transformation of date and time values." }, { "code": null, "e": 3391, "s": 3188, "text": "Dialogs is a Robot Framework standard library that provides a means to pause execution and receive input from users. The dialogs are a bit inconsistent depending on whether the tests are running or not." }, { "code": null, "e": 3633, "s": 3391, "text": "OperatingSystem enables the various operating system-related tasks which are going to perform in the system when the robot framework is running. It can among other things executing commands, can also create and remove files directly as well." }, { "code": null, "e": 4010, "s": 3633, "text": "Process is used for running processes, this library utilizes python submodules and its open class. The main use of the library is to wait for the running process in the system and compile using the run process keyword. we have start process on the background using start process and then we start the process or end process or terminate all process using wait for the process." }, { "code": null, "e": 4108, "s": 4010, "text": "Screenshot is a test library for taking screenshots on the machine where the tests are being run." }, { "code": null, "e": 4176, "s": 4108, "text": "String is a library used for string manipulations and verification." }, { "code": null, "e": 4345, "s": 4176, "text": "Telnet provides communication over a telnet connection. The telnet library makes it possible to connect to a telnet server and execute commands over an open connection." }, { "code": null, "e": 4431, "s": 4345, "text": "XML is also a robot framework text library for verifying and modifying XML documents." }, { "code": null, "e": 4511, "s": 4431, "text": "There are mainly four built-in tools that are used in robot framework that are:" }, { "code": null, "e": 4598, "s": 4511, "text": "Testdoc – Robot Framework generates high-level HTML documentation based on test cases." }, { "code": null, "e": 4704, "s": 4598, "text": "Rebot – Tools to generate logs and reports based on XML output and merge multiple outputs simultaneously." }, { "code": null, "e": 4785, "s": 4704, "text": "Tidy – Robot Framework Tools for cleaning and changing the format of data files." }, { "code": null, "e": 4871, "s": 4785, "text": "Libdoc – Tools for generating keyword documentation for libraries and resource files." }, { "code": null, "e": 5304, "s": 4871, "text": "The test cases in the robot framework are allowed to write in simple English language rather than automated test cases. It follows a Keyword Test driven approach that resonates with natural language in terms of action rather than expectations. Test cases are created from available keywords in test case table and keywords can be imported from test library or resource file or we can also create a keywords table for test case file." }, { "code": null, "e": 5487, "s": 5304, "text": "The first column in a test case table has the test names and the test case starts with something in the column and is continuous with the next test case name or the end of the table." }, { "code": null, "e": 5617, "s": 5487, "text": "The second column usually contains a keyword name and the exception to this rule is to set variables with keyword written values." }, { "code": null, "e": 5787, "s": 5617, "text": "Data-driven testing allows test data to be isolated without mimicking workflows. The [template] setting in the robot framework sets the test case for a data-driven test." }, { "code": null, "e": 5868, "s": 5787, "text": "Test cases in Robot Framework are created with keywords coming from two sources." }, { "code": null, "e": 6283, "s": 5868, "text": "Library Keywords: All the lowest level keywords are defined in the standard library which can be implemented using programming languages like Java, Python, etc. Robot Framework comes with test libraries that can be divided into standard and custom libraries, so the standard libraries are in the main framework such as built-in screenshots and external libraries are installed separately like the Selenium library." }, { "code": null, "e": 6417, "s": 6283, "text": "User Keywords: One of the powerful features of robot framework is that we can create custom high-level keywords using other keywords." }, { "code": null, "e": 6821, "s": 6417, "text": "Robot test cases are created in test case files, but we can organize them in directories that make up the test suite hierarchy. A collection of test cases is called a test suite. Each file containing test cases also forms a test suite. It is possible to organize test cases into a hierarchy by using directories, all of which form a higher-level test suite that derives their names from directory names." }, { "code": null, "e": 6864, "s": 6821, "text": "Step 1: Check robot framework is installed" }, { "code": null, "e": 6930, "s": 6864, "text": "Step 2: Go to the project Eclipse > Robot project >New Test Suite" }, { "code": null, "e": 6958, "s": 6930, "text": "A simple test of the robot:" }, { "code": null, "e": 7016, "s": 6958, "text": "*** Test Cases ***\nMyFirstTest\n Log Hello World!!!" }, { "code": null, "e": 7134, "s": 7016, "text": "To run our Test Case, simply right click on the screen and select Run tests: ‘MyFirstTest‘, and the console will open" }, { "code": null, "e": 7258, "s": 7134, "text": "As we can see all the details about the test and we can see the output, log, and report by following the given address link" }, { "code": null, "e": 7457, "s": 7258, "text": "Here we can clearly see the project report, it gives the time of the report creation. It gives some summary information about the test like Status, Start Time, End Time, Elapsed Time, and Log File. " }, { "code": null, "e": 7514, "s": 7457, "text": "And we visit the Log File by clicking on the link given:" }, { "code": null, "e": 7661, "s": 7514, "text": "Here, we can see the statistics and also check the pass/fail/skip number of test cases. We can check the test execution log and test suite status." }, { "code": null, "e": 8094, "s": 7661, "text": "It is convenient to use and install.It is an open-source framework, anyone with or without programming experience can drive.It is suited to various operating systems and external libraries such as the Selenium library.The Robot framework supports behavior-driven, keyword-driven, and data-driven styles of building test cases.We can use any Robot Integrated Development Environment (RIDE) or any text editor to write the test cases." }, { "code": null, "e": 8131, "s": 8094, "text": "It is convenient to use and install." }, { "code": null, "e": 8220, "s": 8131, "text": "It is an open-source framework, anyone with or without programming experience can drive." }, { "code": null, "e": 8315, "s": 8220, "text": "It is suited to various operating systems and external libraries such as the Selenium library." }, { "code": null, "e": 8424, "s": 8315, "text": "The Robot framework supports behavior-driven, keyword-driven, and data-driven styles of building test cases." }, { "code": null, "e": 8531, "s": 8424, "text": "We can use any Robot Integrated Development Environment (RIDE) or any text editor to write the test cases." }, { "code": null, "e": 8616, "s": 8531, "text": "Scarcity of parallel test execution.Customizing HTML reports is not straightforward." }, { "code": null, "e": 8653, "s": 8616, "text": "Scarcity of parallel test execution." }, { "code": null, "e": 8702, "s": 8653, "text": "Customizing HTML reports is not straightforward." }, { "code": null, "e": 8796, "s": 8702, "text": "Robot lacks support for if-else, nested loops, which are required when the code gets complex." }, { "code": null, "e": 9179, "s": 8796, "text": "The Robot Framework is an open-source test automation framework for acceptance testing and acceptance test-driven development. The test cases in the robot framework are based on keywords written in a tabular format, which makes it clear and readable, and reveals true information about the intent of the test case. For example, to open a browser, the keyword used is “open browser”." }, { "code": null, "e": 9194, "s": 9179, "text": "Blogathon-2021" }, { "code": null, "e": 9211, "s": 9194, "text": "Python Framework" }, { "code": null, "e": 9221, "s": 9211, "text": "Blogathon" }, { "code": null, "e": 9228, "s": 9221, "text": "Python" } ]
Data Structures and Algorithms | Set 27
11 Nov, 2021 Following questions have been asked in GATE CS 2011 exam. 1) An undirected graph G(V, E) contains n ( n > 2 ) nodes named v1 , v2 ,....vn. Two nodes vi , vj are connected if and only if 0 < |i – j| <= 2. Each edge (vi, vj ) is assigned a weight i + j. A sample graph with n = 4 is shown below. What will be the cost of the minimum spanning tree (MST) of such a graph with n nodes?(A) 1/12(11n^2 – 5n)(B) n^2 – n + 1(C) 6n – 11(D) 2n + 1 Answer: (B)Minimum spanning tree for 2 nodes would be (v1) _ (v2) Total weight 3 Minimum spanning tree for 3 nodes would be (v1) _ (v2) | (v3) Total weight= 3 + 4 = 7 Minimum spanning tree for 4 nodes would be (v1) _ (v2) _ (v4) | (v3) Total weight= 3 + 4 + 6 = 13 Minimum spanning tree for 5 nodes would be (v1) _ (v2) _ (v4) | (v3) | (v5) Total weight= 3 + 4 + 6 + 8 = 21 Minimum spanning tree for 6 nodes would be (v1) _ (v2) _ (v4) _ (v6) | (v3) | (v5) Total weight= 3 + 4 + 6 + 8 + 10 = 31 We can observe from above examples that when we add kth node, the weight of spanning tree increases by 2k-2. Let T(n) be the weight of minimum spanning tree. T(n) can be written as T(n) = T(n-1) + (2n-2) for n > 2T(1) = 0, T(2) = 0 and T(2) = 3 The recurrence can be written as sum of series (2n – 2) + (2n-4) + (2n-6) + (2n-8) + .... 3 and solution of this recurrence is n^2 – n + 1. 2) The length of the path from v5 to v6 in the MST of previous question with n = 10 is(A) 11(B) 25(C) 31(D) 41 Answer: (C)Any MST which has more than 5 nodes will have the same distance between v5 and v6 as the basic structure of all MSTs (with more than 5 nodes) would be following. (v1) _ (v2) _ (v4) _ (v6) _ . . (more even numbered nodes) | (v3) | (v5) | . . (more odd numbered nodes) Distance between v5 and v6 = 3 + 4 + 6 + 8 + 10 = 31 3) Consider two binary operators ‘↑ ‘ and ‘↓’ with the precedence of operator ↓ being lower than that of the ↑ operator. Operator ↑ is right associative while operator ↓ is left associative. Which one of the following represents the parse tree for expression (7 ↓ 3 ­↑ 4 ­↑ 3 ↓ 2)? Answer: (B)Let us consider the given expression (7 ↓ 3 ↑ 4 ↑ 3 ↓ 2). Since the precedence of ↑ is higher, the sub-expression ([3 ↑ 4 ↑ 3) will be evaluated first. In this sub-expression, 4 ↑ 3 would be evaluated first because ↑ is right to left associative. So the expression is evaluated as ((7 ↓ (3 ↑ (4 ↑ 3))) ↓ 2). Also, note that among the two ↓ operators, first one is evaluated before the second one because the associativity of ↓ is left to right. Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. GATE-CS-2011 GATE-CS-DS-&-Algo GATE CS MCQ Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Nov, 2021" }, { "code": null, "e": 112, "s": 54, "text": "Following questions have been asked in GATE CS 2011 exam." }, { "code": null, "e": 348, "s": 112, "text": "1) An undirected graph G(V, E) contains n ( n > 2 ) nodes named v1 , v2 ,....vn. Two nodes vi , vj are connected if and only if 0 < |i – j| <= 2. Each edge (vi, vj ) is assigned a weight i + j. A sample graph with n = 4 is shown below." }, { "code": null, "e": 491, "s": 348, "text": "What will be the cost of the minimum spanning tree (MST) of such a graph with n nodes?(A) 1/12(11n^2 – 5n)(B) n^2 – n + 1(C) 6n – 11(D) 2n + 1" }, { "code": null, "e": 545, "s": 491, "text": "Answer: (B)Minimum spanning tree for 2 nodes would be" }, { "code": null, "e": 560, "s": 545, "text": " (v1) _ (v2) \n" }, { "code": null, "e": 575, "s": 560, "text": "Total weight 3" }, { "code": null, "e": 618, "s": 575, "text": "Minimum spanning tree for 3 nodes would be" }, { "code": null, "e": 645, "s": 618, "text": " (v1) _ (v2) \n |\n (v3)\n" }, { "code": null, "e": 669, "s": 645, "text": "Total weight= 3 + 4 = 7" }, { "code": null, "e": 712, "s": 669, "text": "Minimum spanning tree for 4 nodes would be" }, { "code": null, "e": 746, "s": 712, "text": " (v1) _ (v2) _ (v4) \n |\n (v3)\n" }, { "code": null, "e": 775, "s": 746, "text": "Total weight= 3 + 4 + 6 = 13" }, { "code": null, "e": 818, "s": 775, "text": "Minimum spanning tree for 5 nodes would be" }, { "code": null, "e": 864, "s": 818, "text": " (v1) _ (v2) _ (v4) \n |\n (v3)\n |\n (v5)\n" }, { "code": null, "e": 897, "s": 864, "text": "Total weight= 3 + 4 + 6 + 8 = 21" }, { "code": null, "e": 940, "s": 897, "text": "Minimum spanning tree for 6 nodes would be" }, { "code": null, "e": 992, "s": 940, "text": " (v1) _ (v2) _ (v4) _ (v6)\n |\n (v3)\n |\n (v5)\n" }, { "code": null, "e": 1030, "s": 992, "text": "Total weight= 3 + 4 + 6 + 8 + 10 = 31" }, { "code": null, "e": 1211, "s": 1030, "text": "We can observe from above examples that when we add kth node, the weight of spanning tree increases by 2k-2. Let T(n) be the weight of minimum spanning tree. T(n) can be written as" }, { "code": null, "e": 1275, "s": 1211, "text": "T(n) = T(n-1) + (2n-2) for n > 2T(1) = 0, T(2) = 0 and T(2) = 3" }, { "code": null, "e": 1415, "s": 1275, "text": "The recurrence can be written as sum of series (2n – 2) + (2n-4) + (2n-6) + (2n-8) + .... 3 and solution of this recurrence is n^2 – n + 1." }, { "code": null, "e": 1526, "s": 1415, "text": "2) The length of the path from v5 to v6 in the MST of previous question with n = 10 is(A) 11(B) 25(C) 31(D) 41" }, { "code": null, "e": 1699, "s": 1526, "text": "Answer: (C)Any MST which has more than 5 nodes will have the same distance between v5 and v6 as the basic structure of all MSTs (with more than 5 nodes) would be following." }, { "code": null, "e": 1830, "s": 1699, "text": " (v1) _ (v2) _ (v4) _ (v6) _ . . (more even numbered nodes)\n |\n (v3)\n |\n (v5)\n |\n .\n .\n(more odd numbered nodes)\n" }, { "code": null, "e": 1883, "s": 1830, "text": "Distance between v5 and v6 = 3 + 4 + 6 + 8 + 10 = 31" }, { "code": null, "e": 2165, "s": 1883, "text": "3) Consider two binary operators ‘↑ ‘ and ‘↓’ with the precedence of operator ↓ being lower than that of the ↑ operator. Operator ↑ is right associative while operator ↓ is left associative. Which one of the following represents the parse tree for expression (7 ↓ 3 ­↑ 4 ­↑ 3 ↓ 2)?" }, { "code": null, "e": 2234, "s": 2165, "text": "Answer: (B)Let us consider the given expression (7 ↓ 3 ↑ 4 ↑ 3 ↓ 2)." }, { "code": null, "e": 2621, "s": 2234, "text": "Since the precedence of ↑ is higher, the sub-expression ([3 ↑ 4 ↑ 3) will be evaluated first. In this sub-expression, 4 ↑ 3 would be evaluated first because ↑ is right to left associative. So the expression is evaluated as ((7 ↓ (3 ↑ (4 ↑ 3))) ↓ 2). Also, note that among the two ↓ operators, first one is evaluated before the second one because the associativity of ↓ is left to right." }, { "code": null, "e": 2735, "s": 2621, "text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc." }, { "code": null, "e": 2884, "s": 2735, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above." }, { "code": null, "e": 2897, "s": 2884, "text": "GATE-CS-2011" }, { "code": null, "e": 2915, "s": 2897, "text": "GATE-CS-DS-&-Algo" }, { "code": null, "e": 2923, "s": 2915, "text": "GATE CS" }, { "code": null, "e": 2927, "s": 2923, "text": "MCQ" } ]
Regression with Categorical Variables in R Programming
12 Oct, 2020 Regression is a multi-step process for estimating the relationships between a dependent variable and one or more independent variables also known as predictors or covariates. Regression analysis is mainly used for two conceptually distinct purposes: for prediction and forecasting, where its use has substantial overlap with the field of machine learning and second it sometimes can be used to infer relationships between the independent and dependent variables. Categorical Variables are variables that can take on one of a limited and fixed, number of possible values, assigning each individual or other unit of observation to a particular group or nominal category on the basis of some qualitative property. They are also known as a factor or qualitative variables. The type of regression analysis that fits best with categorical variables is Logistic Regression. Logistic regression uses Maximum Likelihood Estimation to estimate the parameters. It derives the relationship between a set of variables(independent) and a categorical variable(dependent). It is very much easier to implement a regression model by using the R language because of its excellent libraries inside it. Now, let’s try to set up a logistic regression model with categorical variables for better understanding. Example: The objective is to predict whether a candidate will get admitted to a university with variables such as gre, gpa, and rank. The R script is provided side by side and is commented for better understanding of the user. The data is in .csv format. We will get the working directory with getwd() function and place out datasets binary.csv inside it to proceed further. Please download the CSV file here. R # preparing the dataset getwd() data <- read.csv("binary.csv" ) str(data) Output: 'data.frame': 400 obs. of 4 variables: $ admit: int 0 1 1 1 0 1 1 0 1 0 ... $ gre : int 380 660 800 640 520 760 560 400 540 700 ... $ gpa : num 3.61 3.67 4 3.19 2.93 3 2.98 3.08 3.39 3.92 ... $ rank : int 3 3 1 4 4 2 1 2 3 2 ... Looking at the structure of the datasets we can observe that it has 4 variables, where admit tells whether a candidate will get admitted or not admitted (1 if admitted and 0 if not admitted) gre, gpa, and rank give the candidates gre score, his/her gpa in the previous college and previous college rank respectively. We use admit as the dependent variable and gre, gpa, and rank as the independent variables. Now, note that admit and rank are categorical variables but are of numeric type. But in order to use them as categorical variables in our model, we will use as.factor() function to convert them into factor variables. R # converting admit and rank# columns into factor variablesdata$admit = as.factor(data$admit)data$rank = as.factor(data$rank) # two-way table of factor# variablextabs(~admit + rank, data = data) Output: rank admit 1 2 3 4 0 28 97 93 55 1 33 54 28 12 Now divide the data into a training set and test set. The training set is used to find the relationship between dependent and independent variables while the test set analyses the performance of the model. We use 60% of the dataset as a training set. The assignment of the data to training and test set is done using random sampling. We perform random sampling on R using sample() function. Use set.seed() to generate the same random sample every time and maintain consistency. R # Partitioning of dataset.seed(1234)data1<-sample(2, nrow(data), replace = T, prob = c(0.6, 0.4))train<-data[data1 == 1,]test<-data[data1 == 2,] Now build a logistic regression model for our data. glm() function helps us to establish a neural network for our data. The glm() function we are using here has the following syntax. Syntax: glm(formula, family = gaussian, data, weights, subset, na.action, start = NULL, etastart, mustart, offset, control = list(...), model = TRUE, method = “glm.fit”, x = FALSE, y = TRUE, singular.ok = TRUE, contrasts = NULL, ...) logical values indicating whether the response vector and model matrix used in the fitting process should be returned as components of the returned value. R mymodel<-glm(admit~gre + gpa + rank, data = train, family = 'binomial')summary(mymodel) Output: Call: glm(formula = admit ~ gre + gpa + rank, family = "binomial", data = train) Deviance Residuals: Min 1Q Median 3Q Max -1.6576 -0.8724 -0.6184 1.0683 2.1035 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) -4.972329 1.518865 -3.274 0.00106 ** gre 0.001449 0.001405 1.031 0.30270 gpa 1.233117 0.450550 2.737 0.00620 ** rank2 -0.784080 0.406376 -1.929 0.05368 . rank3 -1.203013 0.426614 -2.820 0.00480 ** rank4 -1.699652 0.536974 -3.165 0.00155 ** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 (Dispersion parameter for binomial family taken to be 1) Null deviance: 312.66 on 248 degrees of freedom Residual deviance: 283.38 on 243 degrees of freedom AIC: 295.38 Number of Fisher Scoring iterations: 4 From the summary of the model it is evident that gre has no significant role in predictions, so we can remove it from our model and rewrite it as follows: R mymodel<-glm(admit~gpa + rank, data = train, family = 'binomial') Now, let’s try to analyze our regression model by making some predictions. R # Predictionp1<-predict(mymodel, train, type = 'response')head(p1) Output: 1 7 8 10 12 13 0.3013327 0.3784012 0.2414806 0.5116852 0.4610888 0.7211702 R head(train) Output: admit gre gpa rank 1 0 380 3.61 3 7 1 560 2.98 1 8 0 400 3.08 2 10 0 700 3.92 2 12 0 440 3.22 1 13 1 760 4.00 1 Then, we round up our results by creating a confusion matrix to compare the number of true/false positives and negatives. We will form a confusion matrix with training data. R # confusion Matrix # $Misclassification error -Training data pre1<-ifelse(p1 > 0.5, 1, 0)table<-table(Prediction = pre1, Actual = train$admit) table Output: Actual Prediction 0 1 0 158 55 1 11 25 The model generates 158 true negatives (0’s), 25 true positives (1’s), while there are 11 false negatives and 55 false positives. Now, let’s calculate the misclassification error (for training data) which {1 – classification error} R 1 - sum(diag(table)) / sum(table) Output: [1] 0.2650602 The misclassification error comes out to be 24.9%. In this, we can use regression techniques with categorical variables to various other data. Regression Analysis is a very efficient method and there are numerous types of regression models that one can use. This choice often depends on the kind of data you have for the dependent variable and the type of model that provides the best fit like logistic regression is best suited for categorical variables. R regression R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Split Column Into Multiple Columns in R DataFrame? Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? How to import an Excel File into R ? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Oct, 2020" }, { "code": null, "e": 491, "s": 28, "text": "Regression is a multi-step process for estimating the relationships between a dependent variable and one or more independent variables also known as predictors or covariates. Regression analysis is mainly used for two conceptually distinct purposes: for prediction and forecasting, where its use has substantial overlap with the field of machine learning and second it sometimes can be used to infer relationships between the independent and dependent variables." }, { "code": null, "e": 1316, "s": 491, "text": "Categorical Variables are variables that can take on one of a limited and fixed, number of possible values, assigning each individual or other unit of observation to a particular group or nominal category on the basis of some qualitative property. They are also known as a factor or qualitative variables. The type of regression analysis that fits best with categorical variables is Logistic Regression. Logistic regression uses Maximum Likelihood Estimation to estimate the parameters. It derives the relationship between a set of variables(independent) and a categorical variable(dependent). It is very much easier to implement a regression model by using the R language because of its excellent libraries inside it. Now, let’s try to set up a logistic regression model with categorical variables for better understanding." }, { "code": null, "e": 1726, "s": 1316, "text": "Example: The objective is to predict whether a candidate will get admitted to a university with variables such as gre, gpa, and rank. The R script is provided side by side and is commented for better understanding of the user. The data is in .csv format. We will get the working directory with getwd() function and place out datasets binary.csv inside it to proceed further. Please download the CSV file here." }, { "code": null, "e": 1728, "s": 1726, "text": "R" }, { "code": "# preparing the dataset getwd() data <- read.csv(\"binary.csv\" ) str(data)", "e": 1802, "s": 1728, "text": null }, { "code": null, "e": 1810, "s": 1802, "text": "Output:" }, { "code": null, "e": 2054, "s": 1810, "text": "'data.frame': 400 obs. of 4 variables:\n $ admit: int 0 1 1 1 0 1 1 0 1 0 ...\n $ gre : int 380 660 800 640 520 760 560 400 540 700 ...\n $ gpa : num 3.61 3.67 4 3.19 2.93 3 2.98 3.08 3.39 3.92 ...\n $ rank : int 3 3 1 4 4 2 1 2 3 2 ...\n" }, { "code": null, "e": 2682, "s": 2054, "text": "Looking at the structure of the datasets we can observe that it has 4 variables, where admit tells whether a candidate will get admitted or not admitted (1 if admitted and 0 if not admitted) gre, gpa, and rank give the candidates gre score, his/her gpa in the previous college and previous college rank respectively. We use admit as the dependent variable and gre, gpa, and rank as the independent variables. Now, note that admit and rank are categorical variables but are of numeric type. But in order to use them as categorical variables in our model, we will use as.factor() function to convert them into factor variables." }, { "code": null, "e": 2684, "s": 2682, "text": "R" }, { "code": "# converting admit and rank# columns into factor variablesdata$admit = as.factor(data$admit)data$rank = as.factor(data$rank) # two-way table of factor# variablextabs(~admit + rank, data = data)", "e": 2879, "s": 2684, "text": null }, { "code": null, "e": 2887, "s": 2879, "text": "Output:" }, { "code": null, "e": 2952, "s": 2887, "text": " rank\nadmit 1 2 3 4\n 0 28 97 93 55\n 1 33 54 28 12\n" }, { "code": null, "e": 3430, "s": 2952, "text": "Now divide the data into a training set and test set. The training set is used to find the relationship between dependent and independent variables while the test set analyses the performance of the model. We use 60% of the dataset as a training set. The assignment of the data to training and test set is done using random sampling. We perform random sampling on R using sample() function. Use set.seed() to generate the same random sample every time and maintain consistency." }, { "code": null, "e": 3432, "s": 3430, "text": "R" }, { "code": "# Partitioning of dataset.seed(1234)data1<-sample(2, nrow(data), replace = T, prob = c(0.6, 0.4))train<-data[data1 == 1,]test<-data[data1 == 2,]", "e": 3613, "s": 3432, "text": null }, { "code": null, "e": 3796, "s": 3613, "text": "Now build a logistic regression model for our data. glm() function helps us to establish a neural network for our data. The glm() function we are using here has the following syntax." }, { "code": null, "e": 3804, "s": 3796, "text": "Syntax:" }, { "code": null, "e": 3911, "s": 3804, "text": "glm(formula, family = gaussian, data, weights, subset, na.action, start = NULL, etastart, mustart, offset," }, { "code": null, "e": 4036, "s": 3911, "text": " control = list(...), model = TRUE, method = “glm.fit”, x = FALSE, y = TRUE, singular.ok = TRUE, contrasts = NULL, ...)" }, { "code": null, "e": 4158, "s": 4036, "text": " logical values indicating whether the response vector and model matrix used in the fitting process should be returned as" }, { "code": null, "e": 4193, "s": 4158, "text": " components of the returned value." }, { "code": null, "e": 4195, "s": 4193, "text": "R" }, { "code": "mymodel<-glm(admit~gre + gpa + rank, data = train, family = 'binomial')summary(mymodel)", "e": 4331, "s": 4195, "text": null }, { "code": null, "e": 4339, "s": 4331, "text": "Output:" }, { "code": null, "e": 5212, "s": 4339, "text": "Call:\nglm(formula = admit ~ gre + gpa + rank, family = \"binomial\", \n data = train)\n\nDeviance Residuals: \n Min 1Q Median 3Q Max \n-1.6576 -0.8724 -0.6184 1.0683 2.1035 \n\nCoefficients:\n Estimate Std. Error z value Pr(>|z|) \n(Intercept) -4.972329 1.518865 -3.274 0.00106 **\ngre 0.001449 0.001405 1.031 0.30270 \ngpa 1.233117 0.450550 2.737 0.00620 **\nrank2 -0.784080 0.406376 -1.929 0.05368 . \nrank3 -1.203013 0.426614 -2.820 0.00480 **\nrank4 -1.699652 0.536974 -3.165 0.00155 **\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1\n\n(Dispersion parameter for binomial family taken to be 1)\n\n Null deviance: 312.66 on 248 degrees of freedom\nResidual deviance: 283.38 on 243 degrees of freedom\nAIC: 295.38\n\nNumber of Fisher Scoring iterations: 4\n" }, { "code": null, "e": 5367, "s": 5212, "text": "From the summary of the model it is evident that gre has no significant role in predictions, so we can remove it from our model and rewrite it as follows:" }, { "code": null, "e": 5369, "s": 5367, "text": "R" }, { "code": "mymodel<-glm(admit~gpa + rank, data = train, family = 'binomial')", "e": 5470, "s": 5369, "text": null }, { "code": null, "e": 5546, "s": 5470, "text": " Now, let’s try to analyze our regression model by making some predictions." }, { "code": null, "e": 5548, "s": 5546, "text": "R" }, { "code": "# Predictionp1<-predict(mymodel, train, type = 'response')head(p1)", "e": 5627, "s": 5548, "text": null }, { "code": null, "e": 5635, "s": 5627, "text": "Output:" }, { "code": null, "e": 5758, "s": 5635, "text": " 1 7 8 10 12 13 \n0.3013327 0.3784012 0.2414806 0.5116852 0.4610888 0.7211702 \n" }, { "code": null, "e": 5760, "s": 5758, "text": "R" }, { "code": "head(train)", "e": 5772, "s": 5760, "text": null }, { "code": null, "e": 5780, "s": 5772, "text": "Output:" }, { "code": null, "e": 5942, "s": 5780, "text": " admit gre gpa rank\n1 0 380 3.61 3\n7 1 560 2.98 1\n8 0 400 3.08 2\n10 0 700 3.92 2\n12 0 440 3.22 1\n13 1 760 4.00 1\n" }, { "code": null, "e": 6116, "s": 5942, "text": "Then, we round up our results by creating a confusion matrix to compare the number of true/false positives and negatives. We will form a confusion matrix with training data." }, { "code": null, "e": 6118, "s": 6116, "text": "R" }, { "code": "# confusion Matrix # $Misclassification error -Training data pre1<-ifelse(p1 > 0.5, 1, 0)table<-table(Prediction = pre1, Actual = train$admit) table", "e": 6281, "s": 6118, "text": null }, { "code": null, "e": 6289, "s": 6281, "text": "Output:" }, { "code": null, "e": 6364, "s": 6289, "text": " Actual\nPrediction 0 1\n 0 158 55\n 1 11 25\n" }, { "code": null, "e": 6597, "s": 6364, "text": "The model generates 158 true negatives (0’s), 25 true positives (1’s), while there are 11 false negatives and 55 false positives. Now, let’s calculate the misclassification error (for training data) which {1 – classification error}" }, { "code": null, "e": 6599, "s": 6597, "text": "R" }, { "code": "1 - sum(diag(table)) / sum(table)", "e": 6633, "s": 6599, "text": null }, { "code": null, "e": 6641, "s": 6633, "text": "Output:" }, { "code": null, "e": 6656, "s": 6641, "text": "[1] 0.2650602\n" }, { "code": null, "e": 6799, "s": 6656, "text": "The misclassification error comes out to be 24.9%. In this, we can use regression techniques with categorical variables to various other data." }, { "code": null, "e": 7112, "s": 6799, "text": "Regression Analysis is a very efficient method and there are numerous types of regression models that one can use. This choice often depends on the kind of data you have for the dependent variable and the type of model that provides the best fit like logistic regression is best suited for categorical variables." }, { "code": null, "e": 7125, "s": 7112, "text": "R regression" }, { "code": null, "e": 7136, "s": 7125, "text": "R Language" }, { "code": null, "e": 7234, "s": 7136, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7292, "s": 7234, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 7344, "s": 7292, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 7379, "s": 7344, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 7417, "s": 7379, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 7466, "s": 7417, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 7503, "s": 7466, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 7520, "s": 7503, "text": "R - if statement" }, { "code": null, "e": 7557, "s": 7520, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 7600, "s": 7557, "text": "Replace Specific Characters in String in R" } ]
PHP | imagerotate() Function
25 Oct, 2019 The imagerotate() function is an inbuilt function in PHP which is used to rotate an image with a given angle in degrees. The rotation center of the image is center. Syntax: resource imagerotate( $image, $angle, $bgd_color, $ignore_transparent = 0 ) Parameters: This function accepts four parameters as mentioned above and described below: $image: It is returned by one of the image creation functions, such as imagecreatetruecolor(). It is used to create size of image. $angle: This parameter holds the rotation angle in degrees. The rotation angle is used to rotate an image in anticlockwise direction. $bgd_color: This parameter holds the background color of uncovered zone after rotation. $ignore_transparent: If this parameter set and non-zero then transparent colors are ignored. Return Value: This function returns an image resource for the rotated image on success, or False on failure. Below programs illustrate the imagerotate() function in PHP: Program 1: <?php // Assign image file to variable $image_name = 'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-15.png'; // Load image file $image = imagecreatefrompng($image_name); // Use imagerotate() function to rotate the image$img = imagerotate($image, 180, 0); // Output image in the browser header("Content-type: image/png"); imagepng($img); ?> Output: Program 2: <?php // It create the size of image or blank image. $image = imagecreatetruecolor(500, 300); // Set the background color of image. $bg = imagecolorallocate($image, 205, 220, 200); // Fill background with above selected color. imagefill($image, 0, 0, $bg); // Set the color of an ellipse. $col_ellipse = imagecolorallocate($image, 0, 102, 0); // Function to draw the filled ellipse. imagefilledellipse($image, 250, 150, 400, 250, $col_ellipse); // Use imagerotate() function to rotate the image$img = imagerotate($image, 90, 0); // Output image in the browser header("Content-type: image/png"); imagepng($img); ?> Output: Reference: https://www.php.net/manual/en/function.imagerotate.php Akanksha_Rai PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Oct, 2019" }, { "code": null, "e": 193, "s": 28, "text": "The imagerotate() function is an inbuilt function in PHP which is used to rotate an image with a given angle in degrees. The rotation center of the image is center." }, { "code": null, "e": 201, "s": 193, "text": "Syntax:" }, { "code": null, "e": 278, "s": 201, "text": "resource imagerotate( $image, $angle, $bgd_color, $ignore_transparent = 0 ) " }, { "code": null, "e": 368, "s": 278, "text": "Parameters: This function accepts four parameters as mentioned above and described below:" }, { "code": null, "e": 499, "s": 368, "text": "$image: It is returned by one of the image creation functions, such as imagecreatetruecolor(). It is used to create size of image." }, { "code": null, "e": 633, "s": 499, "text": "$angle: This parameter holds the rotation angle in degrees. The rotation angle is used to rotate an image in anticlockwise direction." }, { "code": null, "e": 721, "s": 633, "text": "$bgd_color: This parameter holds the background color of uncovered zone after rotation." }, { "code": null, "e": 814, "s": 721, "text": "$ignore_transparent: If this parameter set and non-zero then transparent colors are ignored." }, { "code": null, "e": 923, "s": 814, "text": "Return Value: This function returns an image resource for the rotated image on success, or False on failure." }, { "code": null, "e": 984, "s": 923, "text": "Below programs illustrate the imagerotate() function in PHP:" }, { "code": null, "e": 995, "s": 984, "text": "Program 1:" }, { "code": "<?php // Assign image file to variable $image_name = 'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-15.png'; // Load image file $image = imagecreatefrompng($image_name); // Use imagerotate() function to rotate the image$img = imagerotate($image, 180, 0); // Output image in the browser header(\"Content-type: image/png\"); imagepng($img); ?> ", "e": 1372, "s": 995, "text": null }, { "code": null, "e": 1380, "s": 1372, "text": "Output:" }, { "code": null, "e": 1391, "s": 1380, "text": "Program 2:" }, { "code": "<?php // It create the size of image or blank image. $image = imagecreatetruecolor(500, 300); // Set the background color of image. $bg = imagecolorallocate($image, 205, 220, 200); // Fill background with above selected color. imagefill($image, 0, 0, $bg); // Set the color of an ellipse. $col_ellipse = imagecolorallocate($image, 0, 102, 0); // Function to draw the filled ellipse. imagefilledellipse($image, 250, 150, 400, 250, $col_ellipse); // Use imagerotate() function to rotate the image$img = imagerotate($image, 90, 0); // Output image in the browser header(\"Content-type: image/png\"); imagepng($img); ?> ", "e": 2036, "s": 1391, "text": null }, { "code": null, "e": 2044, "s": 2036, "text": "Output:" }, { "code": null, "e": 2110, "s": 2044, "text": "Reference: https://www.php.net/manual/en/function.imagerotate.php" }, { "code": null, "e": 2123, "s": 2110, "text": "Akanksha_Rai" }, { "code": null, "e": 2136, "s": 2123, "text": "PHP-function" }, { "code": null, "e": 2140, "s": 2136, "text": "PHP" }, { "code": null, "e": 2157, "s": 2140, "text": "Web Technologies" }, { "code": null, "e": 2161, "s": 2157, "text": "PHP" } ]
GATE | GATE-CS-2014-(Set-1) | Question 65
17 Sep, 2021 Which one of the following is FALSE?(A) A basic block is a sequence of instructions where control enters the sequence at the beginning and exits at the end.(B) Available expression analysis can be used for common subexpression elimination.(C) Live variable analysis can be used for dead code elimination.(D) x = 4 ∗ 5 => x = 20 is an example of common subexpression elimination.Answer: (D)Explanation: (A) A basic block is a sequence of instructions where control enters the sequence at the beginning and exits at the end is TRUE. (B) Available expression analysis can be used for common subexpression elimination is TRUE. Available expressions is an analysis algorithm that determines for each point in the program the set of expressions that need not be recomputed. Available expression analysis is used to do global common subexpression elimination (CSE). If an expression is available at a point, there is no need to re-evaluate it. (C)Live variable analysis can be used for dead code elimination is TRUE. (D) x = 4 ∗ 5 => x = 20 is an example of common subexpression elimination is FALSE.Common subexpression elimination (CSE) refers to compiler optimization replaces identical expressions (i.e., they all evaluate to the same value) with a single variable holding the computed value when it is worthwhile to do so. Below is an example In the following code: a = b * c + g; d = b * c * e; it may be worth transforming the code to: tmp = b * c; a = tmp + g; d = tmp * e; Sources:https://en.wikipedia.org/wiki/Common_subexpression_eliminationhttps://en.wikipedia.org/wiki/Available_expression GATE PYQ - Code Generation and Optimization (Continued...) | Joyojyoti Acharya |GeeksforGeeks GATE | - YouTubeGeeksforGeeks GATE Computer Science17.4K subscribersGATE PYQ - Code Generation and Optimization (Continued...) | Joyojyoti Acharya |GeeksforGeeks GATE |Watch 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:007:31 / 38:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mNG-F-8t3a4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2014-(Set-1) GATE-GATE-CS-2014-(Set-1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | Gate IT 2005 | Question 52 GATE | GATE CS 1996 | Question 63 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 1997 | Question 50 GATE | GATE-CS-2015 (Set 2) | Question 65 GATE | GATE-CS-2001 | Question 50 GATE | GATE CS 2013 | Question 43
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Sep, 2021" }, { "code": null, "e": 583, "s": 52, "text": "Which one of the following is FALSE?(A) A basic block is a sequence of instructions where control enters the sequence at the beginning and exits at the end.(B) Available expression analysis can be used for common subexpression elimination.(C) Live variable analysis can be used for dead code elimination.(D) x = 4 ∗ 5 => x = 20 is an example of common subexpression elimination.Answer: (D)Explanation: (A) A basic block is a sequence of instructions where control enters the sequence at the beginning and exits at the end is TRUE." }, { "code": null, "e": 989, "s": 583, "text": "(B) Available expression analysis can be used for common subexpression elimination is TRUE. Available expressions is an analysis algorithm that determines for each point in the program the set of expressions that need not be recomputed. Available expression analysis is used to do global common subexpression elimination (CSE). If an expression is available at a point, there is no need to re-evaluate it." }, { "code": null, "e": 1062, "s": 989, "text": "(C)Live variable analysis can be used for dead code elimination is TRUE." }, { "code": null, "e": 1373, "s": 1062, "text": "(D) x = 4 ∗ 5 => x = 20 is an example of common subexpression elimination is FALSE.Common subexpression elimination (CSE) refers to compiler optimization replaces identical expressions (i.e., they all evaluate to the same value) with a single variable holding the computed value when it is worthwhile to do so." }, { "code": null, "e": 1393, "s": 1373, "text": "Below is an example" }, { "code": null, "e": 1530, "s": 1393, "text": "In the following code:\n\na = b * c + g;\nd = b * c * e;\n\nit may be worth transforming the code to:\n\ntmp = b * c;\na = tmp + g;\nd = tmp * e;" }, { "code": null, "e": 1651, "s": 1530, "text": "Sources:https://en.wikipedia.org/wiki/Common_subexpression_eliminationhttps://en.wikipedia.org/wiki/Available_expression" }, { "code": null, "e": 2682, "s": 1651, "text": "GATE PYQ - Code Generation and Optimization (Continued...) | Joyojyoti Acharya |GeeksforGeeks GATE | - YouTubeGeeksforGeeks GATE Computer Science17.4K subscribersGATE PYQ - Code Generation and Optimization (Continued...) | Joyojyoti Acharya |GeeksforGeeks GATE |Watch 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:007:31 / 38:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=mNG-F-8t3a4\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 2703, "s": 2682, "text": "GATE-CS-2014-(Set-1)" }, { "code": null, "e": 2729, "s": 2703, "text": "GATE-GATE-CS-2014-(Set-1)" }, { "code": null, "e": 2734, "s": 2729, "text": "GATE" }, { "code": null, "e": 2832, "s": 2734, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2874, "s": 2832, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 2936, "s": 2874, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 2978, "s": 2936, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 3012, "s": 2978, "text": "GATE | Gate IT 2005 | Question 52" }, { "code": null, "e": 3046, "s": 3012, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 3088, "s": 3046, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 3122, "s": 3088, "text": "GATE | GATE CS 1997 | Question 50" }, { "code": null, "e": 3164, "s": 3122, "text": "GATE | GATE-CS-2015 (Set 2) | Question 65" }, { "code": null, "e": 3198, "s": 3164, "text": "GATE | GATE-CS-2001 | Question 50" } ]
Network Scanning using scapy module – Python
01 Mar, 2020 Scapy is a library supported by both Python2 and Python3. It is used for interacting with the packets on the network. It has several functionalities through which we can easily forge and manipulate the packet. Through scapy module we can create different network tools like ARP Spoofer, Network Scanner, packet dumpers etc. This module can be used to create more advanced tools related network security and ethical hacking. Installation of scapy module:As scapy module is not included in Python3 library by default, we have to add it into our Python library using pip. Execute this command in your Linux terminal to get the scapy module for Python3. pip3 install scapy-python3 What is network scanning ?Network scanning refers to scanning of whole network to which we are connected and try to find out what are all the clients connected to our network. We can identify each and every client using their IP and MAC address. We can use ARP ping to find out the alive systems in our network. ARP(): This function defined in scapy module which allows us to create ARP packets (request or response). By default, if we are calling it, it will create an ARP request packet for us. import scapy.all as scapy request = scapy.ARP() summary(): This method provide us the status of the packet that we have created. It does not provide the detailed information about the packet, it just gives us the basic idea like what is the type of packet, what is the destination of the packet etc.For example if we want to create an ARP packet using ARP() method which is present in the scapy module and want to see the summary of the packet then we can do this by creating the object of ARP class. import scapy.all as scapy request = scapy.ARP()print(request.summary()) Now we have created a request packet of ARP. Here the output of the program will be like this – show() method: This method is very similar to summary() method. It gives more detailed information about the packet. The usage of this function is also much similar to as summary() method. import scapy.all as scapy request = scapy.ARP()print(request.show()) ls() function: This method is present in the scapy class. By using this method, we can see what are the fields that we can set for a specific packet.In our example we will create an ARP packet and the with the help of ls() function, we will see what are the available fields for this packet. import scapy.all as scapy request = scapy.ARP()print(scapy.ls(scapy.ARP())) Steps for creating Network Scanner – 1. Create an ARP packet using ARP() method.2. Set the network range using variable.3. Create an Ethernet packet using Ether() method.4. Set the destination to broadcast using variable hwdst.5. Combine ARP request packet and Ethernet frame using ‘/’.6. Send this to your network and capture the response from different devices.7. Print the IP and MAC address from the response packets. Below is the Python implementation – import scapy.all as scapy request = scapy.ARP() request.pdst = 'x'broadcast = scapy.Ether() broadcast.dst = 'ff:ff:ff:ff:ff:ff' request_broadcast = broadcast / requestclients = scapy.srp(request_broadcast, timeout = 1)[0]for element in clients: print(element[1].psrc + " " + element[1].hwsrc) Here x = Network range. For example x = 192.168.1.1/24, 172.16.5.1/16 etc Output: python-utility Technical Scripter 2019 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Mar, 2020" }, { "code": null, "e": 478, "s": 54, "text": "Scapy is a library supported by both Python2 and Python3. It is used for interacting with the packets on the network. It has several functionalities through which we can easily forge and manipulate the packet. Through scapy module we can create different network tools like ARP Spoofer, Network Scanner, packet dumpers etc. This module can be used to create more advanced tools related network security and ethical hacking." }, { "code": null, "e": 704, "s": 478, "text": "Installation of scapy module:As scapy module is not included in Python3 library by default, we have to add it into our Python library using pip. Execute this command in your Linux terminal to get the scapy module for Python3." }, { "code": null, "e": 731, "s": 704, "text": "pip3 install scapy-python3" }, { "code": null, "e": 1043, "s": 731, "text": "What is network scanning ?Network scanning refers to scanning of whole network to which we are connected and try to find out what are all the clients connected to our network. We can identify each and every client using their IP and MAC address. We can use ARP ping to find out the alive systems in our network." }, { "code": null, "e": 1228, "s": 1043, "text": "ARP(): This function defined in scapy module which allows us to create ARP packets (request or response). By default, if we are calling it, it will create an ARP request packet for us." }, { "code": "import scapy.all as scapy request = scapy.ARP()", "e": 1277, "s": 1228, "text": null }, { "code": null, "e": 1730, "s": 1277, "text": "summary(): This method provide us the status of the packet that we have created. It does not provide the detailed information about the packet, it just gives us the basic idea like what is the type of packet, what is the destination of the packet etc.For example if we want to create an ARP packet using ARP() method which is present in the scapy module and want to see the summary of the packet then we can do this by creating the object of ARP class." }, { "code": "import scapy.all as scapy request = scapy.ARP()print(request.summary())", "e": 1803, "s": 1730, "text": null }, { "code": null, "e": 1899, "s": 1803, "text": "Now we have created a request packet of ARP. Here the output of the program will be like this –" }, { "code": null, "e": 2088, "s": 1899, "text": "show() method: This method is very similar to summary() method. It gives more detailed information about the packet. The usage of this function is also much similar to as summary() method." }, { "code": "import scapy.all as scapy request = scapy.ARP()print(request.show())", "e": 2158, "s": 2088, "text": null }, { "code": null, "e": 2450, "s": 2158, "text": "ls() function: This method is present in the scapy class. By using this method, we can see what are the fields that we can set for a specific packet.In our example we will create an ARP packet and the with the help of ls() function, we will see what are the available fields for this packet." }, { "code": "import scapy.all as scapy request = scapy.ARP()print(scapy.ls(scapy.ARP()))", "e": 2527, "s": 2450, "text": null }, { "code": null, "e": 2564, "s": 2527, "text": "Steps for creating Network Scanner –" }, { "code": null, "e": 2949, "s": 2564, "text": "1. Create an ARP packet using ARP() method.2. Set the network range using variable.3. Create an Ethernet packet using Ether() method.4. Set the destination to broadcast using variable hwdst.5. Combine ARP request packet and Ethernet frame using ‘/’.6. Send this to your network and capture the response from different devices.7. Print the IP and MAC address from the response packets." }, { "code": null, "e": 2986, "s": 2949, "text": "Below is the Python implementation –" }, { "code": "import scapy.all as scapy request = scapy.ARP() request.pdst = 'x'broadcast = scapy.Ether() broadcast.dst = 'ff:ff:ff:ff:ff:ff' request_broadcast = broadcast / requestclients = scapy.srp(request_broadcast, timeout = 1)[0]for element in clients: print(element[1].psrc + \" \" + element[1].hwsrc)", "e": 3291, "s": 2986, "text": null }, { "code": null, "e": 3365, "s": 3291, "text": "Here x = Network range. For example x = 192.168.1.1/24, 172.16.5.1/16 etc" }, { "code": null, "e": 3373, "s": 3365, "text": "Output:" }, { "code": null, "e": 3388, "s": 3373, "text": "python-utility" }, { "code": null, "e": 3412, "s": 3388, "text": "Technical Scripter 2019" }, { "code": null, "e": 3419, "s": 3412, "text": "Python" }, { "code": null, "e": 3438, "s": 3419, "text": "Technical Scripter" } ]
How to get a Date from year, month and day in Java?
The of() method of the java.time.LocalDate class accepts the values of the year, month, and day of month as parameters, creates and returns an object of the LocalDate. Live Demo import java.time.LocalDate; public class Test { public static void main(String[] args) { LocalDate date = LocalDate.of(2014, 9, 11); System.out.println("Date Value: "+date); } } Date Value: 2014-09-11 Date Value: 2014-09-11 One of the constructors of the java.util.GregorianCalendar class accepts the values of year, month and day of month as values and creates a Calendar object representing it. import java.util.*; class Test { public static void main(String args[]){ //Creating a calendar object Calendar cal = new GregorianCalendar(2020, 07, 18); int day = cal.get(Calendar.DAY_OF_MONTH); int month = cal.get(Calendar.MONTH); int year = cal.get(Calendar.YEAR); System.out.println("Day: " + day); System.out.println("Month: " + month); System.out.println("Year: " + year); } } Day: 18 Month: 7 Year: 2020 One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat object. To parse/convert a string as a Date object − Instantiate this class by passing desired format string. Parse the date string using the parse() method. Live Demo import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Sample { public static void main(String args[]) throws ParseException { String date_string = "2007-25-06"; //Instantiating the SimpleDateFormat class SimpleDateFormat formatter = new SimpleDateFormat("yyyy-dd-MM"); //Parsing the given String to Date object Date date = formatter.parse(date_string); System.out.println("Date value: "+date); } } Date value: Mon Jun 25 00:00:00 IST 2007
[ { "code": null, "e": 1230, "s": 1062, "text": "The of() method of the java.time.LocalDate class accepts the values of the year, month, and day of month as parameters, creates and returns an object of the LocalDate." }, { "code": null, "e": 1240, "s": 1230, "text": "Live Demo" }, { "code": null, "e": 1436, "s": 1240, "text": "import java.time.LocalDate;\npublic class Test {\n public static void main(String[] args) {\n LocalDate date = LocalDate.of(2014, 9, 11);\n System.out.println(\"Date Value: \"+date);\n }\n}" }, { "code": null, "e": 1459, "s": 1436, "text": "Date Value: 2014-09-11" }, { "code": null, "e": 1482, "s": 1459, "text": "Date Value: 2014-09-11" }, { "code": null, "e": 1655, "s": 1482, "text": "One of the constructors of the java.util.GregorianCalendar class accepts the values of year, month and day of month as values and creates a Calendar object representing it." }, { "code": null, "e": 2095, "s": 1655, "text": "import java.util.*;\nclass Test { \n public static void main(String args[]){\n //Creating a calendar object\n Calendar cal = new GregorianCalendar(2020, 07, 18);\n int day = cal.get(Calendar.DAY_OF_MONTH);\n int month = cal.get(Calendar.MONTH);\n int year = cal.get(Calendar.YEAR);\n System.out.println(\"Day: \" + day);\n System.out.println(\"Month: \" + month);\n System.out.println(\"Year: \" + year);\n }\n}" }, { "code": null, "e": 2123, "s": 2095, "text": "Day: 18\nMonth: 7\nYear: 2020" }, { "code": null, "e": 2303, "s": 2123, "text": "One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat object. To parse/convert a string as a Date object −" }, { "code": null, "e": 2360, "s": 2303, "text": "Instantiate this class by passing desired format string." }, { "code": null, "e": 2408, "s": 2360, "text": "Parse the date string using the parse() method." }, { "code": null, "e": 2418, "s": 2408, "text": "Live Demo" }, { "code": null, "e": 2922, "s": 2418, "text": "import java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\npublic class Sample {\n public static void main(String args[]) throws ParseException { \n String date_string = \"2007-25-06\";\n //Instantiating the SimpleDateFormat class\n SimpleDateFormat formatter = new SimpleDateFormat(\"yyyy-dd-MM\"); \n //Parsing the given String to Date object\n Date date = formatter.parse(date_string); \n System.out.println(\"Date value: \"+date);\n }\n}" }, { "code": null, "e": 2963, "s": 2922, "text": "Date value: Mon Jun 25 00:00:00 IST 2007" } ]
turtle.setpos() and turtle.goto() functions in Python - GeeksforGeeks
17 Jul, 2020 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This method is used to move the turtle to an absolute position. This method has Aliases: setpos, setposition, goto. Syntax: turtle.setpos(x, y=None) or turtle.setposition(x, y=None) or turtle.goto(x, y=None) Parameters: x: x coordinate of a Vec2D-vector y: y coordinate of a Vec2D-vector Below is the implementation of above method with some examples : Example 1: Python3 # import packageimport turtle # forward turtle by 100turtle.forward(100) # stamp the turtle shapeturtle.stamp() # set the position by using setpos()turtle.up()turtle.setpos(-50,50)turtle.down() # forward turtle by 100turtle.forward(100) # stamp the turtle shapeturtle.stamp() # set the position by using goto()turtle.up()turtle.goto(-50,-50)turtle.down() # forward turtle by 100turtle.forward(100) Output : Example 2 : Python3 # import packageimport turtle # method to raw pattern# of circle with rad radiusdef draw(rad): # draw circle turtle.circle(rad) # set the position by using setpos() turtle.up() turtle.setpos(0,-rad) turtle.down() # loop for patternfor i in range(5): draw(20+20*i) Output : Python-turtle 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 | Pandas dataframe.groupby() Create a directory in Python Defaultdict in Python Python | Get unique values from a list
[ { "code": null, "e": 25672, "s": 25644, "text": "\n17 Jul, 2020" }, { "code": null, "e": 25889, "s": 25672, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 26005, "s": 25889, "text": "This method is used to move the turtle to an absolute position. This method has Aliases: setpos, setposition, goto." }, { "code": null, "e": 26097, "s": 26005, "text": "Syntax: turtle.setpos(x, y=None) or turtle.setposition(x, y=None) or turtle.goto(x, y=None)" }, { "code": null, "e": 26109, "s": 26097, "text": "Parameters:" }, { "code": null, "e": 26144, "s": 26109, "text": "x: x coordinate of a Vec2D-vector " }, { "code": null, "e": 26178, "s": 26144, "text": "y: y coordinate of a Vec2D-vector" }, { "code": null, "e": 26243, "s": 26178, "text": "Below is the implementation of above method with some examples :" }, { "code": null, "e": 26254, "s": 26243, "text": "Example 1:" }, { "code": null, "e": 26262, "s": 26254, "text": "Python3" }, { "code": "# import packageimport turtle # forward turtle by 100turtle.forward(100) # stamp the turtle shapeturtle.stamp() # set the position by using setpos()turtle.up()turtle.setpos(-50,50)turtle.down() # forward turtle by 100turtle.forward(100) # stamp the turtle shapeturtle.stamp() # set the position by using goto()turtle.up()turtle.goto(-50,-50)turtle.down() # forward turtle by 100turtle.forward(100)", "e": 26668, "s": 26262, "text": null }, { "code": null, "e": 26677, "s": 26668, "text": "Output :" }, { "code": null, "e": 26689, "s": 26677, "text": "Example 2 :" }, { "code": null, "e": 26697, "s": 26689, "text": "Python3" }, { "code": "# import packageimport turtle # method to raw pattern# of circle with rad radiusdef draw(rad): # draw circle turtle.circle(rad) # set the position by using setpos() turtle.up() turtle.setpos(0,-rad) turtle.down() # loop for patternfor i in range(5): draw(20+20*i)", "e": 26997, "s": 26697, "text": null }, { "code": null, "e": 27006, "s": 26997, "text": "Output :" }, { "code": null, "e": 27020, "s": 27006, "text": "Python-turtle" }, { "code": null, "e": 27027, "s": 27020, "text": "Python" }, { "code": null, "e": 27125, "s": 27027, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27157, "s": 27125, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27199, "s": 27157, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27241, "s": 27199, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27297, "s": 27241, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27324, "s": 27297, "text": "Python Classes and Objects" }, { "code": null, "e": 27355, "s": 27324, "text": "Python | os.path.join() method" }, { "code": null, "e": 27391, "s": 27355, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27420, "s": 27391, "text": "Create a directory in Python" }, { "code": null, "e": 27442, "s": 27420, "text": "Defaultdict in Python" } ]
Combining Matrices in R - GeeksforGeeks
07 Sep, 2021 Combining matrices involves the concatenation of two or more smaller matrices, either row or column wise to form a larger matrix. It is basically a data manipulation operation where the involved matrices must be of compatible sizes to execute the operation. Matrices can be combined either horizontally or vertically. There are two ways of combining matrices in R: Column-wise combination Row-wise Combination Column bind, cbind() function in R, is used to merge two data frames or matrices (n may or may not be equal to p) together by their columns. The matrices involved should have the same number of rows. Example: Python3 # R program for combining two matrices# column-wise # Creating 1st MatrixB = matrix(c(1, 2), nrow = 1, ncol = 2) # Creating 2nd MatrixC = matrix(c(3, 4, 5), nrow = 1, ncol = 3) # Original Matricesprint(B)print(C) # Combining matricesprint (cbind(B, C)) Output: [,1] [,2] [1,] 1 2 [,1] [,2] [,3] [1,] 3 4 5 [,1] [,2] [,3] [,4] [,5] [1,] 1 2 3 4 5 In the above code, the columns [3 4 5] of matrix C are added in order to the columns [1 2] of the matrix B. These changes are not made to any of the existing matrices. Properties: The number of columns of the resultant matrix is the sum of the columns of the two matrices. Non-Commutative: The columns are merged in the order in which the parameters are specified in the function. Therefore, cbind(a, b) != cbind(b, a) Associative: cbind(cbind(a, b), c) = cbind(a, cbind(b, c)) Row bind, rbind() function in R, is used to merge two data frames or matrices (m may or may not be equal to n), together by their rows. The matrices involved should have the same number of columns. Example: Python3 # R program for combining two matrices# row-wise # Creating 1st MatrixB = matrix(c(1, 2, 3), nrow = 1, ncol = 3) # Creating 2nd MatrixC = matrix(c(4, 5, 6, 7, 8, 9), nrow = 2, ncol = 3) # Original Matricesprint(B)print(C) # Combining matricesprint (rbind(B, C)) Output: [,1] [,2] [,3] [1,] 1 2 3 [,1] [,2] [,3] [1,] 4 6 8 [2,] 5 7 9 [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 6 8 [3,] 5 7 9 The rows [4 6 8] and [5 7 9] are appended to a row of matrix B[1 2 3] in order. No changes are made to the original matrices. Properties: The number of rows of the resultant matrix is the sum of the rows of the two matrices. Non-Commutative: The rows are merged in the order in which the parameters are specified in the function. Therefore, rbind(a, b) != rbind(b, a) Associative: rbind(rbind(a, b), c) = rbind(a, rbind(b, c)) Time Complexity: O(m+n) Space Complexity: O(m+n), where m is the total number of elements of first matrix and n of the second matrix. adnanirshad158 Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? Printing Output of an R Program Remove rows with NA in one column of R DataFrame Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame?
[ { "code": null, "e": 24598, "s": 24570, "text": "\n07 Sep, 2021" }, { "code": null, "e": 24917, "s": 24598, "text": "Combining matrices involves the concatenation of two or more smaller matrices, either row or column wise to form a larger matrix. It is basically a data manipulation operation where the involved matrices must be of compatible sizes to execute the operation. Matrices can be combined either horizontally or vertically. " }, { "code": null, "e": 24966, "s": 24917, "text": "There are two ways of combining matrices in R: " }, { "code": null, "e": 24990, "s": 24966, "text": "Column-wise combination" }, { "code": null, "e": 25011, "s": 24990, "text": "Row-wise Combination" }, { "code": null, "e": 25213, "s": 25011, "text": "Column bind, cbind() function in R, is used to merge two data frames or matrices (n may or may not be equal to p) together by their columns. The matrices involved should have the same number of rows. " }, { "code": null, "e": 25224, "s": 25213, "text": "Example: " }, { "code": null, "e": 25232, "s": 25224, "text": "Python3" }, { "code": "# R program for combining two matrices# column-wise # Creating 1st MatrixB = matrix(c(1, 2), nrow = 1, ncol = 2) # Creating 2nd MatrixC = matrix(c(3, 4, 5), nrow = 1, ncol = 3) # Original Matricesprint(B)print(C) # Combining matricesprint (cbind(B, C))", "e": 25485, "s": 25232, "text": null }, { "code": null, "e": 25494, "s": 25485, "text": "Output: " }, { "code": null, "e": 25624, "s": 25494, "text": " [,1] [,2]\n[1,] 1 2\n [,1] [,2] [,3]\n[1,] 3 4 5\n [,1] [,2] [,3] [,4] [,5]\n[1,] 1 2 3 4 5" }, { "code": null, "e": 25793, "s": 25624, "text": "In the above code, the columns [3 4 5] of matrix C are added in order to the columns [1 2] of the matrix B. These changes are not made to any of the existing matrices. " }, { "code": null, "e": 25807, "s": 25793, "text": "Properties: " }, { "code": null, "e": 25900, "s": 25807, "text": "The number of columns of the resultant matrix is the sum of the columns of the two matrices." }, { "code": null, "e": 26046, "s": 25900, "text": "Non-Commutative: The columns are merged in the order in which the parameters are specified in the function. Therefore, cbind(a, b) != cbind(b, a)" }, { "code": null, "e": 26106, "s": 26046, "text": "Associative: cbind(cbind(a, b), c) = cbind(a, cbind(b, c)) " }, { "code": null, "e": 26306, "s": 26106, "text": "Row bind, rbind() function in R, is used to merge two data frames or matrices (m may or may not be equal to n), together by their rows. The matrices involved should have the same number of columns. " }, { "code": null, "e": 26316, "s": 26306, "text": "Example: " }, { "code": null, "e": 26324, "s": 26316, "text": "Python3" }, { "code": "# R program for combining two matrices# row-wise # Creating 1st MatrixB = matrix(c(1, 2, 3), nrow = 1, ncol = 3) # Creating 2nd MatrixC = matrix(c(4, 5, 6, 7, 8, 9), nrow = 2, ncol = 3) # Original Matricesprint(B)print(C) # Combining matricesprint (rbind(B, C))", "e": 26586, "s": 26324, "text": null }, { "code": null, "e": 26595, "s": 26586, "text": "Output: " }, { "code": null, "e": 26775, "s": 26595, "text": " [,1] [,2] [,3]\n[1,] 1 2 3\n [,1] [,2] [,3]\n[1,] 4 6 8\n[2,] 5 7 9\n [,1] [,2] [,3]\n[1,] 1 2 3\n[2,] 4 6 8\n[3,] 5 7 9" }, { "code": null, "e": 26902, "s": 26775, "text": "The rows [4 6 8] and [5 7 9] are appended to a row of matrix B[1 2 3] in order. No changes are made to the original matrices. " }, { "code": null, "e": 26916, "s": 26902, "text": "Properties: " }, { "code": null, "e": 27003, "s": 26916, "text": "The number of rows of the resultant matrix is the sum of the rows of the two matrices." }, { "code": null, "e": 27146, "s": 27003, "text": "Non-Commutative: The rows are merged in the order in which the parameters are specified in the function. Therefore, rbind(a, b) != rbind(b, a)" }, { "code": null, "e": 27206, "s": 27146, "text": "Associative: rbind(rbind(a, b), c) = rbind(a, rbind(b, c)) " }, { "code": null, "e": 27342, "s": 27206, "text": "Time Complexity: O(m+n) Space Complexity: O(m+n), where m is the total number of elements of first matrix and n of the second matrix. " }, { "code": null, "e": 27357, "s": 27342, "text": "adnanirshad158" }, { "code": null, "e": 27364, "s": 27357, "text": "Picked" }, { "code": null, "e": 27375, "s": 27364, "text": "R Language" }, { "code": null, "e": 27473, "s": 27375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27482, "s": 27473, "text": "Comments" }, { "code": null, "e": 27495, "s": 27482, "text": "Old Comments" }, { "code": null, "e": 27553, "s": 27495, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 27605, "s": 27553, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27637, "s": 27605, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27689, "s": 27637, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27733, "s": 27689, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27771, "s": 27733, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27803, "s": 27771, "text": "Printing Output of an R Program" }, { "code": null, "e": 27852, "s": 27803, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 27887, "s": 27852, "text": "Group by function in R using Dplyr" } ]
Insert Image in a Jupyter Notebook - GeeksforGeeks
28 Nov, 2021 In this article, we will discuss how to insert images in a Jupyter Notebook. There are a few ways to insert images. These are – Direct insertion using the edit menu. Embedding in a markdown cell By python code ( embedding an image in a code cell). Step 1: This method is the easiest. first, change the type of the cell to -> markdown. Step 2: After that click edit in the jupyter notebook menu. after that click ‘insert image’. Edit -> insert image. Step 3: After that, a dialogue box opens up and asks us to locate the file. Click on ‘ok’. There are different ways to embed an image in markdown. below is an example of direct embedding: Python3 ![SNOWFALL](snowfall4.jpeg) Output: A code cell can also be used to embed images. To display the image, the Ipython.display() method necessitates the use of a function. In the notebook, you can also specify the width and height of the image. Python3 # import image modulefrom IPython.display import Image # get the imageImage(url="snowfall4.jpeg", width=300, height=300) Output: Jupyter-notebook Picked 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 Defaultdict in Python Python Classes and Objects Create a directory in Python Python | os.path.join() method Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 24390, "s": 24362, "text": "\n28 Nov, 2021" }, { "code": null, "e": 24518, "s": 24390, "text": "In this article, we will discuss how to insert images in a Jupyter Notebook. There are a few ways to insert images. These are –" }, { "code": null, "e": 24556, "s": 24518, "text": "Direct insertion using the edit menu." }, { "code": null, "e": 24585, "s": 24556, "text": "Embedding in a markdown cell" }, { "code": null, "e": 24638, "s": 24585, "text": "By python code ( embedding an image in a code cell)." }, { "code": null, "e": 24727, "s": 24638, "text": "Step 1: This method is the easiest. first, change the type of the cell to -> markdown." }, { "code": null, "e": 24842, "s": 24727, "text": "Step 2: After that click edit in the jupyter notebook menu. after that click ‘insert image’. Edit -> insert image." }, { "code": null, "e": 24933, "s": 24842, "text": "Step 3: After that, a dialogue box opens up and asks us to locate the file. Click on ‘ok’." }, { "code": null, "e": 25031, "s": 24933, "text": "There are different ways to embed an image in markdown. below is an example of direct embedding:" }, { "code": null, "e": 25039, "s": 25031, "text": "Python3" }, { "code": "![SNOWFALL](snowfall4.jpeg)", "e": 25067, "s": 25039, "text": null }, { "code": null, "e": 25075, "s": 25067, "text": "Output:" }, { "code": null, "e": 25281, "s": 25075, "text": "A code cell can also be used to embed images. To display the image, the Ipython.display() method necessitates the use of a function. In the notebook, you can also specify the width and height of the image." }, { "code": null, "e": 25289, "s": 25281, "text": "Python3" }, { "code": "# import image modulefrom IPython.display import Image # get the imageImage(url=\"snowfall4.jpeg\", width=300, height=300)", "e": 25411, "s": 25289, "text": null }, { "code": null, "e": 25419, "s": 25411, "text": "Output:" }, { "code": null, "e": 25436, "s": 25419, "text": "Jupyter-notebook" }, { "code": null, "e": 25443, "s": 25436, "text": "Picked" }, { "code": null, "e": 25450, "s": 25443, "text": "Python" }, { "code": null, "e": 25548, "s": 25450, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25580, "s": 25548, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25622, "s": 25580, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25664, "s": 25622, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25720, "s": 25664, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25742, "s": 25720, "text": "Defaultdict in Python" }, { "code": null, "e": 25769, "s": 25742, "text": "Python Classes and Objects" }, { "code": null, "e": 25798, "s": 25769, "text": "Create a directory in Python" }, { "code": null, "e": 25829, "s": 25798, "text": "Python | os.path.join() method" }, { "code": null, "e": 25865, "s": 25829, "text": "Python | Pandas dataframe.groupby()" } ]
Array of Objects in C++ with Examples - GeeksforGeeks
17 Nov, 2021 An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C/C++ can store derived data types such as structures, pointers, etc. Given below is the picture representation of an array. Example:Let’s consider an example of taking random integers from the user. Array Array of Objects When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects. Syntax: ClassName ObjectName[number of objects]; The Array of Objects stores objects. An array of a class type is also known as an array of objects. Example#1: Storing more than one Employee data. Let’s assume there is an array of objects for storing employee data emp[50]. Below is the C++ program for storing data of one Employee: C++ // C++ program to implement// the above approach#include<iostream>using namespace std; class Employee{ int id; char name[30]; public: void getdata();//Declaration of function void putdata();//Declaration of function};void Employee::getdata(){//Defining of function cout<<"Enter Id : "; cin>>id; cout<<"Enter Name : "; cin>>name;}void Employee::putdata(){//Defining of function cout<<id<<" "; cout<<name<<" "; cout<<endl;}int main(){ Employee emp; //One member emp.getdata();//Accessing the function emp.putdata();//Accessing the function return 0; } Let’s understand the above example – In the above example, a class named Employee with id and name is being considered. The two functions are declared-getdata(): Taking user input for id and name.putdata(): Showing the data on the console screen. getdata(): Taking user input for id and name. putdata(): Showing the data on the console screen. This program can take the data of only one Employee. What if there is a requirement to add data of more than one Employee. Here comes the answer Array of Objects. An array of objects can be used if there is a need to store data of more than one employee. Below is the C++ program to implement the above approach- C++ // C++ program to implement// the above approach#include<iostream>using namespace std; class Employee{ int id; char name[30]; public: // Declaration of function void getdata(); // Declaration of function void putdata();}; // Defining the function outside// the classvoid Employee::getdata(){ cout << "Enter Id : "; cin >> id; cout << "Enter Name : "; cin >> name;} // Defining the function outside// the classvoid Employee::putdata(){ cout << id << " "; cout << name << " "; cout << endl;} // Driver codeint main(){ // This is an array of objects having // maximum limit of 30 Employees Employee emp[30]; int n, i; cout << "Enter Number of Employees - "; cin >> n; // Accessing the function for(i = 0; i < n; i++) emp[i].getdata(); cout << "Employee Data - " << endl; // Accessing the function for(i = 0; i < n; i++) emp[i].putdata();} Output: Explanation:In this example, more than one Employee’s details with an Employee id and name can be stored. Employee emp[30] – This is an array of objects having a maximum limit of 30 Employees. Two for loops are being used-First one to take the input from user by calling emp[i].getdata() function.Second one to print the data of Employee by calling the function emp[i].putdata() function. First one to take the input from user by calling emp[i].getdata() function. Second one to print the data of Employee by calling the function emp[i].putdata() function. Example#2: C++ // C++ program to implement// the above approach#include<iostream>using namespace std;class item{ char name[30]; int price; public: void getitem(); void printitem();}; // Function to get item detailsvoid item::getitem(){ cout << "Item Name = "; cin >> name; cout << "Price = "; cin >> price; } // Function to print item// detailsvoid item ::printitem(){ cout << "Name : " << name << "\n"; cout << "Price : " << price << "\n";} const int size = 3; // Driver codeint main(){ item t[size]; for(int i = 0; i < size; i++) { cout << "Item : " << (i + 1) << "\n"; t[i].getitem(); } for(int i = 0; i < size; i++) { cout << "Item Details : " << (i + 1) << "\n"; t[i].printitem(); }} Output: Advantages of Array of Objects: The array of objects represent storing multiple objects in a single name.In an array of objects, the data can be accessed randomly by using the index number.Reduce the time and memory by storing the data in a single variable. The array of objects represent storing multiple objects in a single name. In an array of objects, the data can be accessed randomly by using the index number. Reduce the time and memory by storing the data in a single variable. surinderdawra388 Arrays C++-Class and Object C++ Arrays CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Destructors in C++
[ { "code": null, "e": 24220, "s": 24192, "text": "\n17 Nov, 2021" }, { "code": null, "e": 24695, "s": 24220, "text": "An array in C/C++ or be it in any programming language is a collection of similar data items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C/C++ can store derived data types such as structures, pointers, etc. Given below is the picture representation of an array." }, { "code": null, "e": 24770, "s": 24695, "text": "Example:Let’s consider an example of taking random integers from the user." }, { "code": null, "e": 24776, "s": 24770, "text": "Array" }, { "code": null, "e": 24793, "s": 24776, "text": "Array of Objects" }, { "code": null, "e": 24990, "s": 24793, "text": "When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects." }, { "code": null, "e": 24998, "s": 24990, "text": "Syntax:" }, { "code": null, "e": 25039, "s": 24998, "text": "ClassName ObjectName[number of objects];" }, { "code": null, "e": 25139, "s": 25039, "text": "The Array of Objects stores objects. An array of a class type is also known as an array of objects." }, { "code": null, "e": 25264, "s": 25139, "text": "Example#1: Storing more than one Employee data. Let’s assume there is an array of objects for storing employee data emp[50]." }, { "code": null, "e": 25323, "s": 25264, "text": "Below is the C++ program for storing data of one Employee:" }, { "code": null, "e": 25327, "s": 25323, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include<iostream>using namespace std; class Employee{ int id; char name[30]; public: void getdata();//Declaration of function void putdata();//Declaration of function};void Employee::getdata(){//Defining of function cout<<\"Enter Id : \"; cin>>id; cout<<\"Enter Name : \"; cin>>name;}void Employee::putdata(){//Defining of function cout<<id<<\" \"; cout<<name<<\" \"; cout<<endl;}int main(){ Employee emp; //One member emp.getdata();//Accessing the function emp.putdata();//Accessing the function return 0; }", "e": 25893, "s": 25327, "text": null }, { "code": null, "e": 25930, "s": 25893, "text": "Let’s understand the above example –" }, { "code": null, "e": 26013, "s": 25930, "text": "In the above example, a class named Employee with id and name is being considered." }, { "code": null, "e": 26140, "s": 26013, "text": "The two functions are declared-getdata(): Taking user input for id and name.putdata(): Showing the data on the console screen." }, { "code": null, "e": 26186, "s": 26140, "text": "getdata(): Taking user input for id and name." }, { "code": null, "e": 26237, "s": 26186, "text": "putdata(): Showing the data on the console screen." }, { "code": null, "e": 26550, "s": 26237, "text": "This program can take the data of only one Employee. What if there is a requirement to add data of more than one Employee. Here comes the answer Array of Objects. An array of objects can be used if there is a need to store data of more than one employee. Below is the C++ program to implement the above approach-" }, { "code": null, "e": 26554, "s": 26550, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include<iostream>using namespace std; class Employee{ int id; char name[30]; public: // Declaration of function void getdata(); // Declaration of function void putdata();}; // Defining the function outside// the classvoid Employee::getdata(){ cout << \"Enter Id : \"; cin >> id; cout << \"Enter Name : \"; cin >> name;} // Defining the function outside// the classvoid Employee::putdata(){ cout << id << \" \"; cout << name << \" \"; cout << endl;} // Driver codeint main(){ // This is an array of objects having // maximum limit of 30 Employees Employee emp[30]; int n, i; cout << \"Enter Number of Employees - \"; cin >> n; // Accessing the function for(i = 0; i < n; i++) emp[i].getdata(); cout << \"Employee Data - \" << endl; // Accessing the function for(i = 0; i < n; i++) emp[i].putdata();}", "e": 27436, "s": 26554, "text": null }, { "code": null, "e": 27444, "s": 27436, "text": "Output:" }, { "code": null, "e": 27550, "s": 27444, "text": "Explanation:In this example, more than one Employee’s details with an Employee id and name can be stored." }, { "code": null, "e": 27637, "s": 27550, "text": "Employee emp[30] – This is an array of objects having a maximum limit of 30 Employees." }, { "code": null, "e": 27833, "s": 27637, "text": "Two for loops are being used-First one to take the input from user by calling emp[i].getdata() function.Second one to print the data of Employee by calling the function emp[i].putdata() function." }, { "code": null, "e": 27909, "s": 27833, "text": "First one to take the input from user by calling emp[i].getdata() function." }, { "code": null, "e": 28001, "s": 27909, "text": "Second one to print the data of Employee by calling the function emp[i].putdata() function." }, { "code": null, "e": 28013, "s": 28001, "text": "Example#2: " }, { "code": null, "e": 28017, "s": 28013, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include<iostream>using namespace std;class item{ char name[30]; int price; public: void getitem(); void printitem();}; // Function to get item detailsvoid item::getitem(){ cout << \"Item Name = \"; cin >> name; cout << \"Price = \"; cin >> price; } // Function to print item// detailsvoid item ::printitem(){ cout << \"Name : \" << name << \"\\n\"; cout << \"Price : \" << price << \"\\n\";} const int size = 3; // Driver codeint main(){ item t[size]; for(int i = 0; i < size; i++) { cout << \"Item : \" << (i + 1) << \"\\n\"; t[i].getitem(); } for(int i = 0; i < size; i++) { cout << \"Item Details : \" << (i + 1) << \"\\n\"; t[i].printitem(); }}", "e": 28769, "s": 28017, "text": null }, { "code": null, "e": 28777, "s": 28769, "text": "Output:" }, { "code": null, "e": 28810, "s": 28777, "text": "Advantages of Array of Objects: " }, { "code": null, "e": 29036, "s": 28810, "text": "The array of objects represent storing multiple objects in a single name.In an array of objects, the data can be accessed randomly by using the index number.Reduce the time and memory by storing the data in a single variable." }, { "code": null, "e": 29110, "s": 29036, "text": "The array of objects represent storing multiple objects in a single name." }, { "code": null, "e": 29195, "s": 29110, "text": "In an array of objects, the data can be accessed randomly by using the index number." }, { "code": null, "e": 29264, "s": 29195, "text": "Reduce the time and memory by storing the data in a single variable." }, { "code": null, "e": 29281, "s": 29264, "text": "surinderdawra388" }, { "code": null, "e": 29288, "s": 29281, "text": "Arrays" }, { "code": null, "e": 29309, "s": 29288, "text": "C++-Class and Object" }, { "code": null, "e": 29313, "s": 29309, "text": "C++" }, { "code": null, "e": 29320, "s": 29313, "text": "Arrays" }, { "code": null, "e": 29324, "s": 29320, "text": "CPP" }, { "code": null, "e": 29422, "s": 29324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29450, "s": 29422, "text": "Operator Overloading in C++" }, { "code": null, "e": 29470, "s": 29450, "text": "Polymorphism in C++" }, { "code": null, "e": 29503, "s": 29470, "text": "Friend class and function in C++" }, { "code": null, "e": 29527, "s": 29503, "text": "Sorting a vector in C++" }, { "code": null, "e": 29552, "s": 29527, "text": "std::string class in C++" }, { "code": null, "e": 29596, "s": 29552, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 29620, "s": 29596, "text": "Inline Functions in C++" }, { "code": null, "e": 29673, "s": 29620, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 29709, "s": 29673, "text": "Convert string to char array in C++" } ]
Nano Text Editor in Linux - GeeksforGeeks
23 Mar, 2020 Nano is a user-friendly, simple and WYSIWYG(What You See Is What You Get) text editor, which improves the features and user-friendliness of UW Pico text editor. Unlike vim editor or any other command-line editor, it doesn’t have any mode. It has an easy GUI(Graphical User Interface) which allows users to interact directly with the text in spite of switching between the modes as in vim editor. Nano is generally by default available in many Linux distributions but in case, it is not installed you may install the same using the following commands. $sudo apt update $sudo apt install nano $yum install nano 1. To create and open a new file. $nano new_filename The above command will open a new file with new_filename as shown in the output. In case the file already exists it will open the same and in case the file is not there in the current directory it will create a new one. At the bottom of the window, there is a list of shortcut keys for nano. 2. To save a file press Ctrl+o It will ask you for the filename. In case, you want to save the changes to a new file or want to create a new file then change the name else keep the name same. As soon as you will press enter key, then In case, you have changed the name of the file then it will save the file with a new name and if not then it will save the changes to the current file. 3. To cut paste in a file. Ctrl+o is used to cut and Ctrl+u is used to paste the text. To cut and paste a whole line. Move to the line which you want to cut then press Ctrl+k. Now the line is moved to clipboard, To paste it, go to the position where you want to paste and then press Ctrl+u To cut and paste the selected text. Select the text which you want to cut then press Ctrl+k. Now the text is moved to clipboard. To paste it, go to the position where you want to paste and then press Ctrl+u.4. To search a word in a file. Ctrl+w is used.Press Ctrl+wIt will ask for a word to search for.Enter the wordIt will search for the word and will place the cursor in the first letter of the first occurrence of the word.5. To enable spell check in nano. First, install the spell check package.$sudo apt install spell It will then ask for the password then enter the password. Then press y and then press enter.To do spell check first press Ctrl+tNow it will ask you to replace the incorrect wordsEnter the word to replace with thereAs soon as you will press the enter keyMy Personal Notes arrow_drop_upSave 4. To search a word in a file. Ctrl+w is used. Press Ctrl+wIt will ask for a word to search for.Enter the wordIt will search for the word and will place the cursor in the first letter of the first occurrence of the word. 5. To enable spell check in nano. First, install the spell check package. $sudo apt install spell It will then ask for the password then enter the password. Then press y and then press enter. To do spell check first press Ctrl+t Now it will ask you to replace the incorrect words Enter the word to replace with there As soon as you will press the enter key Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples chown command in Linux with Examples Docker - COPY Instruction nohup Command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples Thread functions in C/C++ Array Basics in Shell Scripting | Set 1
[ { "code": null, "e": 25761, "s": 25733, "text": "\n23 Mar, 2020" }, { "code": null, "e": 26157, "s": 25761, "text": "Nano is a user-friendly, simple and WYSIWYG(What You See Is What You Get) text editor, which improves the features and user-friendliness of UW Pico text editor. Unlike vim editor or any other command-line editor, it doesn’t have any mode. It has an easy GUI(Graphical User Interface) which allows users to interact directly with the text in spite of switching between the modes as in vim editor." }, { "code": null, "e": 26312, "s": 26157, "text": "Nano is generally by default available in many Linux distributions but in case, it is not installed you may install the same using the following commands." }, { "code": null, "e": 26329, "s": 26312, "text": "$sudo apt update" }, { "code": null, "e": 26352, "s": 26329, "text": "$sudo apt install nano" }, { "code": null, "e": 26370, "s": 26352, "text": "$yum install nano" }, { "code": null, "e": 26404, "s": 26370, "text": "1. To create and open a new file." }, { "code": null, "e": 26424, "s": 26404, "text": "$nano new_filename\n" }, { "code": null, "e": 26716, "s": 26424, "text": "The above command will open a new file with new_filename as shown in the output. In case the file already exists it will open the same and in case the file is not there in the current directory it will create a new one. At the bottom of the window, there is a list of shortcut keys for nano." }, { "code": null, "e": 26734, "s": 26716, "text": "2. To save a file" }, { "code": null, "e": 26748, "s": 26734, "text": "press Ctrl+o\n" }, { "code": null, "e": 26909, "s": 26748, "text": "It will ask you for the filename. In case, you want to save the changes to a new file or want to create a new file then change the name else keep the name same." }, { "code": null, "e": 27103, "s": 26909, "text": "As soon as you will press enter key, then In case, you have changed the name of the file then it will save the file with a new name and if not then it will save the changes to the current file." }, { "code": null, "e": 27190, "s": 27103, "text": "3. To cut paste in a file. Ctrl+o is used to cut and Ctrl+u is used to paste the text." }, { "code": null, "e": 27393, "s": 27190, "text": "To cut and paste a whole line. Move to the line which you want to cut then press Ctrl+k. Now the line is moved to clipboard, To paste it, go to the position where you want to paste and then press Ctrl+u" }, { "code": null, "e": 28206, "s": 27393, "text": "To cut and paste the selected text. Select the text which you want to cut then press Ctrl+k. Now the text is moved to clipboard. To paste it, go to the position where you want to paste and then press Ctrl+u.4. To search a word in a file. Ctrl+w is used.Press Ctrl+wIt will ask for a word to search for.Enter the wordIt will search for the word and will place the cursor in the first letter of the first occurrence of the word.5. To enable spell check in nano. First, install the spell check package.$sudo apt install spell\nIt will then ask for the password then enter the password. Then press y and then press enter.To do spell check first press Ctrl+tNow it will ask you to replace the incorrect wordsEnter the word to replace with thereAs soon as you will press the enter keyMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28253, "s": 28206, "text": "4. To search a word in a file. Ctrl+w is used." }, { "code": null, "e": 28427, "s": 28253, "text": "Press Ctrl+wIt will ask for a word to search for.Enter the wordIt will search for the word and will place the cursor in the first letter of the first occurrence of the word." }, { "code": null, "e": 28501, "s": 28427, "text": "5. To enable spell check in nano. First, install the spell check package." }, { "code": null, "e": 28526, "s": 28501, "text": "$sudo apt install spell\n" }, { "code": null, "e": 28620, "s": 28526, "text": "It will then ask for the password then enter the password. Then press y and then press enter." }, { "code": null, "e": 28657, "s": 28620, "text": "To do spell check first press Ctrl+t" }, { "code": null, "e": 28708, "s": 28657, "text": "Now it will ask you to replace the incorrect words" }, { "code": null, "e": 28745, "s": 28708, "text": "Enter the word to replace with there" }, { "code": null, "e": 28785, "s": 28745, "text": "As soon as you will press the enter key" }, { "code": null, "e": 28796, "s": 28785, "text": "Linux-Unix" }, { "code": null, "e": 28894, "s": 28796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28929, "s": 28894, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28963, "s": 28929, "text": "mv command in Linux with examples" }, { "code": null, "e": 29000, "s": 28963, "text": "chown command in Linux with Examples" }, { "code": null, "e": 29026, "s": 29000, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29063, "s": 29026, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 29092, "s": 29063, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 29134, "s": 29092, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 29170, "s": 29134, "text": "uniq Command in LINUX with examples" }, { "code": null, "e": 29196, "s": 29170, "text": "Thread functions in C/C++" } ]
A Full End-to-End Deployment of a Machine Learning Algorithm into a Live Production Environment | by Graham Harrison | Towards Data Science
In October 2021 I authored an article on “Deploying Machine Learning and Data Science Projects as Public Web Applications” (see https://towardsdatascience.com/deploying-machine-learning-and-data-science-projects-as-public-web-applications-3abc91088c11). In this article I explored how to deploy Jupyter Notebooks as publicly available web apps using Voila, GitHub and mybinder. After the article was published I received feedback from readers who were interested in how to push production deployment further to explore how a machine learning algorithm could be fully deployed into a live production environment so that it could be “consumed” in a platform-agnostic way and that led to the idea for this article ... The first step is to develop the machine learning algorithm that we want to deploy. In the real world this could involve many weeks or months of development time and lots of iteration across the steps of the data science pipeline but for this example I will develop a basic ML algorithm as the main purpose of this article is to find a way to deploy an algorithm for use by “consumers”. I selected a dataset from kaggle (https://www.kaggle.com/prathamtripathi/drug-classification) that has been created by the author with a “CC0: Public Domain” license which means that it has no copyright and that it may be used in other work with no restrictions (see https://creativecommons.org/publicdomain/zero/1.0/ for details). The Python code to develop a predictive machine learning algorithm to classify drug prescriptions given a range of patient criteria is as follows - 0.99 0.012247448713915901 At this point we can see that we have a machine learning algorithm trained to predict drug presriptions and that cross validation (i.e. folding the data) has been used to evaluate the model accuracy at 99%. So far, so good ... We are going to deploy this model into a production environment and although it is a simple example we would not want to have to retrain our model in the live environment every time a user wanted to predict a drug presription, hence our next step is to preserve the state of our trained model using pickle ... Now whenever we want to use the trained model, we simply need to reload its state from the model.pkl file rather than re-executing the training step. I am going to make a couple of assumptions in step 2 - Consumers of the machine learning algorithm have a requirements to make predictions for individual patients rather than a batch of patients.Those consumers wish to communicate with the algorithm using text-like values for the parameters (for example blood pressure = “NORMAL” or “HIGH” rather than their label encoded equivalents like 0 and 1. Consumers of the machine learning algorithm have a requirements to make predictions for individual patients rather than a batch of patients. Those consumers wish to communicate with the algorithm using text-like values for the parameters (for example blood pressure = “NORMAL” or “HIGH” rather than their label encoded equivalents like 0 and 1. Therefore, we will start by reviewing what the values are for all of the label encoded categorical features used as an input to the algorithm ... Sex ['F', 'M'] [0, 1] BP ['HIGH', 'LOW', 'NORMAL'] [0, 1, 2] Cholesterol ['HIGH', 'NORMAL'] [0, 1] Drug ['DrugY', 'drugC', 'drugX', 'drugA', 'drugB'] [0, 3, 4, 1, 2] And there we have it, a list of each categorical feature with the unique values that appear in the data and the corresponding numerical values as transformed by the LabelEncoder(). Armed with this knowledge we can provide a set of dictionaries that map the text-like values (e.g. “HIGH”, “LOW” etc.) into their encoded equivalents and then develop a simple function to make an individual predictions as follows ... This implementation can then be verified by invoking the function to make some predictions based on values from the original data so that we know what the outputs should be ... 'drugC' 'DrugY' Note that our predict_drug function does not need to train the model, rather it "rehydrates" the model that previously had its state saved by pickle into the model.pkl file and we can see from the output that the predictions for drug recommendation are correct. Everything is looking good so far but here is the major problem: clients or consumers of our machine learning algorithm must be written in the Python programming language and not only that, we must have the capability of changing and modifying the application. What if a 3rd party application wants to use and consume our algorithm and what if this 3rd party application is not written in Python? Perhaps it is written in Java, C#, JavaScript or some other non-Python language. This is where web services come in. A web service is a “wrapper” that receives requests from clients and consumers using http GET and http PUT commands, invokes the Python code and returns the result as an HTML response. This means that the clients and callers only need to be able to formulate HTTP requests and nearly all programming languages and environments will have a way of doing this. In the Python world there are several different approaches available but the one I have selected is to use flask to construct our web service wrapper. The code is not very complicated but it can be challenging to get VS Code configured to enable developers to debug a flask application. If you need a tutorial for this step please check out my article titled “How to Debug Flask Applications in VS Code” which can be found here — https://towardsdatascience.com/how-to-debug-flask-applications-in-vs-code-c65c9bdbef21. Here is the wrapper code for the web service ... Start the VS Code IDE from the Anaconda Navigator page (or by starting and Anaconda Command Prompt and typing code). This will start VS Code with the conda base environment which is required to run and debug the flask application. The web service can be started from inside VS Code by clicking on “Run and Debug” and then selecting “Flask Launch and debug a Flask web application” - If everything has gone to plan the last message in the TERMINAL window should be Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) which indicates that your flask web application is up and running. You should now test you web service using one of these methods - Open a web browser and enter: http://127.0.0.1:5000/drug?Age=60&Sex=F&BP=LOW&Cholesterol=HIGH&Na_to_K=20Open an anaconda command prompt and enter: curl -X GET "http://127.0.0.1:5000/drug?Age=60&Sex=F&BP=LOW&Cholesterol=HIGH&Na_to_K=20" Open a web browser and enter: http://127.0.0.1:5000/drug?Age=60&Sex=F&BP=LOW&Cholesterol=HIGH&Na_to_K=20 Open an anaconda command prompt and enter: curl -X GET "http://127.0.0.1:5000/drug?Age=60&Sex=F&BP=LOW&Cholesterol=HIGH&Na_to_K=20" If you want to find out more about developing flask applications and web services, these articles are a great place to start - https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask https://code.visualstudio.com/docs/python/tutorial-flask We now have a predictive machine learning algorithm that can predict drug prescriptions with 99% accuracy, we have a helper function that can make individual predictions and we have a web service wrapper that enables these components to be called from a browser or command line. However all of this is still only callable from the development environment. The next stage is to deploy everything into the cloud so that clients can “consume” the web service over the public Internet. There are many different public services available for web app deployment including - Google — https://cloud.google.com/appengine/docs/standard/python3/building-app/writing-web-service Amazon Web Services — https://medium.com/@rodkey/deploying-a-flask-application-on-aws-a72daba6bb80 Microsoft Azure — https://medium.com/@nikovrdoljak/deploy-your-flask-app-on-azure-in-3-easy-steps-b2fe388a589e I have chosen Azure because it is free (for an entry level account), easy-to-use, quick and fully integrated with VS Code which is my favourite development environment. Switch tasks into VS Code, go to “Extensions” (Ctrl+Shft_X) and add in the “Azure App Service” extension. Once the extension is added you will see a new Azure icon in the Activity Bar - You must have an account to begin deployments into the Azure cloud and you must provide credit card details during the registration process. However you will not be charged unless you specifically opt to move away from the free license. You can follow the instructions on this page — https://azure.microsoft.com/en-gb/free/ to create your free Azure account via a browser, but the easiest way is to click on the new Azure icon in the Activity Bar and choose “Create a Free Azure Account” (or “Sign in to Azure” if you already have one) - The next step is to create an Azure web app to host your application by clicking on the “+” sign in the “APP SERVICE” window. You will be prompted for a name for the app. The name will be used in the final URL and it must be unique but other than that the name is not particularly important. When prompted for a license type choose “Free Trial” — your web app will now be created and you are ready to deploy. Before you can deploy the app to Azure you must create a “requirements.txt” file in the same folder as your Flask web app that contains a list of all of the dependencies and libraries that Azure must install in order to run your application. This step is vital as if the libraries are not in the deployed environment the app will crash. The contents of requirements.txt for our app are as follows - Some points to note - The library names must match exactly to what you would type if you were installing using pip, for example pip install Flask.Note that Flask has an upper case "F". This is because Flask is unusual in being capitalised this way, usually libraries are all lower case.sklearn is required to execute the rehydrated model.pkl. Although sklearn and DecisionTreeClassifier are not referenced explicitly in the code, they are needed for model.fit so if sklearn is omitted the app will crash.A reference to pickle is not required because this library is a part of the core Python installation. If you do include pickle the deployment will crash because you cannot execute pip install pickle. The library names must match exactly to what you would type if you were installing using pip, for example pip install Flask. Note that Flask has an upper case "F". This is because Flask is unusual in being capitalised this way, usually libraries are all lower case. sklearn is required to execute the rehydrated model.pkl. Although sklearn and DecisionTreeClassifier are not referenced explicitly in the code, they are needed for model.fit so if sklearn is omitted the app will crash. A reference to pickle is not required because this library is a part of the core Python installation. If you do include pickle the deployment will crash because you cannot execute pip install pickle. If you stick to these rules your deployment will work and any error messages are usually informative enough to enable the issues to be resolved with a bit of Internet research. If you have been following the steps so far you now have a Flask app inside VS Code. Your app code file will be called app.py and the application name is app. The Flask app has been tested on a local development web server. You have installed the VS Code Azure App Extension and used it to create a Microsoft Azure free account and also to create an Azure web application. You should have your Flask application open in VS Code and you have everything in place to deploy your application into the cloud. This is achieved by simply clicking on the web app name next to the blue circle icon, then clicking on the cloud icon next to the “+” sign. When prompted, choose the following - Select the default folder to deploy Select the “Free Trial” subscription Select the web app name you have created If prompted to overwrite, select “Deploy” When asked to “Always deploy ...” select “Skip for now” When the deployment starts click on “output window” Now sit back and make a coffee whilst the app deploys - When the deployment is complete, click on “Browse Website” and you will be taken to the correct URL which will run app.route("/") function. Simply add in the same URL parameters that we used to test the local deployment and you will see the output from a fully deployed web app! - https://graham-harrison68-web03.azurewebsites.net/drug?Age=60&Sex=F&BP=LOW&Cholesterol=HIGH&Na_to_K=20 A point to note: after a while the azure app goes to sleep and the first call after this takes a very long time. If you choose to upgrade to a paid-for Azure subscription there is an option to keep the app refreshed and “awake” but in the free subscription the sleep-related delay cannot be avoided as this subscription is intended for testing purposes and as such has a few limitations. At this point any programming language or environment that can invoke web requests can call the deployed web service with just a few lines of code. We did start by saying that non-Python environments like C#, JavaScript etc. can all be used but I will finish off this example by writing some code to call the deployed app from a Python client using ipywidgets - If you click “Prescribe” with the default values, the recommendation should be for “drugC”. Change the Age to 60 and Na to K to 20 and “DrugY” should be prescribed. Put the Age back to 47, Na to K back to 14 and change BP to “HIGH” and drugA should be prescribed. These simple tests prove that the Azure-hosted web service using a decision tree based predictive machine learning algorithm is fully deployed to the public cloud, can be called by any development environment capable of executing a http GET command and is fully working end-to-end. There are quite a few steps involved, but using readily available libraries and free tools including scikit-learn, pickle, flask, Microsoft Azure and ipywidgets we have constructed a fully working, publicly available cloud deployment of a machine learning algorithm and a fully functioning client to call and consume the web service and display the results. If you enjoyed reading this article, why not check out my other articles at https://grahamharrison-86487.medium.com/? Also, I would love to hear from you to get your thoughts on this piece, any of my other articles or anything else related to data science and data analytics. If you would like to get in touch to discuss any of these topics please look me up on LinkedIn — https://www.linkedin.com/in/grahamharrison1 or feel free to e-mail me at GHarrison@lincolncollege.ac.uk. If you would like to support the author and 1000’s of others who contribute to article writing world-wide by subscribing, please use this link — https://grahamharrison-86487.medium.com/membership. Note: the author will receive a proportion of the fees if you sign up using this link.
[ { "code": null, "e": 426, "s": 172, "text": "In October 2021 I authored an article on “Deploying Machine Learning and Data Science Projects as Public Web Applications” (see https://towardsdatascience.com/deploying-machine-learning-and-data-science-projects-as-public-web-applications-3abc91088c11)." }, { "code": null, "e": 550, "s": 426, "text": "In this article I explored how to deploy Jupyter Notebooks as publicly available web apps using Voila, GitHub and mybinder." }, { "code": null, "e": 887, "s": 550, "text": "After the article was published I received feedback from readers who were interested in how to push production deployment further to explore how a machine learning algorithm could be fully deployed into a live production environment so that it could be “consumed” in a platform-agnostic way and that led to the idea for this article ..." }, { "code": null, "e": 1274, "s": 887, "text": "The first step is to develop the machine learning algorithm that we want to deploy. In the real world this could involve many weeks or months of development time and lots of iteration across the steps of the data science pipeline but for this example I will develop a basic ML algorithm as the main purpose of this article is to find a way to deploy an algorithm for use by “consumers”." }, { "code": null, "e": 1606, "s": 1274, "text": "I selected a dataset from kaggle (https://www.kaggle.com/prathamtripathi/drug-classification) that has been created by the author with a “CC0: Public Domain” license which means that it has no copyright and that it may be used in other work with no restrictions (see https://creativecommons.org/publicdomain/zero/1.0/ for details)." }, { "code": null, "e": 1754, "s": 1606, "text": "The Python code to develop a predictive machine learning algorithm to classify drug prescriptions given a range of patient criteria is as follows -" }, { "code": null, "e": 1780, "s": 1754, "text": "0.99 0.012247448713915901" }, { "code": null, "e": 1987, "s": 1780, "text": "At this point we can see that we have a machine learning algorithm trained to predict drug presriptions and that cross validation (i.e. folding the data) has been used to evaluate the model accuracy at 99%." }, { "code": null, "e": 2007, "s": 1987, "text": "So far, so good ..." }, { "code": null, "e": 2317, "s": 2007, "text": "We are going to deploy this model into a production environment and although it is a simple example we would not want to have to retrain our model in the live environment every time a user wanted to predict a drug presription, hence our next step is to preserve the state of our trained model using pickle ..." }, { "code": null, "e": 2467, "s": 2317, "text": "Now whenever we want to use the trained model, we simply need to reload its state from the model.pkl file rather than re-executing the training step." }, { "code": null, "e": 2522, "s": 2467, "text": "I am going to make a couple of assumptions in step 2 -" }, { "code": null, "e": 2866, "s": 2522, "text": "Consumers of the machine learning algorithm have a requirements to make predictions for individual patients rather than a batch of patients.Those consumers wish to communicate with the algorithm using text-like values for the parameters (for example blood pressure = “NORMAL” or “HIGH” rather than their label encoded equivalents like 0 and 1." }, { "code": null, "e": 3007, "s": 2866, "text": "Consumers of the machine learning algorithm have a requirements to make predictions for individual patients rather than a batch of patients." }, { "code": null, "e": 3211, "s": 3007, "text": "Those consumers wish to communicate with the algorithm using text-like values for the parameters (for example blood pressure = “NORMAL” or “HIGH” rather than their label encoded equivalents like 0 and 1." }, { "code": null, "e": 3357, "s": 3211, "text": "Therefore, we will start by reviewing what the values are for all of the label encoded categorical features used as an input to the algorithm ..." }, { "code": null, "e": 3523, "s": 3357, "text": "Sex ['F', 'M'] [0, 1] BP ['HIGH', 'LOW', 'NORMAL'] [0, 1, 2] Cholesterol ['HIGH', 'NORMAL'] [0, 1] Drug ['DrugY', 'drugC', 'drugX', 'drugA', 'drugB'] [0, 3, 4, 1, 2]" }, { "code": null, "e": 3704, "s": 3523, "text": "And there we have it, a list of each categorical feature with the unique values that appear in the data and the corresponding numerical values as transformed by the LabelEncoder()." }, { "code": null, "e": 3938, "s": 3704, "text": "Armed with this knowledge we can provide a set of dictionaries that map the text-like values (e.g. “HIGH”, “LOW” etc.) into their encoded equivalents and then develop a simple function to make an individual predictions as follows ..." }, { "code": null, "e": 4115, "s": 3938, "text": "This implementation can then be verified by invoking the function to make some predictions based on values from the original data so that we know what the outputs should be ..." }, { "code": null, "e": 4123, "s": 4115, "text": "'drugC'" }, { "code": null, "e": 4131, "s": 4123, "text": "'DrugY'" }, { "code": null, "e": 4393, "s": 4131, "text": "Note that our predict_drug function does not need to train the model, rather it \"rehydrates\" the model that previously had its state saved by pickle into the model.pkl file and we can see from the output that the predictions for drug recommendation are correct." }, { "code": null, "e": 4654, "s": 4393, "text": "Everything is looking good so far but here is the major problem: clients or consumers of our machine learning algorithm must be written in the Python programming language and not only that, we must have the capability of changing and modifying the application." }, { "code": null, "e": 4871, "s": 4654, "text": "What if a 3rd party application wants to use and consume our algorithm and what if this 3rd party application is not written in Python? Perhaps it is written in Java, C#, JavaScript or some other non-Python language." }, { "code": null, "e": 5092, "s": 4871, "text": "This is where web services come in. A web service is a “wrapper” that receives requests from clients and consumers using http GET and http PUT commands, invokes the Python code and returns the result as an HTML response." }, { "code": null, "e": 5265, "s": 5092, "text": "This means that the clients and callers only need to be able to formulate HTTP requests and nearly all programming languages and environments will have a way of doing this." }, { "code": null, "e": 5416, "s": 5265, "text": "In the Python world there are several different approaches available but the one I have selected is to use flask to construct our web service wrapper." }, { "code": null, "e": 5783, "s": 5416, "text": "The code is not very complicated but it can be challenging to get VS Code configured to enable developers to debug a flask application. If you need a tutorial for this step please check out my article titled “How to Debug Flask Applications in VS Code” which can be found here — https://towardsdatascience.com/how-to-debug-flask-applications-in-vs-code-c65c9bdbef21." }, { "code": null, "e": 5832, "s": 5783, "text": "Here is the wrapper code for the web service ..." }, { "code": null, "e": 6063, "s": 5832, "text": "Start the VS Code IDE from the Anaconda Navigator page (or by starting and Anaconda Command Prompt and typing code). This will start VS Code with the conda base environment which is required to run and debug the flask application." }, { "code": null, "e": 6215, "s": 6063, "text": "The web service can be started from inside VS Code by clicking on “Run and Debug” and then selecting “Flask Launch and debug a Flask web application” -" }, { "code": null, "e": 6420, "s": 6215, "text": "If everything has gone to plan the last message in the TERMINAL window should be Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) which indicates that your flask web application is up and running." }, { "code": null, "e": 6485, "s": 6420, "text": "You should now test you web service using one of these methods -" }, { "code": null, "e": 6721, "s": 6485, "text": "Open a web browser and enter: http://127.0.0.1:5000/drug?Age=60&Sex=F&BP=LOW&Cholesterol=HIGH&Na_to_K=20Open an anaconda command prompt and enter: curl -X GET \"http://127.0.0.1:5000/drug?Age=60&Sex=F&BP=LOW&Cholesterol=HIGH&Na_to_K=20\"" }, { "code": null, "e": 6826, "s": 6721, "text": "Open a web browser and enter: http://127.0.0.1:5000/drug?Age=60&Sex=F&BP=LOW&Cholesterol=HIGH&Na_to_K=20" }, { "code": null, "e": 6958, "s": 6826, "text": "Open an anaconda command prompt and enter: curl -X GET \"http://127.0.0.1:5000/drug?Age=60&Sex=F&BP=LOW&Cholesterol=HIGH&Na_to_K=20\"" }, { "code": null, "e": 7085, "s": 6958, "text": "If you want to find out more about developing flask applications and web services, these articles are a great place to start -" }, { "code": null, "e": 7165, "s": 7085, "text": "https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask" }, { "code": null, "e": 7222, "s": 7165, "text": "https://code.visualstudio.com/docs/python/tutorial-flask" }, { "code": null, "e": 7501, "s": 7222, "text": "We now have a predictive machine learning algorithm that can predict drug prescriptions with 99% accuracy, we have a helper function that can make individual predictions and we have a web service wrapper that enables these components to be called from a browser or command line." }, { "code": null, "e": 7704, "s": 7501, "text": "However all of this is still only callable from the development environment. The next stage is to deploy everything into the cloud so that clients can “consume” the web service over the public Internet." }, { "code": null, "e": 7790, "s": 7704, "text": "There are many different public services available for web app deployment including -" }, { "code": null, "e": 7889, "s": 7790, "text": "Google — https://cloud.google.com/appengine/docs/standard/python3/building-app/writing-web-service" }, { "code": null, "e": 7988, "s": 7889, "text": "Amazon Web Services — https://medium.com/@rodkey/deploying-a-flask-application-on-aws-a72daba6bb80" }, { "code": null, "e": 8099, "s": 7988, "text": "Microsoft Azure — https://medium.com/@nikovrdoljak/deploy-your-flask-app-on-azure-in-3-easy-steps-b2fe388a589e" }, { "code": null, "e": 8268, "s": 8099, "text": "I have chosen Azure because it is free (for an entry level account), easy-to-use, quick and fully integrated with VS Code which is my favourite development environment." }, { "code": null, "e": 8454, "s": 8268, "text": "Switch tasks into VS Code, go to “Extensions” (Ctrl+Shft_X) and add in the “Azure App Service” extension. Once the extension is added you will see a new Azure icon in the Activity Bar -" }, { "code": null, "e": 8691, "s": 8454, "text": "You must have an account to begin deployments into the Azure cloud and you must provide credit card details during the registration process. However you will not be charged unless you specifically opt to move away from the free license." }, { "code": null, "e": 8992, "s": 8691, "text": "You can follow the instructions on this page — https://azure.microsoft.com/en-gb/free/ to create your free Azure account via a browser, but the easiest way is to click on the new Azure icon in the Activity Bar and choose “Create a Free Azure Account” (or “Sign in to Azure” if you already have one) -" }, { "code": null, "e": 9284, "s": 8992, "text": "The next step is to create an Azure web app to host your application by clicking on the “+” sign in the “APP SERVICE” window. You will be prompted for a name for the app. The name will be used in the final URL and it must be unique but other than that the name is not particularly important." }, { "code": null, "e": 9401, "s": 9284, "text": "When prompted for a license type choose “Free Trial” — your web app will now be created and you are ready to deploy." }, { "code": null, "e": 9738, "s": 9401, "text": "Before you can deploy the app to Azure you must create a “requirements.txt” file in the same folder as your Flask web app that contains a list of all of the dependencies and libraries that Azure must install in order to run your application. This step is vital as if the libraries are not in the deployed environment the app will crash." }, { "code": null, "e": 9800, "s": 9738, "text": "The contents of requirements.txt for our app are as follows -" }, { "code": null, "e": 9822, "s": 9800, "text": "Some points to note -" }, { "code": null, "e": 10504, "s": 9822, "text": "The library names must match exactly to what you would type if you were installing using pip, for example pip install Flask.Note that Flask has an upper case \"F\". This is because Flask is unusual in being capitalised this way, usually libraries are all lower case.sklearn is required to execute the rehydrated model.pkl. Although sklearn and DecisionTreeClassifier are not referenced explicitly in the code, they are needed for model.fit so if sklearn is omitted the app will crash.A reference to pickle is not required because this library is a part of the core Python installation. If you do include pickle the deployment will crash because you cannot execute pip install pickle." }, { "code": null, "e": 10629, "s": 10504, "text": "The library names must match exactly to what you would type if you were installing using pip, for example pip install Flask." }, { "code": null, "e": 10770, "s": 10629, "text": "Note that Flask has an upper case \"F\". This is because Flask is unusual in being capitalised this way, usually libraries are all lower case." }, { "code": null, "e": 10989, "s": 10770, "text": "sklearn is required to execute the rehydrated model.pkl. Although sklearn and DecisionTreeClassifier are not referenced explicitly in the code, they are needed for model.fit so if sklearn is omitted the app will crash." }, { "code": null, "e": 11189, "s": 10989, "text": "A reference to pickle is not required because this library is a part of the core Python installation. If you do include pickle the deployment will crash because you cannot execute pip install pickle." }, { "code": null, "e": 11366, "s": 11189, "text": "If you stick to these rules your deployment will work and any error messages are usually informative enough to enable the issues to be resolved with a bit of Internet research." }, { "code": null, "e": 11590, "s": 11366, "text": "If you have been following the steps so far you now have a Flask app inside VS Code. Your app code file will be called app.py and the application name is app. The Flask app has been tested on a local development web server." }, { "code": null, "e": 11739, "s": 11590, "text": "You have installed the VS Code Azure App Extension and used it to create a Microsoft Azure free account and also to create an Azure web application." }, { "code": null, "e": 11870, "s": 11739, "text": "You should have your Flask application open in VS Code and you have everything in place to deploy your application into the cloud." }, { "code": null, "e": 12010, "s": 11870, "text": "This is achieved by simply clicking on the web app name next to the blue circle icon, then clicking on the cloud icon next to the “+” sign." }, { "code": null, "e": 12048, "s": 12010, "text": "When prompted, choose the following -" }, { "code": null, "e": 12084, "s": 12048, "text": "Select the default folder to deploy" }, { "code": null, "e": 12121, "s": 12084, "text": "Select the “Free Trial” subscription" }, { "code": null, "e": 12162, "s": 12121, "text": "Select the web app name you have created" }, { "code": null, "e": 12204, "s": 12162, "text": "If prompted to overwrite, select “Deploy”" }, { "code": null, "e": 12260, "s": 12204, "text": "When asked to “Always deploy ...” select “Skip for now”" }, { "code": null, "e": 12312, "s": 12260, "text": "When the deployment starts click on “output window”" }, { "code": null, "e": 12368, "s": 12312, "text": "Now sit back and make a coffee whilst the app deploys -" }, { "code": null, "e": 12508, "s": 12368, "text": "When the deployment is complete, click on “Browse Website” and you will be taken to the correct URL which will run app.route(\"/\") function." }, { "code": null, "e": 12649, "s": 12508, "text": "Simply add in the same URL parameters that we used to test the local deployment and you will see the output from a fully deployed web app! -" }, { "code": null, "e": 12752, "s": 12649, "text": "https://graham-harrison68-web03.azurewebsites.net/drug?Age=60&Sex=F&BP=LOW&Cholesterol=HIGH&Na_to_K=20" }, { "code": null, "e": 12865, "s": 12752, "text": "A point to note: after a while the azure app goes to sleep and the first call after this takes a very long time." }, { "code": null, "e": 13140, "s": 12865, "text": "If you choose to upgrade to a paid-for Azure subscription there is an option to keep the app refreshed and “awake” but in the free subscription the sleep-related delay cannot be avoided as this subscription is intended for testing purposes and as such has a few limitations." }, { "code": null, "e": 13288, "s": 13140, "text": "At this point any programming language or environment that can invoke web requests can call the deployed web service with just a few lines of code." }, { "code": null, "e": 13502, "s": 13288, "text": "We did start by saying that non-Python environments like C#, JavaScript etc. can all be used but I will finish off this example by writing some code to call the deployed app from a Python client using ipywidgets -" }, { "code": null, "e": 13594, "s": 13502, "text": "If you click “Prescribe” with the default values, the recommendation should be for “drugC”." }, { "code": null, "e": 13766, "s": 13594, "text": "Change the Age to 60 and Na to K to 20 and “DrugY” should be prescribed. Put the Age back to 47, Na to K back to 14 and change BP to “HIGH” and drugA should be prescribed." }, { "code": null, "e": 14048, "s": 13766, "text": "These simple tests prove that the Azure-hosted web service using a decision tree based predictive machine learning algorithm is fully deployed to the public cloud, can be called by any development environment capable of executing a http GET command and is fully working end-to-end." }, { "code": null, "e": 14406, "s": 14048, "text": "There are quite a few steps involved, but using readily available libraries and free tools including scikit-learn, pickle, flask, Microsoft Azure and ipywidgets we have constructed a fully working, publicly available cloud deployment of a machine learning algorithm and a fully functioning client to call and consume the web service and display the results." }, { "code": null, "e": 14524, "s": 14406, "text": "If you enjoyed reading this article, why not check out my other articles at https://grahamharrison-86487.medium.com/?" }, { "code": null, "e": 14682, "s": 14524, "text": "Also, I would love to hear from you to get your thoughts on this piece, any of my other articles or anything else related to data science and data analytics." }, { "code": null, "e": 14884, "s": 14682, "text": "If you would like to get in touch to discuss any of these topics please look me up on LinkedIn — https://www.linkedin.com/in/grahamharrison1 or feel free to e-mail me at GHarrison@lincolncollege.ac.uk." } ]
is_displayed() element method - Selenium Python - GeeksforGeeks
27 Apr, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies This article revolves around how to use is_displayed method in Selenium. is_displayed method is used to check if element it visible to user or not. It returns a boolean value True or False. element.is_displayed() Example – <a href="https://www.geeksforgeeks.org/" id="link" />Text Here</a> To find an element one needs to use one of the locating strategies, For example, element = driver.find_element_by_id("link") element = driver.find_element_by_xpath("//a[@id='link']") Also, to find multiple elements, we can use – elements = driver.find_elements_by_id("link") Now one can check if this element is being displayed with text_length = element.is_displayed() Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we gcheck visibility of courses tab in navigation bar at geeksforgeeks.Program – # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # print valueprint(element.is_displayed()) Output- Terminal Output – Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Read a file line by line in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Reading and Writing to text files in Python Python OOPs Concepts Create a Pandas DataFrame from Lists
[ { "code": null, "e": 24540, "s": 24512, "text": "\n27 Apr, 2020" }, { "code": null, "e": 25097, "s": 24540, "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": 25287, "s": 25097, "text": "This article revolves around how to use is_displayed method in Selenium. is_displayed method is used to check if element it visible to user or not. It returns a boolean value True or False." }, { "code": null, "e": 25310, "s": 25287, "text": "element.is_displayed()" }, { "code": null, "e": 25320, "s": 25310, "text": "Example –" }, { "code": "<a href=\"https://www.geeksforgeeks.org/\" id=\"link\" />Text Here</a>", "e": 25387, "s": 25320, "text": null }, { "code": null, "e": 25468, "s": 25387, "text": "To find an element one needs to use one of the locating strategies, For example," }, { "code": null, "e": 25570, "s": 25468, "text": "element = driver.find_element_by_id(\"link\")\nelement = driver.find_element_by_xpath(\"//a[@id='link']\")" }, { "code": null, "e": 25616, "s": 25570, "text": "Also, to find multiple elements, we can use –" }, { "code": null, "e": 25662, "s": 25616, "text": "elements = driver.find_elements_by_id(\"link\")" }, { "code": null, "e": 25720, "s": 25662, "text": "Now one can check if this element is being displayed with" }, { "code": null, "e": 25757, "s": 25720, "text": "text_length = element.is_displayed()" }, { "code": null, "e": 25931, "s": 25757, "text": "Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we gcheck visibility of courses tab in navigation bar at geeksforgeeks.Program –" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # print valueprint(element.is_displayed())", "e": 26217, "s": 25931, "text": null }, { "code": null, "e": 26225, "s": 26217, "text": "Output-" }, { "code": null, "e": 26243, "s": 26225, "text": "Terminal Output –" }, { "code": null, "e": 26259, "s": 26243, "text": "Python-selenium" }, { "code": null, "e": 26268, "s": 26259, "text": "selenium" }, { "code": null, "e": 26275, "s": 26268, "text": "Python" }, { "code": null, "e": 26373, "s": 26275, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26382, "s": 26373, "text": "Comments" }, { "code": null, "e": 26395, "s": 26382, "text": "Old Comments" }, { "code": null, "e": 26413, "s": 26395, "text": "Python Dictionary" }, { "code": null, "e": 26445, "s": 26413, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26467, "s": 26445, "text": "Enumerate() in Python" }, { "code": null, "e": 26502, "s": 26467, "text": "Read a file line by line in Python" }, { "code": null, "e": 26532, "s": 26502, "text": "Iterate over a list in Python" }, { "code": null, "e": 26574, "s": 26532, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26617, "s": 26574, "text": "Python program to convert a list to string" }, { "code": null, "e": 26661, "s": 26617, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26682, "s": 26661, "text": "Python OOPs Concepts" } ]
How to add an element to a javascript object?
JavaScript object notation is like var car = {name:"Benz", "Brand": "Mercedes", model:"open roof"}; if we need to add the price of the Benz car then the code is as follows. Live Demo <html> <body> <p id="demo"></p> <script> var car = {name:"Benz", "Brand": "Mercedes", model:"open roof"}; car.price = "50,000$", car.color = "Black" document.write(JSON.stringify(car)); </script> </body> </html> {"name":"Benz","Brand":"Mercedes","model":"open roof","price":"50,000$","color":"Black"}
[ { "code": null, "e": 1097, "s": 1062, "text": "JavaScript object notation is like" }, { "code": null, "e": 1162, "s": 1097, "text": "var car = {name:\"Benz\", \"Brand\": \"Mercedes\", model:\"open roof\"};" }, { "code": null, "e": 1236, "s": 1162, "text": " if we need to add the price of the Benz car then the code is as follows." }, { "code": null, "e": 1247, "s": 1236, "text": " Live Demo" }, { "code": null, "e": 1471, "s": 1247, "text": "<html>\n<body>\n<p id=\"demo\"></p>\n<script>\n var car = {name:\"Benz\", \"Brand\": \"Mercedes\", model:\"open roof\"};\n car.price = \"50,000$\",\n car.color = \"Black\"\n document.write(JSON.stringify(car));\n</script>\n</body>\n</html>" }, { "code": null, "e": 1560, "s": 1471, "text": "{\"name\":\"Benz\",\"Brand\":\"Mercedes\",\"model\":\"open roof\",\"price\":\"50,000$\",\"color\":\"Black\"}" } ]
How to match a column in a data frame with a column in another data frame in R?
To match a column in a data frame with a column in another data frame, we can use match function. For example, if we have two data frames called df1 and df2 each having one similar column and the second having an extra column then the matching can be done for similar columns and a new column in the first data frame can be created based on that match and the second column the second data frame. Check out the below examples to understand how it works. Live Demo > df1<-data.frame(x1=sample(0:2,20,replace=TRUE)) > df1 x1 1 2 2 2 3 1 4 0 5 2 6 2 7 2 8 2 9 2 10 1 11 1 12 2 13 1 14 0 15 2 16 2 17 2 18 2 19 2 20 2 > df2<-data.frame(x1=rpois(20,2),x2=rpois(20,5)) > df2 x1 x2 1 2 5 2 2 5 3 3 6 4 0 5 5 1 3 6 1 5 7 2 6 8 1 3 9 4 6 10 0 5 11 1 0 12 3 4 13 1 3 14 1 4 15 2 6 16 1 5 17 2 2 18 3 8 19 0 5 20 1 6 > df1$x2<-df2$x2[match(df1$x1,df2$x1)] > df1 x1 x2 1 2 5 2 2 5 3 1 3 4 0 5 5 2 5 6 2 5 7 2 5 8 2 5 9 2 5 10 1 3 11 1 3 12 2 5 13 1 3 14 0 5 15 2 5 16 2 5 17 2 5 18 2 5 19 2 5 20 2 5 Live Demo > y1<-sample(c("A","B","C"),20,replace=TRUE) > df3<-data.frame(y1) > df3 y1 1 A 2 C 3 C 4 A 5 C 6 B 7 C 8 B 9 B 10 C 11 B 12 C 13 B 14 A 15 A 16 C 17 B 18 B 19 A 20 A > y1<-sample(c("A","B","C","D","E"),20,replace=TRUE) > y2<-sample(LETTERS[1:4],20,replace=TRUE) > df4<-data.frame(y1,y2) > df4 y1 y2 1 E C 2 A D 3 C B 4 C D 5 D B 6 B D 7 D C 8 C B 9 D D 10 C A 11 B D 12 B C 13 C B 14 B D 15 D C 16 B B 17 E C 18 D B 19 A D 20 B C > df3$y2<-df4$y2[match(df3$y1,df4$y1)] > df3 y1 y2 1 A D 2 C B 3 C B 4 A D 5 C B 6 B D 7 C B 8 B D 9 B D 10 C B 11 B D 12 C B 13 B D 14 A D 15 A D 16 C B 17 B D 18 B D 19 A D 20 A D
[ { "code": null, "e": 1516, "s": 1062, "text": "To match a column in a data frame with a column in another data frame, we can use match function. For example, if we have two data frames called df1 and df2 each having one similar column and the second having an extra column then the matching can be done for similar columns and a new column in the first data frame can be created based on that match and the second column the second data frame. Check out the below examples to understand how it works." }, { "code": null, "e": 1526, "s": 1516, "text": "Live Demo" }, { "code": null, "e": 1582, "s": 1526, "text": "> df1<-data.frame(x1=sample(0:2,20,replace=TRUE))\n> df1" }, { "code": null, "e": 1708, "s": 1582, "text": " x1\n1 2\n2 2\n3 1\n4 0\n5 2\n6 2\n7 2\n8 2\n9 2\n10 1\n11 1\n12 2\n13 1\n14 0\n15 2\n16 2\n17 2\n18 2\n19 2\n20 2" }, { "code": null, "e": 1763, "s": 1708, "text": "> df2<-data.frame(x1=rpois(20,2),x2=rpois(20,5))\n> df2" }, { "code": null, "e": 1952, "s": 1763, "text": " x1 x2\n1 2 5\n2 2 5\n3 3 6\n4 0 5\n5 1 3\n6 1 5\n7 2 6\n8 1 3\n9 4 6\n10 0 5\n11 1 0\n12 3 4\n13 1 3\n14 1 4\n15 2 6\n16 1 5\n17 2 2\n18 3 8\n19 0 5\n20 1 6" }, { "code": null, "e": 1997, "s": 1952, "text": "> df1$x2<-df2$x2[match(df1$x1,df2$x1)]\n> df1" }, { "code": null, "e": 2186, "s": 1997, "text": " x1 x2\n1 2 5\n2 2 5\n3 1 3\n4 0 5\n5 2 5\n6 2 5\n7 2 5\n8 2 5\n9 2 5\n10 1 3\n11 1 3\n12 2 5\n13 1 3\n14 0 5\n15 2 5\n16 2 5\n17 2 5\n18 2 5\n19 2 5\n20 2 5" }, { "code": null, "e": 2196, "s": 2186, "text": "Live Demo" }, { "code": null, "e": 2269, "s": 2196, "text": "> y1<-sample(c(\"A\",\"B\",\"C\"),20,replace=TRUE)\n> df3<-data.frame(y1)\n> df3" }, { "code": null, "e": 2395, "s": 2269, "text": " y1\n1 A\n2 C\n3 C\n4 A\n5 C\n6 B\n7 C\n8 B\n9 B\n10 C\n11 B\n12 C\n13 B\n14 A\n15 A\n16 C\n17 B\n18 B\n19 A\n20 A" }, { "code": null, "e": 2522, "s": 2395, "text": "> y1<-sample(c(\"A\",\"B\",\"C\",\"D\",\"E\"),20,replace=TRUE)\n> y2<-sample(LETTERS[1:4],20,replace=TRUE)\n> df4<-data.frame(y1,y2)\n> df4" }, { "code": null, "e": 2711, "s": 2522, "text": " y1 y2\n1 E C\n2 A D\n3 C B\n4 C D\n5 D B\n6 B D\n7 D C\n8 C B\n9 D D\n10 C A\n11 B D\n12 B C\n13 C B\n14 B D\n15 D C\n16 B B\n17 E C\n18 D B\n19 A D\n20 B C" }, { "code": null, "e": 2756, "s": 2711, "text": "> df3$y2<-df4$y2[match(df3$y1,df4$y1)]\n> df3" }, { "code": null, "e": 2945, "s": 2756, "text": " y1 y2\n1 A D\n2 C B\n3 C B\n4 A D\n5 C B\n6 B D\n7 C B\n8 B D\n9 B D\n10 C B\n11 B D\n12 C B\n13 B D\n14 A D\n15 A D\n16 C B\n17 B D\n18 B D\n19 A D\n20 A D" } ]
KnockoutJS - CSS Binding
This binding allows you to define CSS classes for the HTML DOM elements based on certain condition. This is useful in case you need to highlight some data depending on a situation. css: <binding-object> In case of static CSS binding, the parameter can be in the form of JavaScript Object, consisting of property and its value. Property here refers to CSS class to be applied and value can be Boolean true, or false, or JavaScript expression or a function. Classes can be also applied dynamically using Computed Observable functions. In case of static CSS binding, the parameter can be in the form of JavaScript Object, consisting of property and its value. Property here refers to CSS class to be applied and value can be Boolean true, or false, or JavaScript expression or a function. Property here refers to CSS class to be applied and value can be Boolean true, or false, or JavaScript expression or a function. Classes can be also applied dynamically using Computed Observable functions. Classes can be also applied dynamically using Computed Observable functions. Multiple CSS classes can also be applied at once. Following is an example of how 2 classes are added to binding. Multiple CSS classes can also be applied at once. Following is an example of how 2 classes are added to binding. <div data-bind = "css: { outOfStock : productStock() === 0, discountAvailable: discount }"> Class names can also be specified in single quotes such as 'discount Available'. Class names can also be specified in single quotes such as 'discount Available'. 0 and null are treated as false value. Numbers and other objects are treated as true value. 0 and null are treated as false value. Numbers and other objects are treated as true value. If the ViewModel property is an observable, then CSS classes are decided depending on the new updated parameter value. If it is not an observable value, then classes are determined only once for the first time. If the ViewModel property is an observable, then CSS classes are decided depending on the new updated parameter value. If it is not an observable value, then classes are determined only once for the first time. Let us take a look at the following example which demonstrates the use of CSS binding. <!DOCTYPE html> <head> <title>KnockoutJS CSS binding</title> <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js" type = "text/javascript"></script> <style> .outOfStock { color: red; font-weight: bold; } </style> </head> <body> <div data-bind = "css: { outOfStock : productStock() === 0 }"> Product Details. </div> <script> function AppViewModel() { this.productStock = ko.observable(0); } var vm = new AppViewModel(); ko.applyBindings(vm); </script> </body> </html> Let's carry out the following steps to see how the above code works − Save the above code in css-bind.htm file. Save the above code in css-bind.htm file. Open this HTML file in a browser. Open this HTML file in a browser. Product Information is shown in a normal way when the productStockproperty is above 0. Product Information becomes red and bold. once productStock becomes 0. Product Information is shown in a normal way when the productStockproperty is above 0. Product Information becomes red and bold. once productStock becomes 0. 38 Lectures 2 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2033, "s": 1852, "text": "This binding allows you to define CSS classes for the HTML DOM elements based on certain condition. This is useful in case you need to highlight some data depending on a situation." }, { "code": null, "e": 2056, "s": 2033, "text": "css: <binding-object>\n" }, { "code": null, "e": 2389, "s": 2056, "text": "In case of static CSS binding, the parameter can be in the form of JavaScript Object, consisting of property and its value.\n\nProperty here refers to CSS class to be applied and value can be Boolean true, or false, or JavaScript expression or a function.\nClasses can be also applied dynamically using Computed Observable functions.\n\n" }, { "code": null, "e": 2513, "s": 2389, "text": "In case of static CSS binding, the parameter can be in the form of JavaScript Object, consisting of property and its value." }, { "code": null, "e": 2642, "s": 2513, "text": "Property here refers to CSS class to be applied and value can be Boolean true, or false, or JavaScript expression or a function." }, { "code": null, "e": 2771, "s": 2642, "text": "Property here refers to CSS class to be applied and value can be Boolean true, or false, or JavaScript expression or a function." }, { "code": null, "e": 2848, "s": 2771, "text": "Classes can be also applied dynamically using Computed Observable functions." }, { "code": null, "e": 2925, "s": 2848, "text": "Classes can be also applied dynamically using Computed Observable functions." }, { "code": null, "e": 3038, "s": 2925, "text": "Multiple CSS classes can also be applied at once. Following is an example of how 2 classes are added to binding." }, { "code": null, "e": 3151, "s": 3038, "text": "Multiple CSS classes can also be applied at once. Following is an example of how 2 classes are added to binding." }, { "code": null, "e": 3252, "s": 3151, "text": "<div data-bind = \"css: { \n outOfStock : productStock() === 0, \n discountAvailable: discount \n}\">" }, { "code": null, "e": 3333, "s": 3252, "text": "Class names can also be specified in single quotes such as 'discount Available'." }, { "code": null, "e": 3414, "s": 3333, "text": "Class names can also be specified in single quotes such as 'discount Available'." }, { "code": null, "e": 3506, "s": 3414, "text": "0 and null are treated as false value. Numbers and other objects are treated as true value." }, { "code": null, "e": 3598, "s": 3506, "text": "0 and null are treated as false value. Numbers and other objects are treated as true value." }, { "code": null, "e": 3809, "s": 3598, "text": "If the ViewModel property is an observable, then CSS classes are decided depending on the new updated parameter value. If it is not an observable value, then classes are determined only once for the first time." }, { "code": null, "e": 4020, "s": 3809, "text": "If the ViewModel property is an observable, then CSS classes are decided depending on the new updated parameter value. If it is not an observable value, then classes are determined only once for the first time." }, { "code": null, "e": 4107, "s": 4020, "text": "Let us take a look at the following example which demonstrates the use of CSS binding." }, { "code": null, "e": 4800, "s": 4107, "text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS CSS binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js\"\n type = \"text/javascript\"></script>\n \n <style>\n .outOfStock {\n color: red;\n font-weight: bold;\n }\n </style>\n \n </head>\n \n <body>\n <div data-bind = \"css: { outOfStock : productStock() === 0 }\">\n Product Details.\n </div>\n\n <script>\n function AppViewModel() {\n this.productStock = ko.observable(0);\n }\n \n var vm = new AppViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 4870, "s": 4800, "text": "Let's carry out the following steps to see how the above code works −" }, { "code": null, "e": 4912, "s": 4870, "text": "Save the above code in css-bind.htm file." }, { "code": null, "e": 4954, "s": 4912, "text": "Save the above code in css-bind.htm file." }, { "code": null, "e": 4988, "s": 4954, "text": "Open this HTML file in a browser." }, { "code": null, "e": 5022, "s": 4988, "text": "Open this HTML file in a browser." }, { "code": null, "e": 5180, "s": 5022, "text": "Product Information is shown in a normal way when the productStockproperty is above 0. Product Information becomes red and bold. once productStock becomes 0." }, { "code": null, "e": 5338, "s": 5180, "text": "Product Information is shown in a normal way when the productStockproperty is above 0. Product Information becomes red and bold. once productStock becomes 0." }, { "code": null, "e": 5371, "s": 5338, "text": "\n 38 Lectures \n 2 hours \n" }, { "code": null, "e": 5391, "s": 5371, "text": " Skillbakerystudios" }, { "code": null, "e": 5398, "s": 5391, "text": " Print" }, { "code": null, "e": 5409, "s": 5398, "text": " Add Notes" } ]
TypeScript - Interfaces
An interface is a syntactical contract that an entity should conform to. In other words, an interface defines the syntax that any entity must adhere to. Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow. Let’s consider an object − var person = { FirstName:"Tom", LastName:"Hanks", sayHi: ()=>{ return "Hi"} }; If we consider the signature of the object, it could be − { FirstName:string, LastName:string, sayHi()=>string } To reuse the signature across objects we can define it as an interface. The interface keyword is used to declare an interface. Here is the syntax to declare an interface − interface interface_name { } interface IPerson { firstName:string, lastName:string, sayHi: ()=>string } var customer:IPerson = { firstName:"Tom", lastName:"Hanks", sayHi: ():string =>{return "Hi there"} } console.log("Customer Object ") console.log(customer.firstName) console.log(customer.lastName) console.log(customer.sayHi()) var employee:IPerson = { firstName:"Jim", lastName:"Blakes", sayHi: ():string =>{return "Hello!!!"} } console.log("Employee Object ") console.log(employee.firstName); console.log(employee.lastName); The example defines an interface. The customer object is of the type IPerson. Hence, it will now be binding on the object to define all properties as specified by the interface. Another object with following signature, is still considered as IPerson because that object is treated by its size or signature. On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var customer = { firstName: "Tom", lastName: "Hanks", sayHi: function () { return "Hi there"; } }; console.log("Customer Object "); console.log(customer.firstName); console.log(customer.lastName); console.log(customer.sayHi()); var employee = { firstName: "Jim", lastName: "Blakes", sayHi: function () { return "Hello!!!"; } }; console.log("Employee Object "); console.log(employee.firstName); console.log(employee.lastName); The output of the above example code is as follows − Customer object Tom Hanks Hi there Employee object Jim Blakes Hello!!! Interfaces are not to be converted to JavaScript. It’s just part of TypeScript. If you see the screen shot of TS Playground tool there is no java script emitted when you declare an interface unlike a class. So interfaces have zero runtime JavaScript impact. The following example shows the use of Union Type and Interface − interface RunOptions { program:string; commandline:string[]|string|(()=>string); } //commandline as string var options:RunOptions = {program:"test1",commandline:"Hello"}; console.log(options.commandline) //commandline as a string array options = {program:"test1",commandline:["Hello","World"]}; console.log(options.commandline[0]); console.log(options.commandline[1]); //commandline as a function expression options = {program:"test1",commandline:()=>{return "**Hello World**";}}; var fn:any = options.commandline; console.log(fn()); On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 //commandline as string var options = { program: "test1", commandline: "Hello" }; console.log(options.commandline); //commandline as a string array options = { program: "test1", commandline: ["Hello", "World"] }; console.log(options.commandline[0]); console.log(options.commandline[1]); //commandline as a function expression options = { program: "test1", commandline: function () { return "**Hello World**"; } }; var fn = options.commandline; console.log(fn()); Its output is as follows − Hello Hello World **Hello World** Interface can define both the kind of key an array uses and the type of entry it contains. Index can be of type string or type number. interface namelist { [index:number]:string } var list2:namelist = ["John",1,"Bran"] //Error. 1 is not type string interface ages { [index:string]:number } var agelist:ages; agelist["John"] = 15 // Ok agelist[2] = "nine" // Error An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces. Child_interface_name extends super_interface_name Child_interface_name extends super_interface1_name, super_interface2_name,...,super_interfaceN_name interface Person { age:number } interface Musician extends Person { instrument:string } var drummer = <Musician>{}; drummer.age = 27 drummer.instrument = "Drums" console.log("Age: "+drummer.age) console.log("Instrument: "+drummer.instrument) On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var drummer = {}; drummer.age = 27; drummer.instrument = "Drums"; console.log("Age: " + drummer.age); console.log("Instrument: " + drummer.instrument); Its output is as follows − Age: 27 Instrument: Drums interface IParent1 { v1:number } interface IParent2 { v2:number } interface Child extends IParent1, IParent2 { } var Iobj:Child = { v1:12, v2:23} console.log("value 1: "+this.v1+" value 2: "+this.v2) The object Iobj is of the type interface leaf. The interface leaf by the virtue of inheritance now has two attributes- v1 and v2 respectively. Hence, the object Iobj must now contain these attributes. On compiling, it will generate following JavaScript code. //Generated by typescript 1.8.10 var Iobj = { v1: 12, v2: 23 }; console.log("value 1: " + this.v1 + " value 2: " + this.v2); The output of the above code is as follows − value 1: 12 value 2: 23 45 Lectures 4 hours Antonio Papa 41 Lectures 7 hours Haider Malik 60 Lectures 2.5 hours Skillbakerystudios 77 Lectures 8 hours Sean Bradley 77 Lectures 3.5 hours TELCOMA Global 19 Lectures 3 hours Christopher Frewin Print Add Notes Bookmark this page
[ { "code": null, "e": 2201, "s": 2048, "text": "An interface is a syntactical contract that an entity should conform to. In other words, an interface defines the syntax that any entity must adhere to." }, { "code": null, "e": 2507, "s": 2201, "text": "Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow." }, { "code": null, "e": 2534, "s": 2507, "text": "Let’s consider an object −" }, { "code": null, "e": 2627, "s": 2534, "text": "var person = { \n FirstName:\"Tom\", \n LastName:\"Hanks\", \n sayHi: ()=>{ return \"Hi\"} \n};\n" }, { "code": null, "e": 2685, "s": 2627, "text": "If we consider the signature of the object, it could be −" }, { "code": null, "e": 2754, "s": 2685, "text": "{ \n FirstName:string, \n LastName:string, \n sayHi()=>string \n}\n" }, { "code": null, "e": 2826, "s": 2754, "text": "To reuse the signature across objects we can define it as an interface." }, { "code": null, "e": 2926, "s": 2826, "text": "The interface keyword is used to declare an interface. Here is the syntax to declare an interface −" }, { "code": null, "e": 2957, "s": 2926, "text": "interface interface_name { \n}\n" }, { "code": null, "e": 3511, "s": 2957, "text": "interface IPerson { \n firstName:string, \n lastName:string, \n sayHi: ()=>string \n} \n\nvar customer:IPerson = { \n firstName:\"Tom\",\n lastName:\"Hanks\", \n sayHi: ():string =>{return \"Hi there\"} \n} \n\nconsole.log(\"Customer Object \") \nconsole.log(customer.firstName) \nconsole.log(customer.lastName) \nconsole.log(customer.sayHi()) \n\nvar employee:IPerson = { \n firstName:\"Jim\",\n lastName:\"Blakes\", \n sayHi: ():string =>{return \"Hello!!!\"} \n} \n \nconsole.log(\"Employee Object \") \nconsole.log(employee.firstName);\nconsole.log(employee.lastName);\n" }, { "code": null, "e": 3689, "s": 3511, "text": "The example defines an interface. The customer object is of the type IPerson. Hence, it will now be binding on the object to define all properties as specified by the interface." }, { "code": null, "e": 3818, "s": 3689, "text": "Another object with following signature, is still considered as IPerson because that object is treated by its size or signature." }, { "code": null, "e": 3876, "s": 3818, "text": "On compiling, it will generate following JavaScript code." }, { "code": null, "e": 4344, "s": 3876, "text": "//Generated by typescript 1.8.10\nvar customer = { firstName: \"Tom\", lastName: \"Hanks\",\n sayHi: function () { return \"Hi there\"; }\n};\nconsole.log(\"Customer Object \");\nconsole.log(customer.firstName);\nconsole.log(customer.lastName);\nconsole.log(customer.sayHi());\nvar employee = { firstName: \"Jim\", lastName: \"Blakes\",\n sayHi: function () { return \"Hello!!!\"; } };\n\nconsole.log(\"Employee Object \");\nconsole.log(employee.firstName);\nconsole.log(employee.lastName);\n" }, { "code": null, "e": 4397, "s": 4344, "text": "The output of the above example code is as follows −" }, { "code": null, "e": 4478, "s": 4397, "text": "Customer object \nTom \nHanks \nHi there \nEmployee object \nJim \nBlakes \nHello!!!\n" }, { "code": null, "e": 4736, "s": 4478, "text": "Interfaces are not to be converted to JavaScript. It’s just part of TypeScript. If you see the screen shot of TS Playground tool there is no java script emitted when you declare an interface unlike a class. So interfaces have zero runtime JavaScript impact." }, { "code": null, "e": 4802, "s": 4736, "text": "The following example shows the use of Union Type and Interface −" }, { "code": null, "e": 5363, "s": 4802, "text": "interface RunOptions { \n program:string; \n commandline:string[]|string|(()=>string); \n} \n\n//commandline as string \nvar options:RunOptions = {program:\"test1\",commandline:\"Hello\"}; \nconsole.log(options.commandline) \n\n//commandline as a string array \noptions = {program:\"test1\",commandline:[\"Hello\",\"World\"]}; \nconsole.log(options.commandline[0]); \nconsole.log(options.commandline[1]); \n\n//commandline as a function expression \noptions = {program:\"test1\",commandline:()=>{return \"**Hello World**\";}}; \n\nvar fn:any = options.commandline; \nconsole.log(fn());\n" }, { "code": null, "e": 5421, "s": 5363, "text": "On compiling, it will generate following JavaScript code." }, { "code": null, "e": 5920, "s": 5421, "text": "//Generated by typescript 1.8.10\n//commandline as string\nvar options = { program: \"test1\", commandline: \"Hello\" };\nconsole.log(options.commandline);\n\n//commandline as a string array\noptions = { program: \"test1\", commandline: [\"Hello\", \"World\"] };\nconsole.log(options.commandline[0]);\nconsole.log(options.commandline[1]);\n\n//commandline as a function expression\noptions = { program: \"test1\", commandline: function () { return \"**Hello World**\"; } };\nvar fn = options.commandline;\nconsole.log(fn());\n" }, { "code": null, "e": 5947, "s": 5920, "text": "Its output is as follows −" }, { "code": null, "e": 5985, "s": 5947, "text": "Hello \nHello \nWorld \n**Hello World**\n" }, { "code": null, "e": 6120, "s": 5985, "text": "Interface can define both the kind of key an array uses and the type of entry it contains. Index can be of type string or type number." }, { "code": null, "e": 6372, "s": 6120, "text": "interface namelist { \n [index:number]:string \n} \n\nvar list2:namelist = [\"John\",1,\"Bran\"] //Error. 1 is not type string \ninterface ages { \n [index:string]:number \n} \n\nvar agelist:ages; \nagelist[\"John\"] = 15 // Ok \nagelist[2] = \"nine\" // Error\n" }, { "code": null, "e": 6553, "s": 6372, "text": "An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces." }, { "code": null, "e": 6620, "s": 6553, "text": "Use the extends keyword to implement inheritance among interfaces." }, { "code": null, "e": 6671, "s": 6620, "text": "Child_interface_name extends super_interface_name\n" }, { "code": null, "e": 6773, "s": 6671, "text": "Child_interface_name extends super_interface1_name, \nsuper_interface2_name,...,super_interfaceN_name\n" }, { "code": null, "e": 7035, "s": 6773, "text": "interface Person { \n age:number \n} \n\ninterface Musician extends Person { \n instrument:string \n} \n\nvar drummer = <Musician>{}; \ndrummer.age = 27 \ndrummer.instrument = \"Drums\" \nconsole.log(\"Age: \"+drummer.age) console.log(\"Instrument: \"+drummer.instrument)\n" }, { "code": null, "e": 7093, "s": 7035, "text": "On compiling, it will generate following JavaScript code." }, { "code": null, "e": 7281, "s": 7093, "text": "//Generated by typescript 1.8.10\nvar drummer = {};\ndrummer.age = 27;\ndrummer.instrument = \"Drums\";\nconsole.log(\"Age: \" + drummer.age);\nconsole.log(\"Instrument: \" + drummer.instrument);\n" }, { "code": null, "e": 7308, "s": 7281, "text": "Its output is as follows −" }, { "code": null, "e": 7337, "s": 7308, "text": "Age: 27 \nInstrument: Drums \n" }, { "code": null, "e": 7554, "s": 7337, "text": "interface IParent1 { \n v1:number \n} \n\ninterface IParent2 { \n v2:number \n} \n\ninterface Child extends IParent1, IParent2 { } \nvar Iobj:Child = { v1:12, v2:23} \nconsole.log(\"value 1: \"+this.v1+\" value 2: \"+this.v2)\n" }, { "code": null, "e": 7755, "s": 7554, "text": "The object Iobj is of the type interface leaf. The interface leaf by the virtue of inheritance now has two attributes- v1 and v2 respectively. Hence, the object Iobj must now contain these attributes." }, { "code": null, "e": 7813, "s": 7755, "text": "On compiling, it will generate following JavaScript code." }, { "code": null, "e": 7939, "s": 7813, "text": "//Generated by typescript 1.8.10\nvar Iobj = { v1: 12, v2: 23 };\nconsole.log(\"value 1: \" + this.v1 + \" value 2: \" + this.v2);\n" }, { "code": null, "e": 7984, "s": 7939, "text": "The output of the above code is as follows −" }, { "code": null, "e": 8011, "s": 7984, "text": "value 1: 12 value 2: 23\n" }, { "code": null, "e": 8044, "s": 8011, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 8058, "s": 8044, "text": " Antonio Papa" }, { "code": null, "e": 8091, "s": 8058, "text": "\n 41 Lectures \n 7 hours \n" }, { "code": null, "e": 8105, "s": 8091, "text": " Haider Malik" }, { "code": null, "e": 8140, "s": 8105, "text": "\n 60 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8160, "s": 8140, "text": " Skillbakerystudios" }, { "code": null, "e": 8193, "s": 8160, "text": "\n 77 Lectures \n 8 hours \n" }, { "code": null, "e": 8207, "s": 8193, "text": " Sean Bradley" }, { "code": null, "e": 8242, "s": 8207, "text": "\n 77 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8258, "s": 8242, "text": " TELCOMA Global" }, { "code": null, "e": 8291, "s": 8258, "text": "\n 19 Lectures \n 3 hours \n" }, { "code": null, "e": 8311, "s": 8291, "text": " Christopher Frewin" }, { "code": null, "e": 8318, "s": 8311, "text": " Print" }, { "code": null, "e": 8329, "s": 8318, "text": " Add Notes" } ]
How to read contents of a file using Scanner class?
From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. By default, whitespace is considered as the delimiter (to break the data into tokens). To read various datatypes from the source using the nextXXX() methods provided by this class. To read the contents of a file, Scanner class provides various constructors. Assume we have a file myFile.txt in the path D:\ as shown below − Following examples demonstrate how to read data from this file using the above constructors. Create a File object representing your required file. Create a Scanner class by passing the above created file object. The hasNext() verifies whether the file has another line and the nextLine() method reads and returns the next line in the file. Using these methods read the contents of the file. import java.io.File; import java.util.Scanner; public class ContentsOfFile { public static void main(String args[]) throws Exception { //Creating the File object File file = new File("D:\\MyFile.txt"); //Creating a Scanner object Scanner sc = new Scanner(file); //StringBuffer to store the contents StringBuffer sb = new StringBuffer(); //Appending each line to the buffer while(sc.hasNext()) { sb.append(" "+sc.nextLine()); } System.out.println(sb); } } Hi welcome to Tutorialspoint .... Create an FileInputStream object by passing the path of the required file to its constructor, as a parameter. Create a Scanner class by passing the above created FileInputStream object. The hasNext() verifies whether the file has another line and the nextLine() method reads and returns the next line in the file. Using these methods read the contents of the file. import java.io.FileInputStream; import java.io.InputStream; import java.util.Scanner; public class ContentsOfFile { public static void main(String args[]) throws Exception { //Creating the File object InputStream inputStream = new FileInputStream("D:\\MyFile.txt"); //Creating a Scanner object Scanner sc = new Scanner(inputStream); //StringBuffer to store the contents StringBuffer sb = new StringBuffer(); //Appending each line to the buffer while(sc.hasNext()) { sb.append(" "+sc.nextLine()); } System.out.println(sb); } } Hi welcome to Tutorialspoint ....
[ { "code": null, "e": 1372, "s": 1062, "text": "From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. By default, whitespace is considered as the delimiter (to break the data into tokens)." }, { "code": null, "e": 1466, "s": 1372, "text": "To read various datatypes from the source using the nextXXX() methods provided by this class." }, { "code": null, "e": 1543, "s": 1466, "text": "To read the contents of a file, Scanner class provides various constructors." }, { "code": null, "e": 1609, "s": 1543, "text": "Assume we have a file myFile.txt in the path D:\\ as shown below −" }, { "code": null, "e": 1702, "s": 1609, "text": "Following examples demonstrate how to read data from this file using the above constructors." }, { "code": null, "e": 1756, "s": 1702, "text": "Create a File object representing your required file." }, { "code": null, "e": 1821, "s": 1756, "text": "Create a Scanner class by passing the above created file object." }, { "code": null, "e": 2000, "s": 1821, "text": "The hasNext() verifies whether the file has another line and the nextLine() method reads and returns the next line in the file. Using these methods read the contents of the file." }, { "code": null, "e": 2530, "s": 2000, "text": "import java.io.File;\nimport java.util.Scanner;\npublic class ContentsOfFile {\n public static void main(String args[]) throws Exception {\n //Creating the File object\n File file = new File(\"D:\\\\MyFile.txt\");\n //Creating a Scanner object\n Scanner sc = new Scanner(file);\n //StringBuffer to store the contents\n StringBuffer sb = new StringBuffer();\n //Appending each line to the buffer\n while(sc.hasNext()) {\n sb.append(\" \"+sc.nextLine());\n }\n System.out.println(sb);\n }\n}" }, { "code": null, "e": 2564, "s": 2530, "text": "Hi welcome to Tutorialspoint ...." }, { "code": null, "e": 2674, "s": 2564, "text": "Create an FileInputStream object by passing the path of the required file to its constructor, as a parameter." }, { "code": null, "e": 2750, "s": 2674, "text": "Create a Scanner class by passing the above created FileInputStream object." }, { "code": null, "e": 2929, "s": 2750, "text": "The hasNext() verifies whether the file has another line and the nextLine() method reads and returns the next line in the file. Using these methods read the contents of the file." }, { "code": null, "e": 3530, "s": 2929, "text": "import java.io.FileInputStream;\nimport java.io.InputStream;\nimport java.util.Scanner;\npublic class ContentsOfFile {\n public static void main(String args[]) throws Exception {\n //Creating the File object\n InputStream inputStream = new FileInputStream(\"D:\\\\MyFile.txt\");\n //Creating a Scanner object\n Scanner sc = new Scanner(inputStream);\n //StringBuffer to store the contents\n StringBuffer sb = new StringBuffer();\n //Appending each line to the buffer\n while(sc.hasNext()) {\n sb.append(\" \"+sc.nextLine());\n }\n System.out.println(sb);\n }\n}" }, { "code": null, "e": 3564, "s": 3530, "text": "Hi welcome to Tutorialspoint ...." } ]
How to convert a datetime string to millisecond UNIX time stamp?
You can get the current time in milliseconds in Python using the time module. You can get the time in seconds using time.time function(as a floating point value). To convert it to milliseconds, you need to multiply it with 1000 and round it off. import time milliseconds = int(round(time.time() * 1000)) print(milliseconds) This will give the output − 1514825676008 If you want to convert a datetime object to milliseconds timestamp, you can use the timestamp function then apply the same math as above to get the milliseconds time. import time from datetime import datetime dt = datetime(2018, 1, 1) milliseconds = int(round(dt.timestamp() * 1000)) print(milliseconds) This will give the output − 1514745000000
[ { "code": null, "e": 1309, "s": 1062, "text": "You can get the current time in milliseconds in Python using the time module. You can get the time in seconds using time.time function(as a floating point value). To convert it to milliseconds, you need to multiply it with 1000 and round it off. " }, { "code": null, "e": 1387, "s": 1309, "text": "import time\nmilliseconds = int(round(time.time() * 1000))\nprint(milliseconds)" }, { "code": null, "e": 1415, "s": 1387, "text": "This will give the output −" }, { "code": null, "e": 1429, "s": 1415, "text": "1514825676008" }, { "code": null, "e": 1597, "s": 1429, "text": "If you want to convert a datetime object to milliseconds timestamp, you can use the timestamp function then apply the same math as above to get the milliseconds time. " }, { "code": null, "e": 1734, "s": 1597, "text": "import time\nfrom datetime import datetime\ndt = datetime(2018, 1, 1)\nmilliseconds = int(round(dt.timestamp() * 1000))\nprint(milliseconds)" }, { "code": null, "e": 1762, "s": 1734, "text": "This will give the output −" }, { "code": null, "e": 1776, "s": 1762, "text": "1514745000000" } ]
How to create a vector with repeated values in R?
There are two methods to create a vector with repeated values in R but both of them have different approaches, first one is by repeating each element of the vector and the second repeats the elements by a specified number of times. Both of these methods use rep function to create the vectors. Consider the below examples − > x1<-rep(c(1,2,3,4,5),each=10) > x1 [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 [39] 4 4 5 5 5 5 5 5 5 5 5 5 > x2<-rep(c(1,2,3,4,5),times=10) > x2 [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 [39] 4 5 1 2 3 4 5 1 2 3 4 5 > x3<-rep(c(1,2,3,4,5),times=c(10,10,10,10,10)) > x3 [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 [39] 4 4 5 5 5 5 5 5 5 5 5 5 > x4<-rep(c(1,2,3,4,5),times=c(10,20,30,40,50)) > x4 [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 [38] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 [75] 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 [112] 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 [149] 5 5 > x5<-rep(c(1,2,3,4,5),times=c(12,2,30,7,42)) > x5 [1] 1 1 1 1 1 1 1 1 1 1 1 1 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 [39] 3 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 [77] 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 > x6<-rep(1,10) > x6 [1] 1 1 1 1 1 1 1 1 1 1 > x7<-rep(1:5,10) > x7 [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 [39] 4 5 1 2 3 4 5 1 2 3 4 5 > x8<-rep(1:5,each=10) > x8 [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 [39] 4 4 5 5 5 5 5 5 5 5 5 5 > x9<-rep(1:5,times=c(1,2,3,4,5)) > x9 [1] 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 > x10<-rep(c(letters[1:26]),times=1) > x10 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" [20] "t" "u" "v" "w" "x" "y" "z" > x11<-rep(c(letters[1:26]),times=5) > x11 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" [19] "s" "t" "u" "v" "w" "x" "y" "z" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" [37] "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" "a" "b" [55] "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" [73] "u" "v" "w" "x" "y" "z" "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" [91] "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" "a" "b" "c" "d" [109] "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" [127] "w" "x" "y" "z" > x12<-rep(c(letters[1:26]),times=1:26) > x12 [1] "a" "b" "b" "c" "c" "c" "d" "d" "d" "d" "e" "e" "e" "e" "e" "f" "f" "f" [19] "f" "f" "f" "g" "g" "g" "g" "g" "g" "g" "h" "h" "h" "h" "h" "h" "h" "h" [37] "i" "i" "i" "i" "i" "i" "i" "i" "i" "j" "j" "j" "j" "j" "j" "j" "j" "j" [55] "j" "k" "k" "k" "k" "k" "k" "k" "k" "k" "k" "k" "l" "l" "l" "l" "l" "l" [73] "l" "l" "l" "l" "l" "l" "m" "m" "m" "m" "m" "m" "m" "m" "m" "m" "m" "m" [91] "m" "n" "n" "n" "n" "n" "n" "n" "n" "n" "n" "n" "n" "n" "n" "o" "o" "o" [109] "o" "o" "o" "o" "o" "o" "o" "o" "o" "o" "o" "o" "p" "p" "p" "p" "p" "p" [127] "p" "p" "p" "p" "p" "p" "p" "p" "p" "p" "q" "q" "q" "q" "q" "q" "q" "q" [145] "q" "q" "q" "q" "q" "q" "q" "q" "q" "r" "r" "r" "r" "r" "r" "r" "r" "r" [163] "r" "r" "r" "r" "r" "r" "r" "r" "r" "s" "s" "s" "s" "s" "s" "s" "s" "s" [181] "s" "s" "s" "s" "s" "s" "s" "s" "s" "s" "t" "t" "t" "t" "t" "t" "t" "t" [199] "t" "t" "t" "t" "t" "t" "t" "t" "t" "t" "t" "t" "u" "u" "u" "u" "u" "u" [217] "u" "u" "u" "u" "u" "u" "u" "u" "u" "u" "u" "u" "u" "u" "u" "v" "v" "v" [235] "v" "v" "v" "v" "v" "v" "v" "v" "v" "v" "v" "v" "v" "v" "v" "v" "v" "v" [253] "v" "w" "w" "w" "w" "w" "w" "w" "w" "w" "w" "w" "w" "w" "w" "w" "w" "w" [271] "w" "w" "w" "w" "w" "w" "x" "x" "x" "x" "x" "x" "x" "x" "x" "x" "x" "x" [289] "x" "x" "x" "x" "x" "x" "x" "x" "x" "x" "x" "x" "y" "y" "y" "y" "y" "y" [307] "y" "y" "y" "y" "y" "y" "y" "y" "y" "y" "y" "y" "y" "y" "y" "y" "y" "y" [325] "y" "z" "z" "z" "z" "z" "z" "z" "z" "z" "z" "z" "z" "z" "z" "z" "z" "z" [343] "z" "z" "z" "z" "z" "z" "z" "z" "z" > x13<-rep(c("A","B","C","D"),times=c(4,3,2,1)) > x13 [1] "A" "A" "A" "A" "B" "B" "B" "C" "C" "D"
[ { "code": null, "e": 1356, "s": 1062, "text": "There are two methods to create a vector with repeated values in R but both of them have different approaches, first one is by repeating each element of the vector and the second repeats the elements by a specified number of times. Both of these methods use rep function to create the vectors." }, { "code": null, "e": 1386, "s": 1356, "text": "Consider the below examples −" }, { "code": null, "e": 5279, "s": 1386, "text": "> x1<-rep(c(1,2,3,4,5),each=10)\n> x1\n[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4\n[39] 4 4 5 5 5 5 5 5 5 5 5 5\n> x2<-rep(c(1,2,3,4,5),times=10)\n> x2\n[1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3\n[39] 4 5 1 2 3 4 5 1 2 3 4 5\n> x3<-rep(c(1,2,3,4,5),times=c(10,10,10,10,10))\n> x3\n[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4\n[39] 4 4 5 5 5 5 5 5 5 5 5 5\n> x4<-rep(c(1,2,3,4,5),times=c(10,20,30,40,50))\n> x4\n[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3\n[38] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4\n[75] 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5\n[112] 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5\n[149] 5 5\n> x5<-rep(c(1,2,3,4,5),times=c(12,2,30,7,42))\n> x5\n[1] 1 1 1 1 1 1 1 1 1 1 1 1 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3\n[39] 3 3 3 3 3 3 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5\n[77] 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5\n> x6<-rep(1,10)\n> x6\n[1] 1 1 1 1 1 1 1 1 1 1\n> x7<-rep(1:5,10)\n> x7\n[1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3\n[39] 4 5 1 2 3 4 5 1 2 3 4 5\n> x8<-rep(1:5,each=10)\n> x8\n[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4\n[39] 4 4 5 5 5 5 5 5 5 5 5 5\n> x9<-rep(1:5,times=c(1,2,3,4,5))\n> x9\n[1] 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5\n> x10<-rep(c(letters[1:26]),times=1)\n> x10\n[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\" \"k\" \"l\" \"m\" \"n\" \"o\" \"p\" \"q\" \"r\" \"s\"\n[20] \"t\" \"u\" \"v\" \"w\" \"x\" \"y\" \"z\"\n> x11<-rep(c(letters[1:26]),times=5)\n> x11\n[1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\" \"k\" \"l\" \"m\" \"n\" \"o\" \"p\" \"q\" \"r\"\n[19] \"s\" \"t\" \"u\" \"v\" \"w\" \"x\" \"y\" \"z\" \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\"\n[37] \"k\" \"l\" \"m\" \"n\" \"o\" \"p\" \"q\" \"r\" \"s\" \"t\" \"u\" \"v\" \"w\" \"x\" \"y\" \"z\" \"a\" \"b\"\n[55] \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\" \"k\" \"l\" \"m\" \"n\" \"o\" \"p\" \"q\" \"r\" \"s\" \"t\"\n[73] \"u\" \"v\" \"w\" \"x\" \"y\" \"z\" \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\" \"k\" \"l\"\n[91] \"m\" \"n\" \"o\" \"p\" \"q\" \"r\" \"s\" \"t\" \"u\" \"v\" \"w\" \"x\" \"y\" \"z\" \"a\" \"b\" \"c\" \"d\"\n[109] \"e\" \"f\" \"g\" \"h\" \"i\" \"j\" \"k\" \"l\" \"m\" \"n\" \"o\" \"p\" \"q\" \"r\" \"s\" \"t\" \"u\" \"v\"\n[127] \"w\" \"x\" \"y\" \"z\"\n> x12<-rep(c(letters[1:26]),times=1:26)\n> x12\n[1] \"a\" \"b\" \"b\" \"c\" \"c\" \"c\" \"d\" \"d\" \"d\" \"d\" \"e\" \"e\" \"e\" \"e\" \"e\" \"f\" \"f\" \"f\"\n[19] \"f\" \"f\" \"f\" \"g\" \"g\" \"g\" \"g\" \"g\" \"g\" \"g\" \"h\" \"h\" \"h\" \"h\" \"h\" \"h\" \"h\" \"h\"\n[37] \"i\" \"i\" \"i\" \"i\" \"i\" \"i\" \"i\" \"i\" \"i\" \"j\" \"j\" \"j\" \"j\" \"j\" \"j\" \"j\" \"j\" \"j\"\n[55] \"j\" \"k\" \"k\" \"k\" \"k\" \"k\" \"k\" \"k\" \"k\" \"k\" \"k\" \"k\" \"l\" \"l\" \"l\" \"l\" \"l\" \"l\"\n[73] \"l\" \"l\" \"l\" \"l\" \"l\" \"l\" \"m\" \"m\" \"m\" \"m\" \"m\" \"m\" \"m\" \"m\" \"m\" \"m\" \"m\" \"m\"\n[91] \"m\" \"n\" \"n\" \"n\" \"n\" \"n\" \"n\" \"n\" \"n\" \"n\" \"n\" \"n\" \"n\" \"n\" \"n\" \"o\" \"o\" \"o\"\n[109] \"o\" \"o\" \"o\" \"o\" \"o\" \"o\" \"o\" \"o\" \"o\" \"o\" \"o\" \"o\" \"p\" \"p\" \"p\" \"p\" \"p\" \"p\"\n[127] \"p\" \"p\" \"p\" \"p\" \"p\" \"p\" \"p\" \"p\" \"p\" \"p\" \"q\" \"q\" \"q\" \"q\" \"q\" \"q\" \"q\" \"q\"\n[145] \"q\" \"q\" \"q\" \"q\" \"q\" \"q\" \"q\" \"q\" \"q\" \"r\" \"r\" \"r\" \"r\" \"r\" \"r\" \"r\" \"r\" \"r\"\n[163] \"r\" \"r\" \"r\" \"r\" \"r\" \"r\" \"r\" \"r\" \"r\" \"s\" \"s\" \"s\" \"s\" \"s\" \"s\" \"s\" \"s\" \"s\"\n[181] \"s\" \"s\" \"s\" \"s\" \"s\" \"s\" \"s\" \"s\" \"s\" \"s\" \"t\" \"t\" \"t\" \"t\" \"t\" \"t\" \"t\" \"t\"\n[199] \"t\" \"t\" \"t\" \"t\" \"t\" \"t\" \"t\" \"t\" \"t\" \"t\" \"t\" \"t\" \"u\" \"u\" \"u\" \"u\" \"u\" \"u\"\n[217] \"u\" \"u\" \"u\" \"u\" \"u\" \"u\" \"u\" \"u\" \"u\" \"u\" \"u\" \"u\" \"u\" \"u\" \"u\" \"v\" \"v\" \"v\"\n[235] \"v\" \"v\" \"v\" \"v\" \"v\" \"v\" \"v\" \"v\" \"v\" \"v\" \"v\" \"v\" \"v\" \"v\" \"v\" \"v\" \"v\" \"v\"\n[253] \"v\" \"w\" \"w\" \"w\" \"w\" \"w\" \"w\" \"w\" \"w\" \"w\" \"w\" \"w\" \"w\" \"w\" \"w\" \"w\" \"w\" \"w\"\n[271] \"w\" \"w\" \"w\" \"w\" \"w\" \"w\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\"\n[289] \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"x\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\"\n[307] \"y\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\" \"y\"\n[325] \"y\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\"\n[343] \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\" \"z\"\n> x13<-rep(c(\"A\",\"B\",\"C\",\"D\"),times=c(4,3,2,1))\n> x13\n[1] \"A\" \"A\" \"A\" \"A\" \"B\" \"B\" \"B\" \"C\" \"C\" \"D\"" } ]
Python program to print a checkboard pattern of n*n using numpy.
Given the value of n, our task is to display the check board pattern for a n x n matrix. Different types of functions to create arrays with initial value are available in numpy . NumPy is the fundamental package for scientific computing in Python. Step 1: input order of the matrix. Step 2: create n*n matrix using zeros((n, n), dtype=int). Step 3: fill with 1 the alternate rows and columns using a slicing technique. Step 4: print the matrix. import numpy as np def checkboardpattern(n): print("Checkerboard pattern:") x = np.zeros((n, n), dtype = int) x[1::2, ::2] = 1 x[::2, 1::2] = 1 # print the pattern for i in range(n): for j in range(n): print(x[i][j], end =" ") print() # Driver code n = int(input("Enter value of n ::>")) checkboardpattern(n) Enter value of n ::>4 Checkerboard pattern: 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0
[ { "code": null, "e": 1151, "s": 1062, "text": "Given the value of n, our task is to display the check board pattern for a n x n matrix." }, { "code": null, "e": 1310, "s": 1151, "text": "Different types of functions to create arrays with initial value are available in numpy . NumPy is the fundamental package for scientific computing in Python." }, { "code": null, "e": 1508, "s": 1310, "text": "Step 1: input order of the matrix.\nStep 2: create n*n matrix using zeros((n, n), dtype=int).\nStep 3: fill with 1 the alternate rows and columns using a slicing technique.\nStep 4: print the matrix.\n" }, { "code": null, "e": 1869, "s": 1508, "text": "import numpy as np \ndef checkboardpattern(n): \n print(\"Checkerboard pattern:\") \n x = np.zeros((n, n), dtype = int) \n x[1::2, ::2] = 1\n x[::2, 1::2] = 1\n # print the pattern \n for i in range(n): \n for j in range(n): \n print(x[i][j], end =\" \") \n print() \n# Driver code \nn = int(input(\"Enter value of n ::>\"))\ncheckboardpattern(n) " }, { "code": null, "e": 1954, "s": 1869, "text": "Enter value of n ::>4\nCheckerboard pattern:\n0 1 0 1 \n1 0 1 0 \n0 1 0 1 \n1 0 1 0 \n" } ]
How to set margins in an Android LinearLayout programmatically?
This example demonstrate about How to set margins in an Android LinearLayout programmatically. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.java <? xml version= "1.0" encoding= "utf-8" ?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android :layout_width= "match_parent" android :id= "@+id/linearLayout" android :layout_height= "match_parent" android :orientation= "vertical" tools :context= ".MainActivity" /> Step 3 − Add the following code to src/MainActivity.java package app.tutorialspoint.com.sample ; import android.os.Bundle ; import android.support.v7.app.AppCompatActivity ; import android.widget.Button ; import android.widget.LinearLayout ; public class MainActivity extends AppCompatActivity { @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; LinearLayout ll = findViewById(R.id. linearLayout ) ; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams. MATCH_PARENT , LinearLayout.LayoutParams. WRAP_CONTENT ) ; layoutParams.setMargins( 30 , 20 , 30 , 0 ) ; Button okButton= new Button( this ) ; okButton.setText( "some text" ) ; ll.addView(okButton , layoutParams) ; } } Step 4 − Add the following code to androidManifest.xml <? xml version= "1.0" encoding= "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package= "app.tutorialspoint.com.sample" > <uses-permission android :name= "android.permission.VIBRATE" /> <application android :allowBackup= "true" android :icon= "@mipmap/ic_launcher" android:label= "@string/app_name" android:roundIcon= "@mipmap/ic_launcher_round" android:supportsRtl= "true" android:theme= "@style/AppTheme" > <activity android:name= ".MainActivity" > <intent-filter> <action android:name= "android.intent.action.MAIN" /> <category android:name= "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
[ { "code": null, "e": 1157, "s": 1062, "text": "This example demonstrate about How to set margins in an Android LinearLayout programmatically." }, { "code": null, "e": 1286, "s": 1157, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1351, "s": 1286, "text": "Step 2 − Add the following code to res/layout/activity_main.java" }, { "code": null, "e": 1716, "s": 1351, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<LinearLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :id= \"@+id/linearLayout\"\n android :layout_height= \"match_parent\"\n android :orientation= \"vertical\"\n tools :context= \".MainActivity\" />" }, { "code": null, "e": 1773, "s": 1716, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2598, "s": 1773, "text": "package app.tutorialspoint.com.sample ;\nimport android.os.Bundle ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.widget.Button ;\nimport android.widget.LinearLayout ;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n LinearLayout ll = findViewById(R.id. linearLayout ) ;\n LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(\n LinearLayout.LayoutParams. MATCH_PARENT ,\n LinearLayout.LayoutParams. WRAP_CONTENT ) ;\n layoutParams.setMargins( 30 , 20 , 30 , 0 ) ;\n Button okButton= new Button( this ) ;\n okButton.setText( \"some text\" ) ;\n ll.addView(okButton , layoutParams) ;\n }\n}" }, { "code": null, "e": 2653, "s": 2598, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3430, "s": 2653, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\n <uses-permission android :name= \"android.permission.VIBRATE\" />\n <application\n android :allowBackup= \"true\"\n android :icon= \"@mipmap/ic_launcher\"\n android:label= \"@string/app_name\"\n android:roundIcon= \"@mipmap/ic_launcher_round\"\n android:supportsRtl= \"true\"\n android:theme= \"@style/AppTheme\" >\n <activity android:name= \".MainActivity\" >\n <intent-filter>\n <action android:name= \"android.intent.action.MAIN\" />\n <category android:name= \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 3777, "s": 3430, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" } ]
How to draw simple animation using p5.js ? - GeeksforGeeks
04 Oct, 2021 Animation is a method in which a collection of images is combined in a specific way and processed then they appear as moving images. Building animations make on-screen objects seem to be alive. In this article, we will learn to make a simple animation of the house in p5.js by using lines, rectangles and ellipses for making the parts of the house. Approach: Make a list to store all the vertices of the house. Declare two variable iter and counter. Set the function setup() in which the size,colour and background of output window ,initiate the value of iter and counter as 1 and initialise the list of vertices. Set the function draw in which add stroke, stroke weight. Make a if condition to check iter within bound if yes increase the counter by 0.05 and thake the ceil value of counter as iter , if no exit from the loo. Function to add vertices of house giving start and end point of line as addVertices(). Now make functions to draw the parts of house: Make Function to draw vertical and horizontal lines in house. Make Function to draw square window Make Function to draw gate. Make Function to draw circular window. Make Function to draw chimney. After all this step now create a switch case to add all the parts of house step by step. Below is the implementation of the above approach: Javascript // List to store all the verticeslet vertices = []; // Variable declaredvar iter;var counter; // Function to set up output windowfunction setup() { // Size of output window createCanvas(600, 600); // Fill the color fill(31); // Background of output window background(31); // Put the value of variables as 1 iter = 1; counter = 1; // Initialize the list of vertices addVertices();} // Set the draw functionfunction draw() { stroke(255); strokeWeight(4); step(); // Condition to check within bound if (iter < 11) { // Increase counter everytime counter += 0.05; // Set the iter variable to the // floor value of counter iter = floor(counter); } else { // If iter increases by 11 then // stop the loop noLoop(); }} // Function to add vertices of house giving// start and end point of linefunction addVertices() { vertices.push(new p5.Vector(100, 300)); vertices.push(new p5.Vector(340, 300)); vertices.push(new p5.Vector(40, 380)); vertices.push(new p5.Vector(160, 380)); vertices.push(new p5.Vector(400, 380)); vertices.push(new p5.Vector(40, 550)); vertices.push(new p5.Vector(160, 550)); vertices.push(new p5.Vector(400, 550));} // Function to draw lines in housefunction drawLine(a, b) { line(vertices[a].x, vertices[a].y, vertices[b].x, vertices[b].y);} // Function to draw gatefunction addGate() { rectMode(CENTER); rect(100, 500, 70, 100);} // Function to draw windowfunction addWindow() { rect(280, 430, 40, 30);} // Function to add circular windowfunction addOculus() { ellipse(100, 340, 20, 20);} // Function to add Chimneyfunction addChimney() { rect(320, 295, 16, 20); ellipse(320, 285, 16, 10);} // Function to draw parts of// house step by stepfunction step() { switch (iter) { case 1: drawLine(5, 6); break; case 2: drawLine(6, 7); break; case 3: drawLine(2, 5); drawLine(3, 6); break; case 4: drawLine(4, 7); break; case 5: drawLine(2, 3); drawLine(3, 4); break; case 6: drawLine(0, 2); drawLine(0, 3); drawLine(1, 4); break; case 7: drawLine(0, 1); break; case 8: addGate(); break; case 9: addWindow(); break; case 10: addOculus(); break; case 11: addChimney(); break; }} Output: saurabh1990aror gabaa406 sweetyty JavaScript-p5.js JavaScript-Questions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24991, "s": 24963, "text": "\n04 Oct, 2021" }, { "code": null, "e": 25185, "s": 24991, "text": "Animation is a method in which a collection of images is combined in a specific way and processed then they appear as moving images. Building animations make on-screen objects seem to be alive." }, { "code": null, "e": 25340, "s": 25185, "text": "In this article, we will learn to make a simple animation of the house in p5.js by using lines, rectangles and ellipses for making the parts of the house." }, { "code": null, "e": 25350, "s": 25340, "text": "Approach:" }, { "code": null, "e": 25402, "s": 25350, "text": "Make a list to store all the vertices of the house." }, { "code": null, "e": 25441, "s": 25402, "text": "Declare two variable iter and counter." }, { "code": null, "e": 25605, "s": 25441, "text": "Set the function setup() in which the size,colour and background of output window ,initiate the value of iter and counter as 1 and initialise the list of vertices." }, { "code": null, "e": 25664, "s": 25605, "text": "Set the function draw in which add stroke, stroke weight." }, { "code": null, "e": 25818, "s": 25664, "text": "Make a if condition to check iter within bound if yes increase the counter by 0.05 and thake the ceil value of counter as iter , if no exit from the loo." }, { "code": null, "e": 25905, "s": 25818, "text": "Function to add vertices of house giving start and end point of line as addVertices()." }, { "code": null, "e": 25952, "s": 25905, "text": "Now make functions to draw the parts of house:" }, { "code": null, "e": 26015, "s": 25952, "text": "Make Function to draw vertical and horizontal lines in house." }, { "code": null, "e": 26052, "s": 26015, "text": "Make Function to draw square window" }, { "code": null, "e": 26080, "s": 26052, "text": "Make Function to draw gate." }, { "code": null, "e": 26119, "s": 26080, "text": "Make Function to draw circular window." }, { "code": null, "e": 26150, "s": 26119, "text": "Make Function to draw chimney." }, { "code": null, "e": 26239, "s": 26150, "text": "After all this step now create a switch case to add all the parts of house step by step." }, { "code": null, "e": 26290, "s": 26239, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26301, "s": 26290, "text": "Javascript" }, { "code": "// List to store all the verticeslet vertices = []; // Variable declaredvar iter;var counter; // Function to set up output windowfunction setup() { // Size of output window createCanvas(600, 600); // Fill the color fill(31); // Background of output window background(31); // Put the value of variables as 1 iter = 1; counter = 1; // Initialize the list of vertices addVertices();} // Set the draw functionfunction draw() { stroke(255); strokeWeight(4); step(); // Condition to check within bound if (iter < 11) { // Increase counter everytime counter += 0.05; // Set the iter variable to the // floor value of counter iter = floor(counter); } else { // If iter increases by 11 then // stop the loop noLoop(); }} // Function to add vertices of house giving// start and end point of linefunction addVertices() { vertices.push(new p5.Vector(100, 300)); vertices.push(new p5.Vector(340, 300)); vertices.push(new p5.Vector(40, 380)); vertices.push(new p5.Vector(160, 380)); vertices.push(new p5.Vector(400, 380)); vertices.push(new p5.Vector(40, 550)); vertices.push(new p5.Vector(160, 550)); vertices.push(new p5.Vector(400, 550));} // Function to draw lines in housefunction drawLine(a, b) { line(vertices[a].x, vertices[a].y, vertices[b].x, vertices[b].y);} // Function to draw gatefunction addGate() { rectMode(CENTER); rect(100, 500, 70, 100);} // Function to draw windowfunction addWindow() { rect(280, 430, 40, 30);} // Function to add circular windowfunction addOculus() { ellipse(100, 340, 20, 20);} // Function to add Chimneyfunction addChimney() { rect(320, 295, 16, 20); ellipse(320, 285, 16, 10);} // Function to draw parts of// house step by stepfunction step() { switch (iter) { case 1: drawLine(5, 6); break; case 2: drawLine(6, 7); break; case 3: drawLine(2, 5); drawLine(3, 6); break; case 4: drawLine(4, 7); break; case 5: drawLine(2, 3); drawLine(3, 4); break; case 6: drawLine(0, 2); drawLine(0, 3); drawLine(1, 4); break; case 7: drawLine(0, 1); break; case 8: addGate(); break; case 9: addWindow(); break; case 10: addOculus(); break; case 11: addChimney(); break; }}", "e": 28934, "s": 26301, "text": null }, { "code": null, "e": 28942, "s": 28934, "text": "Output:" }, { "code": null, "e": 28958, "s": 28942, "text": "saurabh1990aror" }, { "code": null, "e": 28967, "s": 28958, "text": "gabaa406" }, { "code": null, "e": 28976, "s": 28967, "text": "sweetyty" }, { "code": null, "e": 28993, "s": 28976, "text": "JavaScript-p5.js" }, { "code": null, "e": 29014, "s": 28993, "text": "JavaScript-Questions" }, { "code": null, "e": 29025, "s": 29014, "text": "JavaScript" }, { "code": null, "e": 29042, "s": 29025, "text": "Web Technologies" }, { "code": null, "e": 29140, "s": 29042, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29149, "s": 29140, "text": "Comments" }, { "code": null, "e": 29162, "s": 29149, "text": "Old Comments" }, { "code": null, "e": 29223, "s": 29162, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29264, "s": 29223, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29304, "s": 29264, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29358, "s": 29304, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29420, "s": 29358, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 29476, "s": 29420, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29509, "s": 29476, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29571, "s": 29509, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29614, "s": 29571, "text": "How to fetch data from an API in ReactJS ?" } ]
Median of 2 Sorted Arrays of Different Sizes | Practice | GeeksforGeeks
Given two sorted arrays array1 and array2 of size m and n respectively. Find the median of the two sorted arrays. Example 1: Input: m = 3, n = 4 array1[] = {1,5,9} array2[] = {2,3,6,7} Output: 5 Explanation: The middle element for {1,2,3,5,6,7,9} is 5 Example 2: Input: m = 2, n = 4 array1[] = {4,6} array2[] = {1,2,3,5} Output: 3.5 Your Task: The task is to complete the function MedianOfArrays() that takes array1 and array2 as input and returns their median. Can you solve the problem in expected time complexity? Expected Time Complexity: O(min(log n, log m)). Expected Auxiliary Space: O((n+m)/2). Constraints: 0 ≤ m,n ≤ 104 1 ≤ array1[i], array2[i] ≤ 105 0 adarshsharadpandey23in 12 hours vector<int> arr; for(int i=0;i<array1.size();i++) { arr.push_back(array1[i]); } for(int i=0;i<array2.size();i++) { arr.push_back(array2[i]); } sort(arr.begin(),arr.end()); if(arr.size()%2==0) { return ((double)arr[arr.size()/2] + (double)arr[(arr.size()/2)-1])/2; } return arr[(arr.size()/2)]; 0 parmeet4506 days ago static double medianOfArrays(int n, int m, int a[], int b[]) { // Your Code Here ArrayList<Integer> al = new ArrayList<Integer>(); int nc=0; int mc=0; while(nc<n && mc<m){ if(a[nc]>b[mc]){ al.add(b[mc]); mc++; } else{ al.add(a[nc]); nc++; } } if(mc<m){ for(int i=mc;i<m;i++){ al.add(b[i]); } }else if(nc<n){ for(int i=nc;i<n;i++){ al.add(a[i]); } } int index = (n+m)/2; if((n+m)%2 == 1){ return Double.parseDouble(al.get(index)+""); }else{ return (Double.parseDouble(al.get(index)+"")+Double.parseDouble(al.get(index-1)+""))/2; } } 0 rabab0771 week ago Easy 10 line Python Solution: list contains all elements of both arrays, sort it, compute length of this list. list contains all elements of both arrays, sort it, compute length of this list. #If len(z) is even: ---Calculate x = sum of mid term and the term before the mid term. ---The sum of two middle terms divided by 2 will give their average. ---If average is an even number, divide by 2 and return only floor value. ---if average is odd, return decimal value as well, so simply divide by 2 #if len(z) is odd: ---just return the term at mid term (length divide by 2) def MedianOfArrays(self, array1, array2): #code here z = list(array1+array2) z.sort() if len(z)%2==0: x = z[len(z)//2]+z[len(z)//2 - 1] if x%2==0: return x//2 else: return x/2 else: return z[len(z)//2] please upvote! thanks :) 0 anilkumarreddy100620002 weeks ago double MedianOfArrays(vector<int>& array1, vector<int>& array2) { int size1=array1.size(); int size2=array2.size(); int arr[size1+size2]; int i=0,j=0,k=0; while(i<size1 && j<size2){ if(array1[i]<array2[j]){ arr[k++]=array1[i++]; }else{ arr[k++]=array2[j++]; } } while(i<size1) arr[k++]=array1[i++]; while(j<size2) arr[k++]=array2[j++]; int n=size1+size2; if(n%2==0){ double a=(arr[n/2]+arr[n/2-1])/2.0; return a; }else{ return arr[n/2]; } return 0; } 0 mayank180919992 weeks ago double MedianOfArrays(vector<int>& array1, vector<int>& array2) { // Your code goes here vector<int>v; for(int i=0;i<array1.size();i++){ v.push_back(array1[i]); } for(int i=0;i<array2.size();i++){ v.push_back(array2[i]); } sort(v.begin(),v.end()); int n=v.size(); if(n%2==0){ double a=(v[n/2]+v[n/2-1])/2.0; return a; }else{ return v[n/2]; } return 0; } -1 yadavkhushwant7772 weeks ago ---JAVA SOLUTION--- class GFG { static double medianOfArrays(int n, int m, int a[], int b[]) { // Your Code Here double median; int medIndex; int newArr[] = new int[n+m]; for (int i=0; i<n; i++){ newArr[i] = a[i]; } for (int i=0; i<m; i++){ newArr[n+i] = b[i]; } Arrays.sort(newArr); medIndex = newArr.length/2; if(newArr.length%2 == 0){ double temp = newArr[medIndex-1]+newArr[medIndex]; median = temp/2; } else median = newArr[medIndex]; return median; }} 0 rainx3 weeks ago If you try to memorise it, you are doing wrong +2 anandgeeky3 weeks ago JAVA CODE: int[] arr = new int[n + m]; // Merge two array into one array System.arraycopy(a, 0, arr, 0, n); System.arraycopy(b, 0, arr, n, m); // Sort the merged array Arrays.sort(arr); int size = arr.length; // If length of array is even if (size % 2 == 0) { int z = size / 2; int e = arr[z]; int q = arr[z - 1]; double ans =(double) (e + q) / 2; return ans; } // If length if array is odd else { int z = Math.round(size / 2); return arr[z]; } 0 ritishrish1813 weeks ago double MedianOfArrays(vector<int>& array1, vector<int>& array2) { // Your code goes here vector<int> v; for(int i=0;i<array1.size();i++){ v.push_back(array1[i]); } for(int i=0;i<array2.size();i++){ v.push_back(array2[i]); } sort(v.begin(),v.end()); int n=array1.size()+array2.size(); if(n%2==0){ double a=((double)v[n/2]+(double)v[n/2-1])/2; return a; } else{ double a=(double)v[n/2]; return a; } 0 ritishrish181 This comment was deleted. 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": 352, "s": 238, "text": "Given two sorted arrays array1 and array2 of size m and n respectively. Find the median of the two sorted arrays." }, { "code": null, "e": 363, "s": 352, "text": "Example 1:" }, { "code": null, "e": 491, "s": 363, "text": "Input:\nm = 3, n = 4\narray1[] = {1,5,9}\narray2[] = {2,3,6,7}\nOutput: 5\nExplanation: The middle element for\n{1,2,3,5,6,7,9} is 5\n" }, { "code": null, "e": 502, "s": 491, "text": "Example 2:" }, { "code": null, "e": 572, "s": 502, "text": "Input:\nm = 2, n = 4\narray1[] = {4,6}\narray2[] = {1,2,3,5}\nOutput: 3.5" }, { "code": null, "e": 758, "s": 572, "text": "Your Task:\nThe task is to complete the function MedianOfArrays() that takes array1 and array2 as input and returns their median. \n\nCan you solve the problem in expected time complexity?" }, { "code": null, "e": 844, "s": 758, "text": "Expected Time Complexity: O(min(log n, log m)).\nExpected Auxiliary Space: O((n+m)/2)." }, { "code": null, "e": 903, "s": 844, "text": "Constraints: \n0 ≤ m,n ≤ 104\n1 ≤ array1[i], array2[i] ≤ 105" }, { "code": null, "e": 905, "s": 903, "text": "0" }, { "code": null, "e": 937, "s": 905, "text": "adarshsharadpandey23in 12 hours" }, { "code": null, "e": 1355, "s": 937, "text": "vector<int> arr;\n for(int i=0;i<array1.size();i++)\n {\n arr.push_back(array1[i]);\n }\n for(int i=0;i<array2.size();i++)\n {\n arr.push_back(array2[i]);\n }\n sort(arr.begin(),arr.end());\n if(arr.size()%2==0)\n {\n return ((double)arr[arr.size()/2] + (double)arr[(arr.size()/2)-1])/2;\n }\n return arr[(arr.size()/2)];" }, { "code": null, "e": 1357, "s": 1355, "text": "0" }, { "code": null, "e": 1378, "s": 1357, "text": "parmeet4506 days ago" }, { "code": null, "e": 2177, "s": 1378, "text": "static double medianOfArrays(int n, int m, int a[], int b[]) { // Your Code Here ArrayList<Integer> al = new ArrayList<Integer>(); int nc=0; int mc=0; while(nc<n && mc<m){ if(a[nc]>b[mc]){ al.add(b[mc]); mc++; } else{ al.add(a[nc]); nc++; } } if(mc<m){ for(int i=mc;i<m;i++){ al.add(b[i]); } }else if(nc<n){ for(int i=nc;i<n;i++){ al.add(a[i]); } } int index = (n+m)/2; if((n+m)%2 == 1){ return Double.parseDouble(al.get(index)+\"\"); }else{ return (Double.parseDouble(al.get(index)+\"\")+Double.parseDouble(al.get(index-1)+\"\"))/2; } }" }, { "code": null, "e": 2179, "s": 2177, "text": "0" }, { "code": null, "e": 2198, "s": 2179, "text": "rabab0771 week ago" }, { "code": null, "e": 2228, "s": 2198, "text": "Easy 10 line Python Solution:" }, { "code": null, "e": 2309, "s": 2228, "text": "list contains all elements of both arrays, sort it, compute length of this list." }, { "code": null, "e": 2390, "s": 2309, "text": "list contains all elements of both arrays, sort it, compute length of this list." }, { "code": null, "e": 2410, "s": 2390, "text": "#If len(z) is even:" }, { "code": null, "e": 2477, "s": 2410, "text": "---Calculate x = sum of mid term and the term before the mid term." }, { "code": null, "e": 2546, "s": 2477, "text": "---The sum of two middle terms divided by 2 will give their average." }, { "code": null, "e": 2620, "s": 2546, "text": "---If average is an even number, divide by 2 and return only floor value." }, { "code": null, "e": 2694, "s": 2620, "text": "---if average is odd, return decimal value as well, so simply divide by 2" }, { "code": null, "e": 2713, "s": 2694, "text": "#if len(z) is odd:" }, { "code": null, "e": 3119, "s": 2713, "text": "---just return the term at mid term (length divide by 2) def MedianOfArrays(self, array1, array2): #code here z = list(array1+array2) z.sort() if len(z)%2==0: x = z[len(z)//2]+z[len(z)//2 - 1] if x%2==0: return x//2 else: return x/2 else: return z[len(z)//2]" }, { "code": null, "e": 3144, "s": 3119, "text": "please upvote! thanks :)" }, { "code": null, "e": 3146, "s": 3144, "text": "0" }, { "code": null, "e": 3180, "s": 3146, "text": "anilkumarreddy100620002 weeks ago" }, { "code": null, "e": 3805, "s": 3180, "text": "double MedianOfArrays(vector<int>& array1, vector<int>& array2) { int size1=array1.size(); int size2=array2.size(); int arr[size1+size2]; int i=0,j=0,k=0; while(i<size1 && j<size2){ if(array1[i]<array2[j]){ arr[k++]=array1[i++]; }else{ arr[k++]=array2[j++]; } } while(i<size1) arr[k++]=array1[i++]; while(j<size2) arr[k++]=array2[j++]; int n=size1+size2; if(n%2==0){ double a=(arr[n/2]+arr[n/2-1])/2.0; return a; }else{ return arr[n/2]; } return 0; }" }, { "code": null, "e": 3807, "s": 3805, "text": "0" }, { "code": null, "e": 3833, "s": 3807, "text": "mayank180919992 weeks ago" }, { "code": null, "e": 4362, "s": 3833, "text": " double MedianOfArrays(vector<int>& array1, vector<int>& array2)\n {\n // Your code goes here\n vector<int>v;\n for(int i=0;i<array1.size();i++){\n v.push_back(array1[i]);\n }\n for(int i=0;i<array2.size();i++){\n v.push_back(array2[i]);\n }\n sort(v.begin(),v.end());\n int n=v.size();\n if(n%2==0){\n double a=(v[n/2]+v[n/2-1])/2.0;\n return a;\n }else{\n return v[n/2];\n }\n return 0;\n }" }, { "code": null, "e": 4365, "s": 4362, "text": "-1" }, { "code": null, "e": 4394, "s": 4365, "text": "yadavkhushwant7772 weeks ago" }, { "code": null, "e": 4414, "s": 4394, "text": "---JAVA SOLUTION---" }, { "code": null, "e": 4733, "s": 4416, "text": "class GFG { static double medianOfArrays(int n, int m, int a[], int b[]) { // Your Code Here double median; int medIndex; int newArr[] = new int[n+m]; for (int i=0; i<n; i++){ newArr[i] = a[i]; } for (int i=0; i<m; i++){ newArr[n+i] = b[i]; }" }, { "code": null, "e": 4988, "s": 4733, "text": " Arrays.sort(newArr); medIndex = newArr.length/2; if(newArr.length%2 == 0){ double temp = newArr[medIndex-1]+newArr[medIndex]; median = temp/2; } else median = newArr[medIndex]; return median; }}" }, { "code": null, "e": 4990, "s": 4988, "text": "0" }, { "code": null, "e": 5007, "s": 4990, "text": "rainx3 weeks ago" }, { "code": null, "e": 5054, "s": 5007, "text": "If you try to memorise it, you are doing wrong" }, { "code": null, "e": 5057, "s": 5054, "text": "+2" }, { "code": null, "e": 5079, "s": 5057, "text": "anandgeeky3 weeks ago" }, { "code": null, "e": 5090, "s": 5079, "text": "JAVA CODE:" }, { "code": null, "e": 5706, "s": 5092, "text": " int[] arr = new int[n + m]; // Merge two array into one array System.arraycopy(a, 0, arr, 0, n); System.arraycopy(b, 0, arr, n, m); // Sort the merged array Arrays.sort(arr); int size = arr.length; // If length of array is even if (size % 2 == 0) { int z = size / 2; int e = arr[z]; int q = arr[z - 1]; double ans =(double) (e + q) / 2; return ans; } // If length if array is odd else { int z = Math.round(size / 2); return arr[z]; }" }, { "code": null, "e": 5708, "s": 5706, "text": "0" }, { "code": null, "e": 5733, "s": 5708, "text": "ritishrish1813 weeks ago" }, { "code": null, "e": 6304, "s": 5733, "text": " double MedianOfArrays(vector<int>& array1, vector<int>& array2)\n {\n // Your code goes here\n vector<int> v;\n for(int i=0;i<array1.size();i++){\n v.push_back(array1[i]);\n }\n for(int i=0;i<array2.size();i++){\n v.push_back(array2[i]);\n }\n sort(v.begin(),v.end());\n int n=array1.size()+array2.size();\n if(n%2==0){\n double a=((double)v[n/2]+(double)v[n/2-1])/2;\n return a;\n }\n else{\n double a=(double)v[n/2];\n return a;\n }" }, { "code": null, "e": 6306, "s": 6304, "text": "0" }, { "code": null, "e": 6320, "s": 6306, "text": "ritishrish181" }, { "code": null, "e": 6346, "s": 6320, "text": "This comment was deleted." }, { "code": null, "e": 6492, "s": 6346, "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": 6528, "s": 6492, "text": " Login to access your submissions. " }, { "code": null, "e": 6538, "s": 6528, "text": "\nProblem\n" }, { "code": null, "e": 6548, "s": 6538, "text": "\nContest\n" }, { "code": null, "e": 6611, "s": 6548, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6759, "s": 6611, "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": 6967, "s": 6759, "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": 7073, "s": 6967, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C++ Program to Implement Selection Sort
In the selection sort technique, the list is divided into two parts. In one part all elements are sorted and in another part the items are unsorted. At first we take the maximum or minimum data from the array. After getting the data (say minimum) we place it at the beginning of the list by replacing the data of first place with the minimum data. After performing the array is getting smaller. Thus this sorting technique is done. Time Complexity: O(n2) Time Complexity: O(n2) Space Complexity: O(1) Space Complexity: O(1) Input − The unsorted list: 5 9 7 23 78 20 Output − Array after Sorting: 5 7 9 20 23 78 Input: An array of data, and the total number in the array Output: The sorted Array Begin for i := 0 to size-2 do //find minimum from ith location to size iMin := i; for j:= i+1 to size – 1 do if array[j] < array[iMin] then iMin := j done swap array[i] with array[iMin]. done End #include<iostream> using namespace std; void swapping(int &a, int &b) { //swap the content of a and b int temp; temp = a; a = b; b = temp; } void display(int *array, int size) { for(int i = 0; i<size; i++) cout << array[i] << " "; cout << endl; } void selectionSort(int *array, int size) { int i, j, imin; for(i = 0; i<size-1; i++) { imin = i; //get index of minimum data for(j = i+1; j<size; j++) if(array[j] < array[imin]) imin = j; //placing in correct position swap(array[i], array[imin]); } } int main() { int n; cout << "Enter the number of elements: "; cin >> n; int arr[n]; //create an array with given number of elements cout << "Enter elements:" << endl; for(int i = 0; i<n; i++) { cin >> arr[i]; } cout << "Array before Sorting: "; display(arr, n); selectionSort(arr, n); cout << "Array after Sorting: "; display(arr, n); } Enter the number of elements: 6 Enter elements: 5 9 7 23 78 20 Array before Sorting: 5 9 7 23 78 20 Array after Sorting: 5 7 9 20 23 78
[ { "code": null, "e": 1494, "s": 1062, "text": "In the selection sort technique, the list is divided into two parts. In one part all elements are sorted and in another part the items are unsorted. At first we take the maximum or minimum data from the array. After getting the data (say minimum) we place it at the beginning of the list by replacing the data of first place with the minimum data. After performing the array is getting smaller. Thus this sorting technique is done." }, { "code": null, "e": 1517, "s": 1494, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 1540, "s": 1517, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 1563, "s": 1540, "text": "Space Complexity: O(1)" }, { "code": null, "e": 1586, "s": 1563, "text": "Space Complexity: O(1)" }, { "code": null, "e": 1673, "s": 1586, "text": "Input − The unsorted list: 5 9 7 23 78 20\nOutput − Array after Sorting: 5 7 9 20 23 78" }, { "code": null, "e": 1732, "s": 1673, "text": "Input: An array of data, and the total number in the array" }, { "code": null, "e": 1757, "s": 1732, "text": "Output: The sorted Array" }, { "code": null, "e": 2004, "s": 1757, "text": "Begin\n for i := 0 to size-2 do //find minimum from ith location to size\n iMin := i;\n for j:= i+1 to size – 1 do\n if array[j] < array[iMin] then\n iMin := j\n done\n swap array[i] with array[iMin].\n done\nEnd" }, { "code": null, "e": 2985, "s": 2004, "text": "#include<iostream>\nusing namespace std;\nvoid swapping(int &a, int &b) { //swap the content of a and b\n int temp;\n temp = a;\n a = b;\n b = temp;\n}\nvoid display(int *array, int size) {\n for(int i = 0; i<size; i++)\n cout << array[i] << \" \";\n cout << endl;\n}\nvoid selectionSort(int *array, int size) {\n int i, j, imin;\n for(i = 0; i<size-1; i++) {\n imin = i; //get index of minimum data\n for(j = i+1; j<size; j++)\n if(array[j] < array[imin])\n imin = j;\n //placing in correct position\n swap(array[i], array[imin]);\n }\n}\nint main() {\n int n;\n cout << \"Enter the number of elements: \";\n cin >> n;\n int arr[n]; //create an array with given number of elements\n cout << \"Enter elements:\" << endl;\n for(int i = 0; i<n; i++) {\n cin >> arr[i];\n }\n cout << \"Array before Sorting: \";\n display(arr, n);\n selectionSort(arr, n);\n cout << \"Array after Sorting: \";\n display(arr, n);\n}" }, { "code": null, "e": 3121, "s": 2985, "text": "Enter the number of elements: 6\nEnter elements:\n5 9 7 23 78 20\nArray before Sorting: 5 9 7 23 78 20\nArray after Sorting: 5 7 9 20 23 78" } ]
How to specify the file path in a tkinter filedialog?
Tkinter offers several built-in functions and class library methods to build components and user-actionable items of an application. filedialog is one of the tkinter modules that provides classes and library functions to create file/directory selection windows. You can use filedialog where you need to ask the user to browse a file or a directory from the system. You can also specify the location of the directory from where a particular file should be picked up. To display the filedialog that starts from a particular location, use the initialdir = <location> argument in the static factory function askopenfilename(initialdir=<location>). This function creates a modal-like dialogbox and waits for the user's selection and returns the value of the selected file to the caller. Let us create an application which asks the user to select a file from the system directory. # Import required libraries from tkinter import * from tkinter import filedialog from tkinter import ttk # Create an instance of tkinter window win = Tk() win.geometry("700x350") # Create an instance of style class style=ttk.Style(win) def open_win_diag(): # Create a dialog box file=filedialog.askopenfilename(initialdir="C:/") f=open(win.file, 'r') # Create a label widget label=Label(win, text= "Click the button to browse the file", font='Arial 15 bold') label.pack(pady= 20) # Create a button to open the dialog box button=ttk.Button(win, text="Open", command=open_win_diag) button.pack(pady=5) win.mainloop() Running the above code will display a window that contains two widgets. The button widget triggers the file dialog box, asking the user to browse the file from the system. We have specified "initialdir=C:/" in the askopenfilename() function. Hence, it opens the C Drive as the initial directory.
[ { "code": null, "e": 1427, "s": 1062, "text": "Tkinter offers several built-in functions and class library methods to build components and user-actionable items of an application. filedialog is one of the tkinter modules that provides classes and library functions to create file/directory selection windows. You can use filedialog where you need to ask the user to browse a file or a directory from the system." }, { "code": null, "e": 1844, "s": 1427, "text": "You can also specify the location of the directory from where a particular file should be picked up. To display the filedialog that starts from a particular location, use the initialdir = <location> argument in the static factory function askopenfilename(initialdir=<location>). This function creates a modal-like dialogbox and waits for the user's selection and returns the value of the selected file to the caller." }, { "code": null, "e": 1937, "s": 1844, "text": "Let us create an application which asks the user to select a file from the system directory." }, { "code": null, "e": 2567, "s": 1937, "text": "# Import required libraries\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import ttk\n\n# Create an instance of tkinter window\nwin = Tk()\nwin.geometry(\"700x350\")\n\n# Create an instance of style class\nstyle=ttk.Style(win)\n\ndef open_win_diag():\n # Create a dialog box\n file=filedialog.askopenfilename(initialdir=\"C:/\")\n f=open(win.file, 'r')\n\n# Create a label widget\nlabel=Label(win, text= \"Click the button to browse the file\", font='Arial 15 bold')\nlabel.pack(pady= 20)\n\n# Create a button to open the dialog box\nbutton=ttk.Button(win, text=\"Open\", command=open_win_diag)\nbutton.pack(pady=5)\n\nwin.mainloop()" }, { "code": null, "e": 2639, "s": 2567, "text": "Running the above code will display a window that contains two widgets." }, { "code": null, "e": 2739, "s": 2639, "text": "The button widget triggers the file dialog box, asking the user to browse the file from the system." }, { "code": null, "e": 2863, "s": 2739, "text": "We have specified \"initialdir=C:/\" in the askopenfilename() function. Hence, it opens the C Drive as the initial directory." } ]
How to Generate Music using a LSTM Neural Network in Keras | by Sigurður Skúli | Towards Data Science
Neural networks are being used to improve all aspects of our lives. They provide us with recommendations for items we want to purchase, generate text based on the style of an author and can even be used to change the art style of an image. In recent years, there have been a number of tutorials on how to generate text using neural networks but a lack of tutorials on how to create music. In this article we will go through how to create music using a recurrent neural network in Python using the Keras library. For the impatient, there is a link to the Github repository at the end of the tutorial. Before we go into the details of the implementation there is some terminology that we must clarify. A recurrent neural network is a class of artificial neural networks that make use of sequential information. They are called recurrent because they perform the same function for every single element of a sequence, with the result being dependent on previous computations. Whereas outputs are independent of previous computations in traditional neural networks. In this tutorial we will use a Long Short-Term Memory (LSTM) network. They are a type of Recurrent Neural Network that can efficiently learn via gradient descent. Using a gating mechanism, LSTMs are able to recognise and encode long-term patterns. LSTMs are extremely useful to solve problems where the network has to remember information for a long period of time as is the case in music and text generation. Music21 is a Python toolkit used for computer-aided musicology. It allows us to teach the fundamentals of music theory, generate music examples and study music. The toolkit provides a simple interface to acquire the musical notation of MIDI files. Additionally, it allows us to create Note and Chord objects so that we can make our own MIDI files easily. In this tutorial we will use Music21 to extract the contents of our dataset and to take the output of the neural network and translate it to musical notation. Keras is a high-level neural networks API that simplifies interactions with Tensorflow. It was developed with a focus on enabling fast experimentation. In this tutorial we will use the Keras library to create and train the LSTM model. Once the model is trained we will use it to generate the musical notation for our music. In this section we will cover how we gathered data for our model, how we prepared it so that it could be used in a LSTM model and the architecture of our model. In our Github repository we used piano music, mostly consisting of music from Final Fantasy soundtracks. We picked Final Fantasy music due to the very distinct and beautiful melodies that the majority of the pieces have and the sheer amount of pieces that exist. But any set of MIDI files consisting of a single instrument would work for our purposes. The first step to implementing the neural network is to examine the data we will be working with. Below we can see an excerpt from a midi file that has been read using Music21: ...<music21.note.Note F><music21.chord.Chord A2 E3><music21.chord.Chord A2 E3><music21.note.Note E><music21.chord.Chord B-2 F3><music21.note.Note F><music21.note.Note G><music21.note.Note D><music21.chord.Chord B-2 F3><music21.note.Note F><music21.chord.Chord B-2 F3><music21.note.Note E><music21.chord.Chord B-2 F3><music21.note.Note D><music21.chord.Chord B-2 F3><music21.note.Note E><music21.chord.Chord A2 E3>... The data splits into two object types: Notes and Chords. Note objects contain information about the pitch, octave, and offset of the Note. Pitch refers to the frequency of the sound, or how high or low it is and is represented with the letters [A, B, C, D, E, F, G], with A being the highest and G being the lowest. Octave refers to which set of pitches you use on a piano. Offset refers to where the note is located in the piece. And Chord objects are essentially a container for a set of notes that are played at the same time. Now we can see that to generate music accurately our neural network will have to be able to predict which note or chord is next. That means that our prediction array will have to contain every note and chord object that we encounter in our training set. In the training set on the Github page the total number of different notes and chords was 352. That seems like a lot of possible output predictions for the network to handle, but a LSTM network can easily handle it. Next we have to worry about where we want to put the notes. As most people that have listened to music have noticed, notes usually have varying intervals between them. You can have many notes in quick succession and then followed by a rest period where no note is played for a short while. Below we have another excerpt from a midi file that has been read using Music21, only this time we have added the offset of the object behind it. This allows us to see the interval between each note and chord. ...<music21.note.Note B> 72.0<music21.chord.Chord E3 A3> 72.0<music21.note.Note A> 72.5<music21.chord.Chord E3 A3> 72.5<music21.note.Note E> 73.0<music21.chord.Chord E3 A3> 73.0<music21.chord.Chord E3 A3> 73.5<music21.note.Note E-> 74.0<music21.chord.Chord F3 A3> 74.0<music21.chord.Chord F3 A3> 74.5<music21.chord.Chord F3 A3> 75.0<music21.chord.Chord F3 A3> 75.5<music21.chord.Chord E3 A3> 76.0<music21.chord.Chord E3 A3> 76.5<music21.chord.Chord E3 A3> 77.0<music21.chord.Chord E3 A3> 77.5<music21.chord.Chord F3 A3> 78.0<music21.chord.Chord F3 A3> 78.5<music21.chord.Chord F3 A3> 79.0... As can be seen from this excerpt and most of the dataset, the most common interval between notes in the midi files is 0.5. Therefore, we can simplify the data and model by disregarding the varying offsets in the list of possible outputs. It will not affect the melodies of the music generated by the network too severely. So we will ignore the offset in this tutorial and keep our list of possible outputs at 352. Now that we have examined the data and determined that the features that we want to use are the notes and chords as the input and output of our LSTM network it is time to prepare the data for the network. First, we will load the data into an array as can be seen in the code snippet below: from music21 import converter, instrument, note, chordnotes = []for file in glob.glob("midi_songs/*.mid"): midi = converter.parse(file) notes_to_parse = None parts = instrument.partitionByInstrument(midi) if parts: # file has instrument parts notes_to_parse = parts.parts[0].recurse() else: # file has notes in a flat structure notes_to_parse = midi.flat.notes for element in notes_to_parse: if isinstance(element, note.Note): notes.append(str(element.pitch)) elif isinstance(element, chord.Chord): notes.append('.'.join(str(n) for n in element.normalOrder)) We start by loading each file into a Music21 stream object using the converter.parse(file) function. Using that stream object we get a list of all the notes and chords in the file. We append the pitch of every note object using its string notation since the most significant parts of the note can be recreated using the string notation of the pitch. And we append every chord by encoding the id of every note in the chord together into a single string, with each note being separated by a dot. These encodings allows us to easily decode the output generated by the network into the correct notes and chords. Now that we have put all the notes and chords into a sequential list we can create the sequences that will serve as the input of our network. First, we will create a mapping function to map from string-based categorical data to integer-based numerical data. This is done because neural network perform much better with integer-based numerical data than string-based categorical data. An example of a categorical to numerical transformation can be seen in Figure 1. Next, we have to create input sequences for the network and their respective outputs. The output for each input sequence will be the first note or chord that comes after the sequence of notes in the input sequence in our list of notes. sequence_length = 100# get all pitch namespitchnames = sorted(set(item for item in notes))# create a dictionary to map pitches to integersnote_to_int = dict((note, number) for number, note in enumerate(pitchnames))network_input = []network_output = []# create input sequences and the corresponding outputsfor i in range(0, len(notes) - sequence_length, 1): sequence_in = notes[i:i + sequence_length] sequence_out = notes[i + sequence_length] network_input.append([note_to_int[char] for char in sequence_in]) network_output.append(note_to_int[sequence_out])n_patterns = len(network_input)# reshape the input into a format compatible with LSTM layersnetwork_input = numpy.reshape(network_input, (n_patterns, sequence_length, 1))# normalize inputnetwork_input = network_input / float(n_vocab)network_output = np_utils.to_categorical(network_output) In our code example, we have put the length of each sequence to be 100 notes/chords. This means that to predict the next note in the sequence the network has the previous 100 notes to help make the prediction. I highly recommend training the network using different sequence lengths to see the impact different sequence lengths can have on the music generated by the network. The final step in preparing the data for the network is to normalise the input and one-hot encode the output. Finally we get to designing the model architecture. In our model we use four different types of layers: LSTM layers is a Recurrent Neural Net layer that takes a sequence as an input and can return either sequences (return_sequences=True) or a matrix. Dropout layers are a regularisation technique that consists of setting a fraction of input units to 0 at each update during the training to prevent overfitting. The fraction is determined by the parameter used with the layer. Dense layers or fully connected layers is a fully connected neural network layer where each input node is connected to each output node. The Activation layer determines what activation function our neural network will use to calculate the output of a node. model = Sequential() model.add(LSTM( 256, input_shape=(network_input.shape[1], network_input.shape[2]), return_sequences=True )) model.add(Dropout(0.3)) model.add(LSTM(512, return_sequences=True)) model.add(Dropout(0.3)) model.add(LSTM(256)) model.add(Dense(256)) model.add(Dropout(0.3)) model.add(Dense(n_vocab)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop') Now that we have some information about the different layers we will be using it is time to add them to the network model. For each LSTM, Dense, and Activation layer the first parameter is how many nodes the layer should have. For the Dropout layer the first parameter is the fraction of input units that should be dropped during training. For the first layer we have to provide a unique parameter called input_shape. The purpose of the parameter is to inform the network of the shape of the data it will be training. The last layer should always contain the same amount of nodes as the number different outputs our system has. This assures that the output of the network will map directly to our classes. For this tutorial we will use a simple network consisting of three LSTM layers, three Dropout layers, two Dense layers and one activation layer. I would recommend playing around with the structure of the network to see if you can improve the quality of the predictions. To calculate the loss for each iteration of the training we will be using categorical cross entropy since each of our outputs only belongs to a single class and we have more than two classes to work with. And to optimise our network we will use a RMSprop optimizer as it is usually a very good choice for recurrent neural networks. filepath = "weights-improvement-{epoch:02d}-{loss:.4f}-bigger.hdf5" checkpoint = ModelCheckpoint( filepath, monitor='loss', verbose=0, save_best_only=True, mode='min') callbacks_list = [checkpoint] model.fit(network_input, network_output, epochs=200, batch_size=64, callbacks=callbacks_list) Once we have determined the architecture of our network the time has come to start the training. The model.fit() function in Keras is used to train the network. The first parameter is the list of input sequences that we prepared earlier and the second is a list of their respective outputs. In our tutorial we are going to train the network for 200 epochs (iterations), with each batch that is propagated through the network containing 64 samples. To make sure that we can stop the training at any point in time without losing all of our hard work, we will use model checkpoints. Model checkpoints provide us with a way to save the weights of the network nodes to a file after every epoch. This allows us to stop running the neural network once we are satisfied with the loss value without having to worry about losing the weights. Otherwise we would have to wait until the network has finished going through all 200 epochs before we could get the chance to save the weights to a file. Now that we have finished training the network it is time to have some fun with the network we have spent hours training. To be able to use the neural network to generate music you will have to put it into the same state as before. For simplicity we will reuse code from the training section to prepare the data and set up the network model in the same way as before. Except, that instead of training the network we load the weights that we saved during the training section into the model. model = Sequential()model.add(LSTM( 512, input_shape=(network_input.shape[1], network_input.shape[2]), return_sequences=True))model.add(Dropout(0.3))model.add(LSTM(512, return_sequences=True))model.add(Dropout(0.3))model.add(LSTM(512))model.add(Dense(256))model.add(Dropout(0.3))model.add(Dense(n_vocab))model.add(Activation('softmax'))model.compile(loss='categorical_crossentropy', optimizer='rmsprop')# Load the weights to each nodemodel.load_weights('weights.hdf5') Now we can use the trained model to start generating notes. Since we have a full list of note sequences at our disposal we will pick a random index in the list as our starting point, this allows us to rerun the generation code without changing anything and get different results every time. However, If you wish to control the starting point simply replace the random function with a command line argument. Here we also need to create a mapping function to decode the output of the network. This function will map from numerical data to categorical data (from integers to notes). start = numpy.random.randint(0, len(network_input)-1)int_to_note = dict((number, note) for number, note in enumerate(pitchnames))pattern = network_input[start]prediction_output = []# generate 500 notesfor note_index in range(500): prediction_input = numpy.reshape(pattern, (1, len(pattern), 1)) prediction_input = prediction_input / float(n_vocab) prediction = model.predict(prediction_input, verbose=0) index = numpy.argmax(prediction) result = int_to_note[index] prediction_output.append(result) pattern.append(index) pattern = pattern[1:len(pattern)] We chose to generate 500 notes using the network since that is roughly two minutes of music and gives the network plenty of space to create a melody. For each note that we want to generate we have to submit a sequence to the network. The first sequence we submit is the sequence of notes at the starting index. For every subsequent sequence that we use as input, we will remove the first note of the sequence and insert the output of the previous iteration at the end of the sequence as can be seen in Figure 2. To determine the most likely prediction from the output from the network, we extract the index of the highest value. The value at index X in the output array correspond to the probability that X is the next note. Figure 3 helps explain this. Then we collect all the outputs from the network into a single array. Now that we have all the encoded representations of the notes and chords in an array we can start decoding them and creating an array of Note and Chord objects. First we have to determine whether the output we are decoding is a Note or a Chord. If the pattern is a Chord, we have to split the string up into an array of notes. Then we loop through the string representation of each note and create a Note object for each of them. Then we can create a Chord object containing each of these notes. If the pattern is a Note, we create a Note object using the string representation of the pitch contained in the pattern. At the end of each iteration we increase the offset by 0.5 (as we decided in a previous section) and append the Note/Chord object created to a list. offset = 0output_notes = []# create note and chord objects based on the values generated by the modelfor pattern in prediction_output: # pattern is a chord if ('.' in pattern) or pattern.isdigit(): notes_in_chord = pattern.split('.') notes = [] for current_note in notes_in_chord: new_note = note.Note(int(current_note)) new_note.storedInstrument = instrument.Piano() notes.append(new_note) new_chord = chord.Chord(notes) new_chord.offset = offset output_notes.append(new_chord) # pattern is a note else: new_note = note.Note(pattern) new_note.offset = offset new_note.storedInstrument = instrument.Piano() output_notes.append(new_note) # increase offset each iteration so that notes do not stack offset += 0.5 Now that we have a list of Notes and Chords generated by the network we can create a Music21 Stream object using the list as a parameter. Then finally to create the MIDI file to contain the music generated by the network we use the write function in the Music21 toolkit to write the stream to a file. midi_stream = stream.Stream(output_notes)midi_stream.write('midi', fp='test_output.mid') Now it is time to marvel at the results. Figure 4 contains sheet music representation of music that was generated using the LSTM network. At a quick glance we can see that there is some structure to it. This is especially obvious in the third to last line on the second page. People that are knowledgeable about music and can read musical notation can see that there are some weird notes strewn about the sheet. This is a result of the neural network not being able to create perfect melodies. With our current implementation there will always be some false notes and to be able to achieve better results we will need a bigger network. The results from this relatively shallow network are still really impressive as can be heard from the example music in Embed 1. For those interested, the sheet music in Figure 4 represents the musical notation of NeuralNet Music 5. We have achieved remarkable results and beautiful melodies by using a simple LSTM network and 352 classes. However, there are areas that can be improved. First, the implementation we have at the moment does not support varying duration of notes and different offsets between notes. To achieve that we could add more classes for each different duration and add rest classes that represent the rest period between notes. To achieve satisfying results with more classes added we would also have to increase the depth of the LSTM network, which would require a significantly more powerful computer. It took the laptop I use at home approximately twenty hours to train the network as it is now. Second, add beginnings and endings to pieces. As the network is now there is no distinction between pieces, that is to say the network does not know where one piece ends and another one begins. This would allow the network to generate a piece from start to finish instead of ending the generated piece abruptly as it does now. Third, add a method to handle unknown notes. As it is now the network would enter a fail state if it encounters a note that it does not know. A possible method to solve that issue would be to find the note or chord that is most similar to the unknown note. Finally, adding more instruments to the dataset. As it is now, the network only supports pieces that only have a single instrument. It would be interesting to see if it could be expanded to support a whole orchestra. During this tutorial we have shown how to create a LSTM neural network to generate music. While the results may not be perfect, they are pretty impressive nonetheless and shows us that neural networks can create music and could potentially be used to help create more complex musical pieces. Check out the Github repository for the tutorial here
[ { "code": null, "e": 683, "s": 171, "text": "Neural networks are being used to improve all aspects of our lives. They provide us with recommendations for items we want to purchase, generate text based on the style of an author and can even be used to change the art style of an image. In recent years, there have been a number of tutorials on how to generate text using neural networks but a lack of tutorials on how to create music. In this article we will go through how to create music using a recurrent neural network in Python using the Keras library." }, { "code": null, "e": 771, "s": 683, "text": "For the impatient, there is a link to the Github repository at the end of the tutorial." }, { "code": null, "e": 871, "s": 771, "text": "Before we go into the details of the implementation there is some terminology that we must clarify." }, { "code": null, "e": 1232, "s": 871, "text": "A recurrent neural network is a class of artificial neural networks that make use of sequential information. They are called recurrent because they perform the same function for every single element of a sequence, with the result being dependent on previous computations. Whereas outputs are independent of previous computations in traditional neural networks." }, { "code": null, "e": 1642, "s": 1232, "text": "In this tutorial we will use a Long Short-Term Memory (LSTM) network. They are a type of Recurrent Neural Network that can efficiently learn via gradient descent. Using a gating mechanism, LSTMs are able to recognise and encode long-term patterns. LSTMs are extremely useful to solve problems where the network has to remember information for a long period of time as is the case in music and text generation." }, { "code": null, "e": 1997, "s": 1642, "text": "Music21 is a Python toolkit used for computer-aided musicology. It allows us to teach the fundamentals of music theory, generate music examples and study music. The toolkit provides a simple interface to acquire the musical notation of MIDI files. Additionally, it allows us to create Note and Chord objects so that we can make our own MIDI files easily." }, { "code": null, "e": 2156, "s": 1997, "text": "In this tutorial we will use Music21 to extract the contents of our dataset and to take the output of the neural network and translate it to musical notation." }, { "code": null, "e": 2308, "s": 2156, "text": "Keras is a high-level neural networks API that simplifies interactions with Tensorflow. It was developed with a focus on enabling fast experimentation." }, { "code": null, "e": 2480, "s": 2308, "text": "In this tutorial we will use the Keras library to create and train the LSTM model. Once the model is trained we will use it to generate the musical notation for our music." }, { "code": null, "e": 2641, "s": 2480, "text": "In this section we will cover how we gathered data for our model, how we prepared it so that it could be used in a LSTM model and the architecture of our model." }, { "code": null, "e": 2993, "s": 2641, "text": "In our Github repository we used piano music, mostly consisting of music from Final Fantasy soundtracks. We picked Final Fantasy music due to the very distinct and beautiful melodies that the majority of the pieces have and the sheer amount of pieces that exist. But any set of MIDI files consisting of a single instrument would work for our purposes." }, { "code": null, "e": 3091, "s": 2993, "text": "The first step to implementing the neural network is to examine the data we will be working with." }, { "code": null, "e": 3170, "s": 3091, "text": "Below we can see an excerpt from a midi file that has been read using Music21:" }, { "code": null, "e": 3587, "s": 3170, "text": "...<music21.note.Note F><music21.chord.Chord A2 E3><music21.chord.Chord A2 E3><music21.note.Note E><music21.chord.Chord B-2 F3><music21.note.Note F><music21.note.Note G><music21.note.Note D><music21.chord.Chord B-2 F3><music21.note.Note F><music21.chord.Chord B-2 F3><music21.note.Note E><music21.chord.Chord B-2 F3><music21.note.Note D><music21.chord.Chord B-2 F3><music21.note.Note E><music21.chord.Chord A2 E3>..." }, { "code": null, "e": 3726, "s": 3587, "text": "The data splits into two object types: Notes and Chords. Note objects contain information about the pitch, octave, and offset of the Note." }, { "code": null, "e": 3903, "s": 3726, "text": "Pitch refers to the frequency of the sound, or how high or low it is and is represented with the letters [A, B, C, D, E, F, G], with A being the highest and G being the lowest." }, { "code": null, "e": 3961, "s": 3903, "text": "Octave refers to which set of pitches you use on a piano." }, { "code": null, "e": 4018, "s": 3961, "text": "Offset refers to where the note is located in the piece." }, { "code": null, "e": 4117, "s": 4018, "text": "And Chord objects are essentially a container for a set of notes that are played at the same time." }, { "code": null, "e": 4587, "s": 4117, "text": "Now we can see that to generate music accurately our neural network will have to be able to predict which note or chord is next. That means that our prediction array will have to contain every note and chord object that we encounter in our training set. In the training set on the Github page the total number of different notes and chords was 352. That seems like a lot of possible output predictions for the network to handle, but a LSTM network can easily handle it." }, { "code": null, "e": 4877, "s": 4587, "text": "Next we have to worry about where we want to put the notes. As most people that have listened to music have noticed, notes usually have varying intervals between them. You can have many notes in quick succession and then followed by a rest period where no note is played for a short while." }, { "code": null, "e": 5087, "s": 4877, "text": "Below we have another excerpt from a midi file that has been read using Music21, only this time we have added the offset of the object behind it. This allows us to see the interval between each note and chord." }, { "code": null, "e": 5679, "s": 5087, "text": "...<music21.note.Note B> 72.0<music21.chord.Chord E3 A3> 72.0<music21.note.Note A> 72.5<music21.chord.Chord E3 A3> 72.5<music21.note.Note E> 73.0<music21.chord.Chord E3 A3> 73.0<music21.chord.Chord E3 A3> 73.5<music21.note.Note E-> 74.0<music21.chord.Chord F3 A3> 74.0<music21.chord.Chord F3 A3> 74.5<music21.chord.Chord F3 A3> 75.0<music21.chord.Chord F3 A3> 75.5<music21.chord.Chord E3 A3> 76.0<music21.chord.Chord E3 A3> 76.5<music21.chord.Chord E3 A3> 77.0<music21.chord.Chord E3 A3> 77.5<music21.chord.Chord F3 A3> 78.0<music21.chord.Chord F3 A3> 78.5<music21.chord.Chord F3 A3> 79.0..." }, { "code": null, "e": 6093, "s": 5679, "text": "As can be seen from this excerpt and most of the dataset, the most common interval between notes in the midi files is 0.5. Therefore, we can simplify the data and model by disregarding the varying offsets in the list of possible outputs. It will not affect the melodies of the music generated by the network too severely. So we will ignore the offset in this tutorial and keep our list of possible outputs at 352." }, { "code": null, "e": 6298, "s": 6093, "text": "Now that we have examined the data and determined that the features that we want to use are the notes and chords as the input and output of our LSTM network it is time to prepare the data for the network." }, { "code": null, "e": 6383, "s": 6298, "text": "First, we will load the data into an array as can be seen in the code snippet below:" }, { "code": null, "e": 7010, "s": 6383, "text": "from music21 import converter, instrument, note, chordnotes = []for file in glob.glob(\"midi_songs/*.mid\"): midi = converter.parse(file) notes_to_parse = None parts = instrument.partitionByInstrument(midi) if parts: # file has instrument parts notes_to_parse = parts.parts[0].recurse() else: # file has notes in a flat structure notes_to_parse = midi.flat.notes for element in notes_to_parse: if isinstance(element, note.Note): notes.append(str(element.pitch)) elif isinstance(element, chord.Chord): notes.append('.'.join(str(n) for n in element.normalOrder))" }, { "code": null, "e": 7618, "s": 7010, "text": "We start by loading each file into a Music21 stream object using the converter.parse(file) function. Using that stream object we get a list of all the notes and chords in the file. We append the pitch of every note object using its string notation since the most significant parts of the note can be recreated using the string notation of the pitch. And we append every chord by encoding the id of every note in the chord together into a single string, with each note being separated by a dot. These encodings allows us to easily decode the output generated by the network into the correct notes and chords." }, { "code": null, "e": 7760, "s": 7618, "text": "Now that we have put all the notes and chords into a sequential list we can create the sequences that will serve as the input of our network." }, { "code": null, "e": 8083, "s": 7760, "text": "First, we will create a mapping function to map from string-based categorical data to integer-based numerical data. This is done because neural network perform much better with integer-based numerical data than string-based categorical data. An example of a categorical to numerical transformation can be seen in Figure 1." }, { "code": null, "e": 8319, "s": 8083, "text": "Next, we have to create input sequences for the network and their respective outputs. The output for each input sequence will be the first note or chord that comes after the sequence of notes in the input sequence in our list of notes." }, { "code": null, "e": 9177, "s": 8319, "text": "sequence_length = 100# get all pitch namespitchnames = sorted(set(item for item in notes))# create a dictionary to map pitches to integersnote_to_int = dict((note, number) for number, note in enumerate(pitchnames))network_input = []network_output = []# create input sequences and the corresponding outputsfor i in range(0, len(notes) - sequence_length, 1): sequence_in = notes[i:i + sequence_length] sequence_out = notes[i + sequence_length] network_input.append([note_to_int[char] for char in sequence_in]) network_output.append(note_to_int[sequence_out])n_patterns = len(network_input)# reshape the input into a format compatible with LSTM layersnetwork_input = numpy.reshape(network_input, (n_patterns, sequence_length, 1))# normalize inputnetwork_input = network_input / float(n_vocab)network_output = np_utils.to_categorical(network_output)" }, { "code": null, "e": 9553, "s": 9177, "text": "In our code example, we have put the length of each sequence to be 100 notes/chords. This means that to predict the next note in the sequence the network has the previous 100 notes to help make the prediction. I highly recommend training the network using different sequence lengths to see the impact different sequence lengths can have on the music generated by the network." }, { "code": null, "e": 9663, "s": 9553, "text": "The final step in preparing the data for the network is to normalise the input and one-hot encode the output." }, { "code": null, "e": 9767, "s": 9663, "text": "Finally we get to designing the model architecture. In our model we use four different types of layers:" }, { "code": null, "e": 9914, "s": 9767, "text": "LSTM layers is a Recurrent Neural Net layer that takes a sequence as an input and can return either sequences (return_sequences=True) or a matrix." }, { "code": null, "e": 10140, "s": 9914, "text": "Dropout layers are a regularisation technique that consists of setting a fraction of input units to 0 at each update during the training to prevent overfitting. The fraction is determined by the parameter used with the layer." }, { "code": null, "e": 10277, "s": 10140, "text": "Dense layers or fully connected layers is a fully connected neural network layer where each input node is connected to each output node." }, { "code": null, "e": 10397, "s": 10277, "text": "The Activation layer determines what activation function our neural network will use to calculate the output of a node." }, { "code": null, "e": 10866, "s": 10397, "text": "model = Sequential() model.add(LSTM( 256, input_shape=(network_input.shape[1], network_input.shape[2]), return_sequences=True )) model.add(Dropout(0.3)) model.add(LSTM(512, return_sequences=True)) model.add(Dropout(0.3)) model.add(LSTM(256)) model.add(Dense(256)) model.add(Dropout(0.3)) model.add(Dense(n_vocab)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='rmsprop')" }, { "code": null, "e": 10989, "s": 10866, "text": "Now that we have some information about the different layers we will be using it is time to add them to the network model." }, { "code": null, "e": 11206, "s": 10989, "text": "For each LSTM, Dense, and Activation layer the first parameter is how many nodes the layer should have. For the Dropout layer the first parameter is the fraction of input units that should be dropped during training." }, { "code": null, "e": 11384, "s": 11206, "text": "For the first layer we have to provide a unique parameter called input_shape. The purpose of the parameter is to inform the network of the shape of the data it will be training." }, { "code": null, "e": 11572, "s": 11384, "text": "The last layer should always contain the same amount of nodes as the number different outputs our system has. This assures that the output of the network will map directly to our classes." }, { "code": null, "e": 11842, "s": 11572, "text": "For this tutorial we will use a simple network consisting of three LSTM layers, three Dropout layers, two Dense layers and one activation layer. I would recommend playing around with the structure of the network to see if you can improve the quality of the predictions." }, { "code": null, "e": 12174, "s": 11842, "text": "To calculate the loss for each iteration of the training we will be using categorical cross entropy since each of our outputs only belongs to a single class and we have more than two classes to work with. And to optimise our network we will use a RMSprop optimizer as it is usually a very good choice for recurrent neural networks." }, { "code": null, "e": 12505, "s": 12174, "text": "filepath = \"weights-improvement-{epoch:02d}-{loss:.4f}-bigger.hdf5\" checkpoint = ModelCheckpoint( filepath, monitor='loss', verbose=0, save_best_only=True, mode='min') callbacks_list = [checkpoint] model.fit(network_input, network_output, epochs=200, batch_size=64, callbacks=callbacks_list)" }, { "code": null, "e": 12953, "s": 12505, "text": "Once we have determined the architecture of our network the time has come to start the training. The model.fit() function in Keras is used to train the network. The first parameter is the list of input sequences that we prepared earlier and the second is a list of their respective outputs. In our tutorial we are going to train the network for 200 epochs (iterations), with each batch that is propagated through the network containing 64 samples." }, { "code": null, "e": 13491, "s": 12953, "text": "To make sure that we can stop the training at any point in time without losing all of our hard work, we will use model checkpoints. Model checkpoints provide us with a way to save the weights of the network nodes to a file after every epoch. This allows us to stop running the neural network once we are satisfied with the loss value without having to worry about losing the weights. Otherwise we would have to wait until the network has finished going through all 200 epochs before we could get the chance to save the weights to a file." }, { "code": null, "e": 13613, "s": 13491, "text": "Now that we have finished training the network it is time to have some fun with the network we have spent hours training." }, { "code": null, "e": 13982, "s": 13613, "text": "To be able to use the neural network to generate music you will have to put it into the same state as before. For simplicity we will reuse code from the training section to prepare the data and set up the network model in the same way as before. Except, that instead of training the network we load the weights that we saved during the training section into the model." }, { "code": null, "e": 14460, "s": 13982, "text": "model = Sequential()model.add(LSTM( 512, input_shape=(network_input.shape[1], network_input.shape[2]), return_sequences=True))model.add(Dropout(0.3))model.add(LSTM(512, return_sequences=True))model.add(Dropout(0.3))model.add(LSTM(512))model.add(Dense(256))model.add(Dropout(0.3))model.add(Dense(n_vocab))model.add(Activation('softmax'))model.compile(loss='categorical_crossentropy', optimizer='rmsprop')# Load the weights to each nodemodel.load_weights('weights.hdf5')" }, { "code": null, "e": 14520, "s": 14460, "text": "Now we can use the trained model to start generating notes." }, { "code": null, "e": 14867, "s": 14520, "text": "Since we have a full list of note sequences at our disposal we will pick a random index in the list as our starting point, this allows us to rerun the generation code without changing anything and get different results every time. However, If you wish to control the starting point simply replace the random function with a command line argument." }, { "code": null, "e": 15040, "s": 14867, "text": "Here we also need to create a mapping function to decode the output of the network. This function will map from numerical data to categorical data (from integers to notes)." }, { "code": null, "e": 15618, "s": 15040, "text": "start = numpy.random.randint(0, len(network_input)-1)int_to_note = dict((number, note) for number, note in enumerate(pitchnames))pattern = network_input[start]prediction_output = []# generate 500 notesfor note_index in range(500): prediction_input = numpy.reshape(pattern, (1, len(pattern), 1)) prediction_input = prediction_input / float(n_vocab) prediction = model.predict(prediction_input, verbose=0) index = numpy.argmax(prediction) result = int_to_note[index] prediction_output.append(result) pattern.append(index) pattern = pattern[1:len(pattern)]" }, { "code": null, "e": 16130, "s": 15618, "text": "We chose to generate 500 notes using the network since that is roughly two minutes of music and gives the network plenty of space to create a melody. For each note that we want to generate we have to submit a sequence to the network. The first sequence we submit is the sequence of notes at the starting index. For every subsequent sequence that we use as input, we will remove the first note of the sequence and insert the output of the previous iteration at the end of the sequence as can be seen in Figure 2." }, { "code": null, "e": 16372, "s": 16130, "text": "To determine the most likely prediction from the output from the network, we extract the index of the highest value. The value at index X in the output array correspond to the probability that X is the next note. Figure 3 helps explain this." }, { "code": null, "e": 16442, "s": 16372, "text": "Then we collect all the outputs from the network into a single array." }, { "code": null, "e": 16603, "s": 16442, "text": "Now that we have all the encoded representations of the notes and chords in an array we can start decoding them and creating an array of Note and Chord objects." }, { "code": null, "e": 16687, "s": 16603, "text": "First we have to determine whether the output we are decoding is a Note or a Chord." }, { "code": null, "e": 16938, "s": 16687, "text": "If the pattern is a Chord, we have to split the string up into an array of notes. Then we loop through the string representation of each note and create a Note object for each of them. Then we can create a Chord object containing each of these notes." }, { "code": null, "e": 17059, "s": 16938, "text": "If the pattern is a Note, we create a Note object using the string representation of the pitch contained in the pattern." }, { "code": null, "e": 17208, "s": 17059, "text": "At the end of each iteration we increase the offset by 0.5 (as we decided in a previous section) and append the Note/Chord object created to a list." }, { "code": null, "e": 18040, "s": 17208, "text": "offset = 0output_notes = []# create note and chord objects based on the values generated by the modelfor pattern in prediction_output: # pattern is a chord if ('.' in pattern) or pattern.isdigit(): notes_in_chord = pattern.split('.') notes = [] for current_note in notes_in_chord: new_note = note.Note(int(current_note)) new_note.storedInstrument = instrument.Piano() notes.append(new_note) new_chord = chord.Chord(notes) new_chord.offset = offset output_notes.append(new_chord) # pattern is a note else: new_note = note.Note(pattern) new_note.offset = offset new_note.storedInstrument = instrument.Piano() output_notes.append(new_note) # increase offset each iteration so that notes do not stack offset += 0.5" }, { "code": null, "e": 18341, "s": 18040, "text": "Now that we have a list of Notes and Chords generated by the network we can create a Music21 Stream object using the list as a parameter. Then finally to create the MIDI file to contain the music generated by the network we use the write function in the Music21 toolkit to write the stream to a file." }, { "code": null, "e": 18430, "s": 18341, "text": "midi_stream = stream.Stream(output_notes)midi_stream.write('midi', fp='test_output.mid')" }, { "code": null, "e": 18706, "s": 18430, "text": "Now it is time to marvel at the results. Figure 4 contains sheet music representation of music that was generated using the LSTM network. At a quick glance we can see that there is some structure to it. This is especially obvious in the third to last line on the second page." }, { "code": null, "e": 19066, "s": 18706, "text": "People that are knowledgeable about music and can read musical notation can see that there are some weird notes strewn about the sheet. This is a result of the neural network not being able to create perfect melodies. With our current implementation there will always be some false notes and to be able to achieve better results we will need a bigger network." }, { "code": null, "e": 19298, "s": 19066, "text": "The results from this relatively shallow network are still really impressive as can be heard from the example music in Embed 1. For those interested, the sheet music in Figure 4 represents the musical notation of NeuralNet Music 5." }, { "code": null, "e": 19452, "s": 19298, "text": "We have achieved remarkable results and beautiful melodies by using a simple LSTM network and 352 classes. However, there are areas that can be improved." }, { "code": null, "e": 19717, "s": 19452, "text": "First, the implementation we have at the moment does not support varying duration of notes and different offsets between notes. To achieve that we could add more classes for each different duration and add rest classes that represent the rest period between notes." }, { "code": null, "e": 19988, "s": 19717, "text": "To achieve satisfying results with more classes added we would also have to increase the depth of the LSTM network, which would require a significantly more powerful computer. It took the laptop I use at home approximately twenty hours to train the network as it is now." }, { "code": null, "e": 20315, "s": 19988, "text": "Second, add beginnings and endings to pieces. As the network is now there is no distinction between pieces, that is to say the network does not know where one piece ends and another one begins. This would allow the network to generate a piece from start to finish instead of ending the generated piece abruptly as it does now." }, { "code": null, "e": 20572, "s": 20315, "text": "Third, add a method to handle unknown notes. As it is now the network would enter a fail state if it encounters a note that it does not know. A possible method to solve that issue would be to find the note or chord that is most similar to the unknown note." }, { "code": null, "e": 20789, "s": 20572, "text": "Finally, adding more instruments to the dataset. As it is now, the network only supports pieces that only have a single instrument. It would be interesting to see if it could be expanded to support a whole orchestra." }, { "code": null, "e": 21081, "s": 20789, "text": "During this tutorial we have shown how to create a LSTM neural network to generate music. While the results may not be perfect, they are pretty impressive nonetheless and shows us that neural networks can create music and could potentially be used to help create more complex musical pieces." } ]
Matplotlib - Cursor Widget - GeeksforGeeks
15 Mar, 2021 Matplotlib is a Data Visualization library in python. It consists of many widgets that are designed to work for any of the GUI backends. Some examples of widgets in matplotlib are Button, CheckButtons, RadioButtons, Cursor, and TextBox. In this article, the Cursor Widget of Matplotlib library has been discussed. A Cursor spans the axes horizontally and/or vertically and moves with the mouse cursor. Syntax: Cursor(ax, horizOn=True, vertOn=True, useblit=False, **lineprops) Parameters: ax : Axes to attach the cursor to. Optional Parameters: horizOn : To draw the horizontal line(default: True). vertOn : To draw the vertical line(default: True). useblit : Use blitting for faster drawing if supported by the backend(default: False). **lineprops: Line properties to control appearance of the lines(linewidth, color). Example 1: Python3 # importing cursor widget from matplotlibfrom matplotlib.widgets import Cursorimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure()ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) num = 100x = np.random.rand(num)y = np.random.rand(num) ax.scatter(x, y, c='blue')ax.set_xlabel('X-axis')ax.set_ylabel('Y-axis') cursor = Cursor(ax, color='green', linewidth=2)plt.show() Output: In the above output, the cursor can be moved horizontally and vertically throughout the matplotlib axes. We can just drag the cursor wherever necessary. MultiCursor is used to show cursor on multiple plots at the same time i.e., Cursor is shared between multiple axes. Syntax: MultiCursor(canvas, axes, useblit=True, horizOn=False, vertOn=True, **lineprops) Example: Python3 # Import MultiCursor from matplotlibfrom matplotlib.widgets import MultiCursorimport matplotlib.pyplot as pltimport numpy as np fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True) x = np.linspace(-np.pi, np.pi, 256, endpoint=True)y = np.sin(x)z = np.cos(x) ax1.plot(x, y, label="sin function")ax1.legend(loc="upper right")ax2.plot(x, z, label="cos function") multi = MultiCursor(fig.canvas, (ax1, ax2), color='g', lw=2, horizOn=False, vertOn=True) ax2.legend(loc="upper right")plt.show() Output: Example: Python3 from matplotlib.widgets import MultiCursorimport matplotlib.pyplot as pltimport numpy as np fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) x1 = ['Telugu', 'Hindi', 'English', 'Maths', 'Science', 'Social']y1 = [45, 34, 30, 45, 50, 38]y2 = [36, 28, 30, 45, 38, 50] labels = ["in 2020", "in 2021"] l1 = ax1.plot(x1, y1, 'o', color="green")l2 = ax2.plot(x1, y2, 'o', color="blue") ax1.set_yticks(np.arange(0, 51, 5))ax2.set_yticks(np.arange(0, 51, 5)) ax1.set_ylabel('Number of students passed', fontsize=15) fig.legend([l1, l2], labels=labels, loc="upper right")cursor = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=2, horizOn=True, vertOn=True) plt.subplots_adjust(right=0.9)plt.show() Output: Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23925, "s": 23897, "text": "\n15 Mar, 2021" }, { "code": null, "e": 24239, "s": 23925, "text": "Matplotlib is a Data Visualization library in python. It consists of many widgets that are designed to work for any of the GUI backends. Some examples of widgets in matplotlib are Button, CheckButtons, RadioButtons, Cursor, and TextBox. In this article, the Cursor Widget of Matplotlib library has been discussed." }, { "code": null, "e": 24328, "s": 24239, "text": "A Cursor spans the axes horizontally and/or vertically and moves with the mouse cursor. " }, { "code": null, "e": 24402, "s": 24328, "text": "Syntax: Cursor(ax, horizOn=True, vertOn=True, useblit=False, **lineprops)" }, { "code": null, "e": 24414, "s": 24402, "text": "Parameters:" }, { "code": null, "e": 24449, "s": 24414, "text": "ax : Axes to attach the cursor to." }, { "code": null, "e": 24470, "s": 24449, "text": "Optional Parameters:" }, { "code": null, "e": 24524, "s": 24470, "text": "horizOn : To draw the horizontal line(default: True)." }, { "code": null, "e": 24575, "s": 24524, "text": "vertOn : To draw the vertical line(default: True)." }, { "code": null, "e": 24662, "s": 24575, "text": "useblit : Use blitting for faster drawing if supported by the backend(default: False)." }, { "code": null, "e": 24745, "s": 24662, "text": "**lineprops: Line properties to control appearance of the lines(linewidth, color)." }, { "code": null, "e": 24756, "s": 24745, "text": "Example 1:" }, { "code": null, "e": 24764, "s": 24756, "text": "Python3" }, { "code": "# importing cursor widget from matplotlibfrom matplotlib.widgets import Cursorimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure()ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) num = 100x = np.random.rand(num)y = np.random.rand(num) ax.scatter(x, y, c='blue')ax.set_xlabel('X-axis')ax.set_ylabel('Y-axis') cursor = Cursor(ax, color='green', linewidth=2)plt.show()", "e": 25141, "s": 24764, "text": null }, { "code": null, "e": 25149, "s": 25141, "text": "Output:" }, { "code": null, "e": 25302, "s": 25149, "text": "In the above output, the cursor can be moved horizontally and vertically throughout the matplotlib axes. We can just drag the cursor wherever necessary." }, { "code": null, "e": 25418, "s": 25302, "text": "MultiCursor is used to show cursor on multiple plots at the same time i.e., Cursor is shared between multiple axes." }, { "code": null, "e": 25426, "s": 25418, "text": "Syntax:" }, { "code": null, "e": 25507, "s": 25426, "text": "MultiCursor(canvas, axes, useblit=True, horizOn=False, vertOn=True, **lineprops)" }, { "code": null, "e": 25516, "s": 25507, "text": "Example:" }, { "code": null, "e": 25524, "s": 25516, "text": "Python3" }, { "code": "# Import MultiCursor from matplotlibfrom matplotlib.widgets import MultiCursorimport matplotlib.pyplot as pltimport numpy as np fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True) x = np.linspace(-np.pi, np.pi, 256, endpoint=True)y = np.sin(x)z = np.cos(x) ax1.plot(x, y, label=\"sin function\")ax1.legend(loc=\"upper right\")ax2.plot(x, z, label=\"cos function\") multi = MultiCursor(fig.canvas, (ax1, ax2), color='g', lw=2, horizOn=False, vertOn=True) ax2.legend(loc=\"upper right\")plt.show()", "e": 26037, "s": 25524, "text": null }, { "code": null, "e": 26045, "s": 26037, "text": "Output:" }, { "code": null, "e": 26054, "s": 26045, "text": "Example:" }, { "code": null, "e": 26062, "s": 26054, "text": "Python3" }, { "code": "from matplotlib.widgets import MultiCursorimport matplotlib.pyplot as pltimport numpy as np fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) x1 = ['Telugu', 'Hindi', 'English', 'Maths', 'Science', 'Social']y1 = [45, 34, 30, 45, 50, 38]y2 = [36, 28, 30, 45, 38, 50] labels = [\"in 2020\", \"in 2021\"] l1 = ax1.plot(x1, y1, 'o', color=\"green\")l2 = ax2.plot(x1, y2, 'o', color=\"blue\") ax1.set_yticks(np.arange(0, 51, 5))ax2.set_yticks(np.arange(0, 51, 5)) ax1.set_ylabel('Number of students passed', fontsize=15) fig.legend([l1, l2], labels=labels, loc=\"upper right\")cursor = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=2, horizOn=True, vertOn=True) plt.subplots_adjust(right=0.9)plt.show()", "e": 26791, "s": 26062, "text": null }, { "code": null, "e": 26799, "s": 26791, "text": "Output:" }, { "code": null, "e": 26806, "s": 26799, "text": "Picked" }, { "code": null, "e": 26824, "s": 26806, "text": "Python-matplotlib" }, { "code": null, "e": 26831, "s": 26824, "text": "Python" }, { "code": null, "e": 26929, "s": 26831, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26938, "s": 26929, "text": "Comments" }, { "code": null, "e": 26951, "s": 26938, "text": "Old Comments" }, { "code": null, "e": 26983, "s": 26951, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27039, "s": 26983, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27081, "s": 27039, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27123, "s": 27081, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27159, "s": 27123, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27198, "s": 27159, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27220, "s": 27198, "text": "Defaultdict in Python" }, { "code": null, "e": 27251, "s": 27220, "text": "Python | os.path.join() method" }, { "code": null, "e": 27278, "s": 27251, "text": "Python Classes and Objects" } ]
Configuration file parser in Python (configparser)
The configparser module from Python's standard library defines functionality for reading and writing configuration files as used by Microsoft Windows OS. Such files usually have .INI extension. The INI file consists of sections, each led by a [section] header. Between square brackets, we can put the section’s name. Section is followed by key/value entries separated by = or : character. It may include comments, prefixed by # or ; symbol. A sample INI file is shown below − [Settings] # Set detailed log for additional debugging info DetailedLog=1 RunStatus=1 StatusPort=6090 StatusRefresh=10 Archive=1 # Sets the location of the MV_FTP log file LogFile=/opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log Version=0.9 Build 4 ServerName=Unknown [FTP] # set the FTP server active RunFTP=1 # defines the FTP control port FTPPort=21 # Sets the location of the FTP data directory FTPDir=/opt/ecs/mvuser/MV_IPTel/data/FTPdata # set the admin Name UserName=admin # set the Password Password=admin The configparser module has ConfigParser class. It is responsible for parsing a list of configuration files, and managing the parsed database. Object of ConfigParser is created by following statement − parser = configparser.ConfigParser() Following methods are defined in this class − Following script reads and parses the 'sampleconfig.ini' file import configparser parser = configparser.ConfigParser() parser.read('sampleconfig.ini') for sect in parser.sections(): print('Section:', sect) for k,v in parser.items(sect): print(' {} = {}'.format(k,v)) print() Section: Settings detailedlog = 1 runstatus = 1 statusport = 6090 statusrefresh = 10 archive = 1 logfile = /opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log version = 0.9 Build 4 servername = Unknown Section: FTP runftp = 1 ftpport = 21 ftpdir = /opt/ecs/mvuser/MV_IPTel/data/FTPdata username = admin password = admin The write() method is used to create a configuration file. Following script configures the parser object and writes it to a file object representing 'test.ini' import configparser parser = configparser.ConfigParser() parser.add_section('Manager') parser.set('Manager', 'Name', 'Ashok Kulkarni') parser.set('Manager', 'email', 'ashok@gmail.com') parser.set('Manager', 'password', 'secret') fp=open('test.ini','w') parser.write(fp) fp.close()
[ { "code": null, "e": 1256, "s": 1062, "text": "The configparser module from Python's standard library defines functionality for reading and writing configuration files as used by Microsoft Windows OS. Such files usually have .INI extension." }, { "code": null, "e": 1538, "s": 1256, "text": "The INI file consists of sections, each led by a [section] header. Between square brackets, we can put the section’s name. Section is followed by key/value entries separated by = or : character. It may include comments, prefixed by # or ; symbol. A sample INI file is shown below −" }, { "code": null, "e": 2046, "s": 1538, "text": "[Settings]\n# Set detailed log for additional debugging info\nDetailedLog=1\nRunStatus=1\nStatusPort=6090\nStatusRefresh=10\nArchive=1\n# Sets the location of the MV_FTP log file\nLogFile=/opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log\nVersion=0.9 Build 4\nServerName=Unknown\n\n[FTP]\n# set the FTP server active\nRunFTP=1\n# defines the FTP control port\nFTPPort=21\n# Sets the location of the FTP data directory\nFTPDir=/opt/ecs/mvuser/MV_IPTel/data/FTPdata\n# set the admin Name\nUserName=admin\n# set the Password\nPassword=admin" }, { "code": null, "e": 2189, "s": 2046, "text": "The configparser module has ConfigParser class. It is responsible for parsing a list of configuration files, and managing the parsed database." }, { "code": null, "e": 2248, "s": 2189, "text": "Object of ConfigParser is created by following statement −" }, { "code": null, "e": 2286, "s": 2248, "text": "parser = configparser.ConfigParser()\n" }, { "code": null, "e": 2332, "s": 2286, "text": "Following methods are defined in this class −" }, { "code": null, "e": 2394, "s": 2332, "text": "Following script reads and parses the 'sampleconfig.ini' file" }, { "code": null, "e": 2622, "s": 2394, "text": "import configparser\nparser = configparser.ConfigParser()\nparser.read('sampleconfig.ini')\nfor sect in parser.sections():\n print('Section:', sect)\n for k,v in parser.items(sect):\n print(' {} = {}'.format(k,v))\n print()" }, { "code": null, "e": 2933, "s": 2622, "text": "Section: Settings\ndetailedlog = 1\nrunstatus = 1\nstatusport = 6090\nstatusrefresh = 10\narchive = 1\nlogfile = /opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log\nversion = 0.9 Build 4\nservername = Unknown\n\nSection: FTP\nrunftp = 1\nftpport = 21\nftpdir = /opt/ecs/mvuser/MV_IPTel/data/FTPdata\nusername = admin\npassword = admin" }, { "code": null, "e": 3093, "s": 2933, "text": "The write() method is used to create a configuration file. Following script configures the parser object and writes it to a file object representing 'test.ini'" }, { "code": null, "e": 3374, "s": 3093, "text": "import configparser\nparser = configparser.ConfigParser()\nparser.add_section('Manager')\nparser.set('Manager', 'Name', 'Ashok Kulkarni')\nparser.set('Manager', 'email', 'ashok@gmail.com')\nparser.set('Manager', 'password', 'secret')\nfp=open('test.ini','w')\nparser.write(fp)\nfp.close()" } ]
How to convert an std::string to const char* or char* in C++?
You can use the c_str() method of the string class to get a const char* with the string contents. #include<iostream> using namespace std; int main() { string x("hello"); const char* ccx = x.c_str(); cout << ccx; } This will give the output − hello To get a char*, use the copy function. #include<iostream> using namespace std; int main() { string x("hello"); // Allocate memory char* ccx = new char[s.length() + 1]; // Copy contents std::copy(s.begin(), s.end(), ccx) cout << ccx; } This will give the output − hello
[ { "code": null, "e": 1161, "s": 1062, "text": "You can use the c_str() method of the string class to get a const char* with the string contents. " }, { "code": null, "e": 1287, "s": 1161, "text": "#include<iostream>\nusing namespace std;\n\nint main() {\n string x(\"hello\");\n const char* ccx = x.c_str();\n cout << ccx;\n}" }, { "code": null, "e": 1315, "s": 1287, "text": "This will give the output −" }, { "code": null, "e": 1321, "s": 1315, "text": "hello" }, { "code": null, "e": 1360, "s": 1321, "text": "To get a char*, use the copy function." }, { "code": null, "e": 1577, "s": 1360, "text": "#include<iostream>\nusing namespace std;\n\nint main() {\n string x(\"hello\");\n\n // Allocate memory\n char* ccx = new char[s.length() + 1];\n\n // Copy contents\n std::copy(s.begin(), s.end(), ccx)\n cout << ccx;\n}" }, { "code": null, "e": 1605, "s": 1577, "text": "This will give the output −" }, { "code": null, "e": 1611, "s": 1605, "text": "hello" } ]
EVM - Cost Variance
Cost Variance (CV) is a very important factor to measure project performance. CV indicates how much over - or under-budget the project is. CV can be calculated using the following formula: Cost Variance (CV) = Earned Value (EV) − Actual Cost (AC) OR Cost Variance (CV) = BCWP − ACWP The formula mentioned above gives the variance in terms of cost. Positive CV indicates the project is under-budget. Negative CV indicates the project is over-budget. Cost Variance % indicates how much over - or under-budget the project is in terms of percentage. Cost Variance % can be calculated using the following formula: CV % = Cost Variance (CV) ⁄ Earned Value (EV) OR CV % = CV ⁄ BCWP The formula mentioned above gives the variance in terms of percentage. Positive Variance % indicates % under budget Negative Variance % indicates % over budget. Cost Performance Indicator (CPI) is an index showing the efficiency of the utilization of the resources on the project. CPI can be calculated using the following formula: CPI = Earned Value (EV) ⁄ Actual Cost (AC) OR CPI = BCWP ⁄ ACWP The formula mentioned above gives the efficiency of the utilization of the resources allocated to the project. The formula mentioned above gives the efficiency of the utilization of the resources allocated to the project. A CPI value above 1 indicates the efficiency of utilizing the resources allocated to the project is good. A CPI value above 1 indicates the efficiency of utilizing the resources allocated to the project is good. A CPI value below 1 indicates the efficiency of utilizing the resources allocated to the project is not good. A CPI value below 1 indicates the efficiency of utilizing the resources allocated to the project is not good. To Complete Cost Performance Indicator (TCPI) is an index showing the efficiency at which the resources on the project should be utilized for the remainder of the project. It can be calculated using the following formula: TCPI = ( Total Budget − EV ) ⁄ ( Total Budget − AC ) OR TCPI = ( Total Budget − BCWP ) ⁄ ( Total Budget − ACWP ) The formula mentioned above gives the efficiency at which the project team should be utilized for the remainder of the project. The formula mentioned above gives the efficiency at which the project team should be utilized for the remainder of the project. A TCPI value above 1 indicates the utilization of the project team for the remainder of the project can be stringent. A TCPI value above 1 indicates the utilization of the project team for the remainder of the project can be stringent. A TCPI value below 1 indicates the utilization of the project team for the remainder of the project should be lenient. A TCPI value below 1 indicates the utilization of the project team for the remainder of the project should be lenient. 136 Lectures 11 hours In28Minutes Official 288 Lectures 25 hours In28Minutes Official 14 Lectures 57 mins Kaushik Roy Chowdhury 64 Lectures 10.5 hours Eduonix Learning Solutions 56 Lectures 12.5 hours Eduonix Learning Solutions 53 Lectures 9 hours Anshul Chauhan Print Add Notes Bookmark this page
[ { "code": null, "e": 1843, "s": 1704, "text": "Cost Variance (CV) is a very important factor to measure project performance. CV indicates how much over - or under-budget the project is." }, { "code": null, "e": 1893, "s": 1843, "text": "CV can be calculated using the following formula:" }, { "code": null, "e": 1952, "s": 1893, "text": "Cost Variance (CV) = Earned Value (EV) − Actual Cost (AC)\n" }, { "code": null, "e": 1955, "s": 1952, "text": "OR" }, { "code": null, "e": 1989, "s": 1955, "text": "Cost Variance (CV) = BCWP − ACWP\n" }, { "code": null, "e": 2054, "s": 1989, "text": "The formula mentioned above gives the variance in terms of cost." }, { "code": null, "e": 2105, "s": 2054, "text": "Positive CV indicates the project is under-budget." }, { "code": null, "e": 2155, "s": 2105, "text": "Negative CV indicates the project is over-budget." }, { "code": null, "e": 2252, "s": 2155, "text": "Cost Variance % indicates how much over - or under-budget the project is in terms of percentage." }, { "code": null, "e": 2315, "s": 2252, "text": "Cost Variance % can be calculated using the following formula:" }, { "code": null, "e": 2362, "s": 2315, "text": "CV % = Cost Variance (CV) ⁄ Earned Value (EV)\n" }, { "code": null, "e": 2365, "s": 2362, "text": "OR" }, { "code": null, "e": 2383, "s": 2365, "text": "CV % = CV ⁄ BCWP\n" }, { "code": null, "e": 2454, "s": 2383, "text": "The formula mentioned above gives the variance in terms of percentage." }, { "code": null, "e": 2499, "s": 2454, "text": "Positive Variance % indicates % under budget" }, { "code": null, "e": 2544, "s": 2499, "text": "Negative Variance % indicates % over budget." }, { "code": null, "e": 2715, "s": 2544, "text": "Cost Performance Indicator (CPI) is an index showing the efficiency of the utilization of the resources on the project. CPI can be calculated using the following formula:" }, { "code": null, "e": 2759, "s": 2715, "text": "CPI = Earned Value (EV) ⁄ Actual Cost (AC)\n" }, { "code": null, "e": 2762, "s": 2759, "text": "OR" }, { "code": null, "e": 2781, "s": 2762, "text": "CPI = BCWP ⁄ ACWP\n" }, { "code": null, "e": 2892, "s": 2781, "text": "The formula mentioned above gives the efficiency of the utilization of the resources allocated to the project." }, { "code": null, "e": 3003, "s": 2892, "text": "The formula mentioned above gives the efficiency of the utilization of the resources allocated to the project." }, { "code": null, "e": 3109, "s": 3003, "text": "A CPI value above 1 indicates the efficiency of utilizing the resources allocated to the project is good." }, { "code": null, "e": 3215, "s": 3109, "text": "A CPI value above 1 indicates the efficiency of utilizing the resources allocated to the project is good." }, { "code": null, "e": 3325, "s": 3215, "text": "A CPI value below 1 indicates the efficiency of utilizing the resources allocated to the project is not good." }, { "code": null, "e": 3435, "s": 3325, "text": "A CPI value below 1 indicates the efficiency of utilizing the resources allocated to the project is not good." }, { "code": null, "e": 3657, "s": 3435, "text": "To Complete Cost Performance Indicator (TCPI) is an index showing the efficiency at which the resources on the project should be utilized for the remainder of the project. It can be calculated using the following formula:" }, { "code": null, "e": 3711, "s": 3657, "text": "TCPI = ( Total Budget − EV ) ⁄ ( Total Budget − AC )\n" }, { "code": null, "e": 3714, "s": 3711, "text": "OR" }, { "code": null, "e": 3772, "s": 3714, "text": "TCPI = ( Total Budget − BCWP ) ⁄ ( Total Budget − ACWP )\n" }, { "code": null, "e": 3900, "s": 3772, "text": "The formula mentioned above gives the efficiency at which the project team should be utilized for the remainder of the project." }, { "code": null, "e": 4028, "s": 3900, "text": "The formula mentioned above gives the efficiency at which the project team should be utilized for the remainder of the project." }, { "code": null, "e": 4146, "s": 4028, "text": "A TCPI value above 1 indicates the utilization of the project team for the remainder of the project can be stringent." }, { "code": null, "e": 4264, "s": 4146, "text": "A TCPI value above 1 indicates the utilization of the project team for the remainder of the project can be stringent." }, { "code": null, "e": 4383, "s": 4264, "text": "A TCPI value below 1 indicates the utilization of the project team for the\nremainder of the project should be lenient." }, { "code": null, "e": 4502, "s": 4383, "text": "A TCPI value below 1 indicates the utilization of the project team for the\nremainder of the project should be lenient." }, { "code": null, "e": 4537, "s": 4502, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4559, "s": 4537, "text": " In28Minutes Official" }, { "code": null, "e": 4594, "s": 4559, "text": "\n 288 Lectures \n 25 hours \n" }, { "code": null, "e": 4616, "s": 4594, "text": " In28Minutes Official" }, { "code": null, "e": 4648, "s": 4616, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 4671, "s": 4648, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4707, "s": 4671, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4735, "s": 4707, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4771, "s": 4735, "text": "\n 56 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4799, "s": 4771, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4832, "s": 4799, "text": "\n 53 Lectures \n 9 hours \n" }, { "code": null, "e": 4848, "s": 4832, "text": " Anshul Chauhan" }, { "code": null, "e": 4855, "s": 4848, "text": " Print" }, { "code": null, "e": 4866, "s": 4855, "text": " Add Notes" } ]
Bootstrap class input-group-xs
To make extra small input group, use the input-group-xs. You can try to run the following code to implement the input-group-xs class in Bootstrap − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div style = "padding: 100px 100px 10px; background: blue;"> <form class = "bs-example bs-example-form" role = "form"> <div class = "input-group input-group-xs"> <span class = "input-group-addon">$</span> <input type = "text" class = "form-control"> </div> </form> </div> </body> </html>
[ { "code": null, "e": 1119, "s": 1062, "text": "To make extra small input group, use the input-group-xs." }, { "code": null, "e": 1210, "s": 1119, "text": "You can try to run the following code to implement the input-group-xs class in Bootstrap −" }, { "code": null, "e": 1220, "s": 1210, "text": "Live Demo" }, { "code": null, "e": 1880, "s": 1220, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div style = \"padding: 100px 100px 10px; background: blue;\">\n <form class = \"bs-example bs-example-form\" role = \"form\">\n <div class = \"input-group input-group-xs\">\n <span class = \"input-group-addon\">$</span>\n <input type = \"text\" class = \"form-control\">\n </div>\n </form>\n </div>\n </body>\n</html>" } ]
Detecting communities in social networks using Girvan Newman algorithm in Python - GeeksforGeeks
05 Sep, 2020 Prerequisite– Python Basics, NetworkX Basics We are going to divide the nodes of the graph into two or more communities using the Girvan Newman algorithm. The Girvan Newman Algorithm removes the edges with the highest betweenness until there are no edges remain. Betweenness is the number of the shortest paths between pairs of nodes that run through it. We will use a Girvan Newman Algorithm for this task. Algorithm: Create a graph of N nodes and its edges or take an inbuilt graph like a barbell graph.Calculate the betweenness of all existed edges in the graph.Now remove all the edge(s) with the highest betweenness.Now recalculate the betweenness of all the edges that got affected by the removal of edges.Now repeat steps 3 and 4 until no edges remain. Create a graph of N nodes and its edges or take an inbuilt graph like a barbell graph. Calculate the betweenness of all existed edges in the graph. Now remove all the edge(s) with the highest betweenness. Now recalculate the betweenness of all the edges that got affected by the removal of edges. Now repeat steps 3 and 4 until no edges remain. Python Code: Python3 import networkx as nx def edge_to_remove(g): d1 = nx.edge_betweenness_centrality(g) list_of_tuples = list(d1.items()) sorted(list_of_tuples, key = lambda x:x[1], reverse = True) # Will return in the form (a,b) return list_of_tuples[0][0] def girvan(g): a = nx.connected_components(g) lena = len(list(a)) print (' The number of connected components are ', lena) while (lena == 1): # We need (a,b) instead of ((a,b)) u, v = edge_to_remove(g) g.remove_edge(u, v) a = nx.connected_components(g) lena=len(list(a)) print (' The number of connected components are ', lena) return a # Driver Codeg = nx.barbell_graph(5,0)a = girvan(g)print ('Barbell Graph') for i in a: print (i.nodes()) print ('.............') g1 = nx.karate_club_graph()a1 = girvan(g1) print ('Karate Club Graph')for i in a1: print (i.nodes()) print ('.............') Output: Barbell Graph The number of connected components are 1 The number of connected components are 2 [0, 1, 2, 3, 4] ............. [8, 9, 5, 6, 7] ............. Karate Club Graph The number of connected components are 1 The number of connected components are 1 The number of connected components are 1 The number of connected components are 1 The number of connected components are 1 The number of connected components are 1 The number of connected components are 1 The number of connected components are 1 The number of connected components are 1 The number of connected components are 1 The number of connected components are 1 The number of connected components are 2 [32, 33, 2, 8, 9, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] ............. [0, 1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21] ............. python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Python String | replace() sum() function in Python Python | Get unique values from a list Python string length | len() *args and **kwargs in Python Check if element exists in list in Python
[ { "code": null, "e": 24681, "s": 24653, "text": "\n05 Sep, 2020" }, { "code": null, "e": 24726, "s": 24681, "text": "Prerequisite– Python Basics, NetworkX Basics" }, { "code": null, "e": 25036, "s": 24726, "text": "We are going to divide the nodes of the graph into two or more communities using the Girvan Newman algorithm. The Girvan Newman Algorithm removes the edges with the highest betweenness until there are no edges remain. Betweenness is the number of the shortest paths between pairs of nodes that run through it." }, { "code": null, "e": 25089, "s": 25036, "text": "We will use a Girvan Newman Algorithm for this task." }, { "code": null, "e": 25100, "s": 25089, "text": "Algorithm:" }, { "code": null, "e": 25441, "s": 25100, "text": "Create a graph of N nodes and its edges or take an inbuilt graph like a barbell graph.Calculate the betweenness of all existed edges in the graph.Now remove all the edge(s) with the highest betweenness.Now recalculate the betweenness of all the edges that got affected by the removal of edges.Now repeat steps 3 and 4 until no edges remain." }, { "code": null, "e": 25528, "s": 25441, "text": "Create a graph of N nodes and its edges or take an inbuilt graph like a barbell graph." }, { "code": null, "e": 25589, "s": 25528, "text": "Calculate the betweenness of all existed edges in the graph." }, { "code": null, "e": 25646, "s": 25589, "text": "Now remove all the edge(s) with the highest betweenness." }, { "code": null, "e": 25738, "s": 25646, "text": "Now recalculate the betweenness of all the edges that got affected by the removal of edges." }, { "code": null, "e": 25786, "s": 25738, "text": "Now repeat steps 3 and 4 until no edges remain." }, { "code": null, "e": 25799, "s": 25786, "text": "Python Code:" }, { "code": null, "e": 25807, "s": 25799, "text": "Python3" }, { "code": "import networkx as nx def edge_to_remove(g): d1 = nx.edge_betweenness_centrality(g) list_of_tuples = list(d1.items()) sorted(list_of_tuples, key = lambda x:x[1], reverse = True) # Will return in the form (a,b) return list_of_tuples[0][0] def girvan(g): a = nx.connected_components(g) lena = len(list(a)) print (' The number of connected components are ', lena) while (lena == 1): # We need (a,b) instead of ((a,b)) u, v = edge_to_remove(g) g.remove_edge(u, v) a = nx.connected_components(g) lena=len(list(a)) print (' The number of connected components are ', lena) return a # Driver Codeg = nx.barbell_graph(5,0)a = girvan(g)print ('Barbell Graph') for i in a: print (i.nodes()) print ('.............') g1 = nx.karate_club_graph()a1 = girvan(g1) print ('Karate Club Graph')for i in a1: print (i.nodes()) print ('.............')", "e": 26763, "s": 25807, "text": null }, { "code": null, "e": 26771, "s": 26763, "text": "Output:" }, { "code": null, "e": 26785, "s": 26771, "text": "Barbell Graph" }, { "code": null, "e": 26826, "s": 26785, "text": "The number of connected components are 1" }, { "code": null, "e": 26867, "s": 26826, "text": "The number of connected components are 2" }, { "code": null, "e": 26883, "s": 26867, "text": "[0, 1, 2, 3, 4]" }, { "code": null, "e": 26897, "s": 26883, "text": "............." }, { "code": null, "e": 26913, "s": 26897, "text": "[8, 9, 5, 6, 7]" }, { "code": null, "e": 26927, "s": 26913, "text": "............." }, { "code": null, "e": 26945, "s": 26927, "text": "Karate Club Graph" }, { "code": null, "e": 26986, "s": 26945, "text": "The number of connected components are 1" }, { "code": null, "e": 27027, "s": 26986, "text": "The number of connected components are 1" }, { "code": null, "e": 27068, "s": 27027, "text": "The number of connected components are 1" }, { "code": null, "e": 27109, "s": 27068, "text": "The number of connected components are 1" }, { "code": null, "e": 27150, "s": 27109, "text": "The number of connected components are 1" }, { "code": null, "e": 27191, "s": 27150, "text": "The number of connected components are 1" }, { "code": null, "e": 27232, "s": 27191, "text": "The number of connected components are 1" }, { "code": null, "e": 27273, "s": 27232, "text": "The number of connected components are 1" }, { "code": null, "e": 27314, "s": 27273, "text": "The number of connected components are 1" }, { "code": null, "e": 27355, "s": 27314, "text": "The number of connected components are 1" }, { "code": null, "e": 27396, "s": 27355, "text": "The number of connected components are 1" }, { "code": null, "e": 27437, "s": 27396, "text": "The number of connected components are 2" }, { "code": null, "e": 27511, "s": 27437, "text": "[32, 33, 2, 8, 9, 14, 15, 18, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]" }, { "code": null, "e": 27525, "s": 27511, "text": "............." }, { "code": null, "e": 27579, "s": 27525, "text": "[0, 1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 16, 17, 19, 21]" }, { "code": null, "e": 27593, "s": 27579, "text": "............." }, { "code": null, "e": 27608, "s": 27593, "text": "python-utility" }, { "code": null, "e": 27615, "s": 27608, "text": "Python" }, { "code": null, "e": 27713, "s": 27615, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27722, "s": 27713, "text": "Comments" }, { "code": null, "e": 27735, "s": 27722, "text": "Old Comments" }, { "code": null, "e": 27770, "s": 27735, "text": "Read a file line by line in Python" }, { "code": null, "e": 27792, "s": 27770, "text": "Enumerate() in Python" }, { "code": null, "e": 27824, "s": 27792, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27850, "s": 27824, "text": "Python String | replace()" }, { "code": null, "e": 27875, "s": 27850, "text": "sum() function in Python" }, { "code": null, "e": 27914, "s": 27875, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27943, "s": 27914, "text": "Python string length | len()" }, { "code": null, "e": 27972, "s": 27943, "text": "*args and **kwargs in Python" } ]
Reverse bits of a positive integer number in Python - GeeksforGeeks
19 Nov, 2020 Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits. Examples: Input : n = 1, bitSize=32 Output : 2147483648 On a machine with size of bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648, bitSize=32 Output : 1 We can solve this problem quickly in Python. Approach is very simple, Convert integer number into it’s binary representation using bin(num) function.bin() function appends 0b as a prefix in binary representation of number, skip first two characters of binary representation and reverse remaining part of string.As we know in memory any binary representation of a number is filled with leading zeros after last set bit from left that means we need to append bitSize – len(reversedBits) number of zeros after reversing remaining string.Now convert binary representation into integer number using int(string,base) method. Convert integer number into it’s binary representation using bin(num) function. bin() function appends 0b as a prefix in binary representation of number, skip first two characters of binary representation and reverse remaining part of string. As we know in memory any binary representation of a number is filled with leading zeros after last set bit from left that means we need to append bitSize – len(reversedBits) number of zeros after reversing remaining string. Now convert binary representation into integer number using int(string,base) method. int(string,base) method takes a string and base to identify that string is referring to what number system ( binary=2, heaxadecimal=16, octal=8 etc. ) and converts string into decimal number system accordingly. For example ; int(‘1010’,2) = 10. # Function to reverse bits of positive # integer number def reverseBits(num,bitSize): # convert number into binary representation # output will be like bin(10) = '0b10101' binary = bin(num) # skip first two characters of binary # representation string and reverse # remaining string and then append zeros # after it. binary[-1:1:-1] --> start # from last character and reverse it until # second last character from left reverse = binary[-1:1:-1] reverse = reverse + (bitSize - len(reverse))*'0' # converts reversed binary string into integer print (int(reverse,2)) # Driver program if __name__ == "__main__": num = 1 bitSize = 32 reverseBits(num,bitSize) Output: 2147483648 base-conversion Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Bar Plot in Matplotlib Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Python - Call function from another file loops in python Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method Python Lambda Functions
[ { "code": null, "e": 23925, "s": 23897, "text": "\n19 Nov, 2020" }, { "code": null, "e": 24034, "s": 23925, "text": "Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits." }, { "code": null, "e": 24044, "s": 24034, "text": "Examples:" }, { "code": null, "e": 24213, "s": 24044, "text": "Input : n = 1, bitSize=32\nOutput : 2147483648 \nOn a machine with size of \nbit as 32. Reverse of 0....001 is\n100....0.\n\nInput : n = 2147483648, bitSize=32\nOutput : 1 \n" }, { "code": null, "e": 24283, "s": 24213, "text": "We can solve this problem quickly in Python. Approach is very simple," }, { "code": null, "e": 24832, "s": 24283, "text": "Convert integer number into it’s binary representation using bin(num) function.bin() function appends 0b as a prefix in binary representation of number, skip first two characters of binary representation and reverse remaining part of string.As we know in memory any binary representation of a number is filled with leading zeros after last set bit from left that means we need to append bitSize – len(reversedBits) number of zeros after reversing remaining string.Now convert binary representation into integer number using int(string,base) method." }, { "code": null, "e": 24912, "s": 24832, "text": "Convert integer number into it’s binary representation using bin(num) function." }, { "code": null, "e": 25075, "s": 24912, "text": "bin() function appends 0b as a prefix in binary representation of number, skip first two characters of binary representation and reverse remaining part of string." }, { "code": null, "e": 25299, "s": 25075, "text": "As we know in memory any binary representation of a number is filled with leading zeros after last set bit from left that means we need to append bitSize – len(reversedBits) number of zeros after reversing remaining string." }, { "code": null, "e": 25384, "s": 25299, "text": "Now convert binary representation into integer number using int(string,base) method." }, { "code": null, "e": 25629, "s": 25384, "text": "int(string,base) method takes a string and base to identify that string is referring to what number system ( binary=2, heaxadecimal=16, octal=8 etc. ) and converts string into decimal number system accordingly. For example ; int(‘1010’,2) = 10." }, { "code": "# Function to reverse bits of positive # integer number def reverseBits(num,bitSize): # convert number into binary representation # output will be like bin(10) = '0b10101' binary = bin(num) # skip first two characters of binary # representation string and reverse # remaining string and then append zeros # after it. binary[-1:1:-1] --> start # from last character and reverse it until # second last character from left reverse = binary[-1:1:-1] reverse = reverse + (bitSize - len(reverse))*'0' # converts reversed binary string into integer print (int(reverse,2)) # Driver program if __name__ == \"__main__\": num = 1 bitSize = 32 reverseBits(num,bitSize)", "e": 26380, "s": 25629, "text": null }, { "code": null, "e": 26388, "s": 26380, "text": "Output:" }, { "code": null, "e": 26400, "s": 26388, "text": "2147483648\n" }, { "code": null, "e": 26416, "s": 26400, "text": "base-conversion" }, { "code": null, "e": 26423, "s": 26416, "text": "Python" }, { "code": null, "e": 26521, "s": 26423, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26530, "s": 26521, "text": "Comments" }, { "code": null, "e": 26543, "s": 26530, "text": "Old Comments" }, { "code": null, "e": 26579, "s": 26543, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 26602, "s": 26579, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26641, "s": 26602, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26674, "s": 26641, "text": "Python | Convert set into a list" }, { "code": null, "e": 26723, "s": 26674, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 26764, "s": 26723, "text": "Python - Call function from another file" }, { "code": null, "e": 26780, "s": 26764, "text": "loops in python" }, { "code": null, "e": 26831, "s": 26780, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 26863, "s": 26831, "text": "Python Dictionary keys() method" } ]
Subscript and SuperScript a string in Android?
This example demonstrates how do I Subscript and SuperScript a string in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="36sp" android:textStyle="bold" android:layout_centerInParent="true" android:fontFamily="sans-serif-condensed"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.RelativeSizeSpan; import android.text.style.SubscriptSpan; import android.text.style.SuperscriptSpan; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView; String strText; SpannableStringBuilder spannableStringBuilder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); strText= "Test text to show SubscriptSpan X2 and SuperscriptSpan Y5 example."; spannableStringBuilder = new SpannableStringBuilder(strText); SubscriptSpan subscriptSpan = new SubscriptSpan(); SuperscriptSpan superscriptSpan = new SuperscriptSpan(); spannableStringBuilder.setSpan(subscriptSpan, strText.indexOf("2"), strText.indexOf("2") + ("2").length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannableStringBuilder.setSpan(superscriptSpan, strText.indexOf("5"), strText.indexOf("5") + ("5").length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); showSmallSizeText("2"); showSmallSizeText("5"); textView.setText(spannableStringBuilder); } private void showSmallSizeText(String s) { RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(.5f); spannableStringBuilder.setSpan(relativeSizeSpan, strText.indexOf(s), strText.indexOf(s) + (s).length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1144, "s": 1062, "text": "This example demonstrates how do I Subscript and SuperScript a string in android." }, { "code": null, "e": 1273, "s": 1144, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1338, "s": 1273, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1943, "s": 1338, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"36sp\"\n android:textStyle=\"bold\"\n android:layout_centerInParent=\"true\"\n android:fontFamily=\"sans-serif-condensed\"/>\n</RelativeLayout>" }, { "code": null, "e": 2000, "s": 1943, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3624, "s": 2000, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.SpannableStringBuilder;\nimport android.text.Spanned;\nimport android.text.style.RelativeSizeSpan;\nimport android.text.style.SubscriptSpan;\nimport android.text.style.SuperscriptSpan;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n String strText;\n SpannableStringBuilder spannableStringBuilder;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.textView);\n strText= \"Test text to show SubscriptSpan X2 and SuperscriptSpan Y5 example.\";\n spannableStringBuilder = new SpannableStringBuilder(strText);\n SubscriptSpan subscriptSpan = new SubscriptSpan();\n SuperscriptSpan superscriptSpan = new SuperscriptSpan();\n spannableStringBuilder.setSpan(subscriptSpan, strText.indexOf(\"2\"),\n strText.indexOf(\"2\") + (\"2\").length(),\n Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);\n spannableStringBuilder.setSpan(superscriptSpan, strText.indexOf(\"5\"), strText.indexOf(\"5\") + (\"5\").length(),\n Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);\n showSmallSizeText(\"2\");\n showSmallSizeText(\"5\");\n textView.setText(spannableStringBuilder);\n }\n private void showSmallSizeText(String s) {\n RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(.5f);\n spannableStringBuilder.setSpan(relativeSizeSpan, strText.indexOf(s), strText.indexOf(s) + (s).length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);\n }\n}" }, { "code": null, "e": 3679, "s": 3624, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4349, "s": 3679, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4696, "s": 4349, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 4737, "s": 4696, "text": "Click here to download the project code." } ]
Creating and training a U-Net model with PyTorch for 2D & 3D semantic segmentation: Training [3/4] | by Johannes Schmidt | Towards Data Science
In the previous chapters we created our dataset and built the U-Net model. Now it is time to start training. For that we will write our own training loop within a simple Trainer class and save it in trainer.py. The Jupyter notebook can be found here. The idea is that we can instantiate a Trainer object with parameters such as the model, a criterion etc. and then call it’s class method run_trainer() to start training. This method will output the accumulated training loss, the validation loss, and the learning rate that was used for training. Here is the code: In order to create a trainer object the following parameters are required: model: e.g. the U-Net device: CPU or GPU criterion: loss function (e.g. CrossEntropyLoss, DiceCoefficientLoss) optimizer: e.g. SGD training_DataLoader: a training dataloader validation_DataLoader: a validation dataloader lr_scheduler: a learning rate scheduler (optional) epochs: The number of epochs we want to train epoch: The epoch number from where training should start Training can then be started with the class method run_trainer(). Since training is usually performed with a training and a validation phase, _train() and _validate() are two functions that are run once for every epoch we train with run_trainer() (line 33–53). If we have a lr_scheduler, we also perform a step with the lr_scheduler. To visualize the progress of training, I included a progress bar with the library tqdm. Now let’s take a closer look on what happens when calling _train() and _validate() . If you are familiar with using PyTorch for network training, there is probably nothing new here. In _train() we basically just iterate over our training dataloader and send our batches through the network in train mode (line 56–64). We then use this output together with our target to compute the loss with the loss function for the current batch (line 65). The computed loss is then appended in a temporary list (line 66–67). Based on the computed gradients, we perform a backward pass and a step with our optimizer to update the model’s parameters (line 68–69). At the end we update our progress bar for the training phase to show the current loss (line 71). The function outputs the mean of the temporary loss list and the learning rate that was used. In _validate() , similar to _train() , we iterate over our validation dataloader, send our batches through the network in validation mode and compute the loss. This time, without computing the gradients and without performing a backward pass (line 78–97). Let’s create our Carvana data generators once again, but this time run the code within a Jupyter notebook. Please note that I resize the images to 128x128x3 using skimage.transform.resize() to speed up training. This will generate batches of images that look like this: from visual import DatasetViewerdataset_viewer_training = DatasetViewer(dataset_train)dataset_viewer_training.napari() I can then instantiate the Trainer object and start training: Training will look something like this: Although training was performed on a NVIDIA 1070, it took 1:19 min to train 2 epochs with only 96 images (size 128x128x3) for each epoch. Why is that? The reason why this is so painfully slow, is because every time we generate a batch we read the data in full resolution (1918x1280x3) and resize it. And we do this for every epoch! Therefore, it would make more sense to either store the data in a lower resolution and then to pick the data up, or store the data in cache and access it when it’s needed. Or both. Let’s slightly change our custom SegmentationDataSet1 class (create a new class called SegmentationDataSet2): Here we added the argument use_cache and pre_transform . We basically just iterate over our input and target list and store the images in a list when we instantiate our dataset. When __getitem__ is called, an image-target pair from this list is returned. I added the pre_transform argument because I don’t want to change the original files. Instead, I want the images to be picked up, resized and stored in memory. Again, I included a progress bar to visualize the caching. Let’s try it out. The changes in code are the following: And it looks something like this: The first progress bar represents the training dataloader and the second the validation dataloader. Let’s train again for 2 epochs and see how long it’ll take. Training took about 2 seconds only! That’s much better. But there is one part we can still improve. Creating the dataset that reads images and stores them in memory takes a bit of time. When you look at the code and the CPU usage, you’ll notice that only one core is used. Let’s change it in a way, so that all cores are used. Here I use the multiprocessing library: Please note that there is no progressbar in this dataset class! Before we perform training, let’s also make a quick detour and talk about the learning rate. The learning rate is one of the most important hyperparameters in neural network training. Choosing proper learning rates throughout the learning procedure is difficult as a small learning rate leads to slow convergence while a high learning rate can cause divergence. Also, frequent parameter updates with high variance in SGD can cause fluctuations, which makes finding the (local) minimum for SGD even more difficult. To identify an optimal learning rate, we can test different learning rates empirically with a learning rate range test. Inspired by the best practices I picked up from the fast.ai course, I recommend using a learning rate finder before starting the actual training. Sylvain Gugger from fast.ai wrote a really good summary about this problem. The code that I will show you is based on Tanjid Hasan Tonmoy’s pytorch-lr-finder, which is an implementation of the learning rate range test from Leslie Smith. I only slightly modified the code and included a progressbar (yes, I like them). Let’s perform such a learning rate range test. Since our dataset is rather small (96 images), we’ll perform some extra steps (1000). The upper progressbar displays the number of epochs and the lower progressbar shows the number of steps we perform on the current epoch. Let’s plot the results of the test: 0.01 seems to be a good learning rate. We’ll take it. Let’s train for 100 epochs... ...and visualize the training and validation loss. For that I will use matplotlib and write a function that I can add to the visual.py file. Let’s see what the function plot_training() will output when we pass in our losses and the learning rate. Training looks good! We can then save our model with PyTorch: # save the modelmodel_name = 'carvana_model.pt'torch.save(model.state_dict(), pathlib.Path.cwd() / model_name) In this part, we performed training with a sample of the Carvana dataset by creating a simple training loop. The progress of this training loop can be visualized with a progressbar and the result of training can be plotted with matplotlib. We noticed that training was painfully slow because our data was picked up very slowly by our custom data generator. Because of that, we changed it in a way so that data is only read once and then picked up from memory when needed. We also made use of multiprocessing for that case. Additionally, we added a learning rate range finder, to determine an optimal learning rate which we then used for model training. In the next chapter, we’ll let the model predict the segmentation maps of unseen image data (inference).
[ { "code": null, "e": 736, "s": 171, "text": "In the previous chapters we created our dataset and built the U-Net model. Now it is time to start training. For that we will write our own training loop within a simple Trainer class and save it in trainer.py. The Jupyter notebook can be found here. The idea is that we can instantiate a Trainer object with parameters such as the model, a criterion etc. and then call it’s class method run_trainer() to start training. This method will output the accumulated training loss, the validation loss, and the learning rate that was used for training. Here is the code:" }, { "code": null, "e": 811, "s": 736, "text": "In order to create a trainer object the following parameters are required:" }, { "code": null, "e": 833, "s": 811, "text": "model: e.g. the U-Net" }, { "code": null, "e": 852, "s": 833, "text": "device: CPU or GPU" }, { "code": null, "e": 922, "s": 852, "text": "criterion: loss function (e.g. CrossEntropyLoss, DiceCoefficientLoss)" }, { "code": null, "e": 942, "s": 922, "text": "optimizer: e.g. SGD" }, { "code": null, "e": 985, "s": 942, "text": "training_DataLoader: a training dataloader" }, { "code": null, "e": 1032, "s": 985, "text": "validation_DataLoader: a validation dataloader" }, { "code": null, "e": 1083, "s": 1032, "text": "lr_scheduler: a learning rate scheduler (optional)" }, { "code": null, "e": 1129, "s": 1083, "text": "epochs: The number of epochs we want to train" }, { "code": null, "e": 1186, "s": 1129, "text": "epoch: The epoch number from where training should start" }, { "code": null, "e": 1790, "s": 1186, "text": "Training can then be started with the class method run_trainer(). Since training is usually performed with a training and a validation phase, _train() and _validate() are two functions that are run once for every epoch we train with run_trainer() (line 33–53). If we have a lr_scheduler, we also perform a step with the lr_scheduler. To visualize the progress of training, I included a progress bar with the library tqdm. Now let’s take a closer look on what happens when calling _train() and _validate() . If you are familiar with using PyTorch for network training, there is probably nothing new here." }, { "code": null, "e": 2448, "s": 1790, "text": "In _train() we basically just iterate over our training dataloader and send our batches through the network in train mode (line 56–64). We then use this output together with our target to compute the loss with the loss function for the current batch (line 65). The computed loss is then appended in a temporary list (line 66–67). Based on the computed gradients, we perform a backward pass and a step with our optimizer to update the model’s parameters (line 68–69). At the end we update our progress bar for the training phase to show the current loss (line 71). The function outputs the mean of the temporary loss list and the learning rate that was used." }, { "code": null, "e": 2704, "s": 2448, "text": "In _validate() , similar to _train() , we iterate over our validation dataloader, send our batches through the network in validation mode and compute the loss. This time, without computing the gradients and without performing a backward pass (line 78–97)." }, { "code": null, "e": 2811, "s": 2704, "text": "Let’s create our Carvana data generators once again, but this time run the code within a Jupyter notebook." }, { "code": null, "e": 2974, "s": 2811, "text": "Please note that I resize the images to 128x128x3 using skimage.transform.resize() to speed up training. This will generate batches of images that look like this:" }, { "code": null, "e": 3093, "s": 2974, "text": "from visual import DatasetViewerdataset_viewer_training = DatasetViewer(dataset_train)dataset_viewer_training.napari()" }, { "code": null, "e": 3155, "s": 3093, "text": "I can then instantiate the Trainer object and start training:" }, { "code": null, "e": 3195, "s": 3155, "text": "Training will look something like this:" }, { "code": null, "e": 3818, "s": 3195, "text": "Although training was performed on a NVIDIA 1070, it took 1:19 min to train 2 epochs with only 96 images (size 128x128x3) for each epoch. Why is that? The reason why this is so painfully slow, is because every time we generate a batch we read the data in full resolution (1918x1280x3) and resize it. And we do this for every epoch! Therefore, it would make more sense to either store the data in a lower resolution and then to pick the data up, or store the data in cache and access it when it’s needed. Or both. Let’s slightly change our custom SegmentationDataSet1 class (create a new class called SegmentationDataSet2):" }, { "code": null, "e": 4349, "s": 3818, "text": "Here we added the argument use_cache and pre_transform . We basically just iterate over our input and target list and store the images in a list when we instantiate our dataset. When __getitem__ is called, an image-target pair from this list is returned. I added the pre_transform argument because I don’t want to change the original files. Instead, I want the images to be picked up, resized and stored in memory. Again, I included a progress bar to visualize the caching. Let’s try it out. The changes in code are the following:" }, { "code": null, "e": 4383, "s": 4349, "text": "And it looks something like this:" }, { "code": null, "e": 4543, "s": 4383, "text": "The first progress bar represents the training dataloader and the second the validation dataloader. Let’s train again for 2 epochs and see how long it’ll take." }, { "code": null, "e": 4910, "s": 4543, "text": "Training took about 2 seconds only! That’s much better. But there is one part we can still improve. Creating the dataset that reads images and stores them in memory takes a bit of time. When you look at the code and the CPU usage, you’ll notice that only one core is used. Let’s change it in a way, so that all cores are used. Here I use the multiprocessing library:" }, { "code": null, "e": 4974, "s": 4910, "text": "Please note that there is no progressbar in this dataset class!" }, { "code": null, "e": 5067, "s": 4974, "text": "Before we perform training, let’s also make a quick detour and talk about the learning rate." }, { "code": null, "e": 6072, "s": 5067, "text": "The learning rate is one of the most important hyperparameters in neural network training. Choosing proper learning rates throughout the learning procedure is difficult as a small learning rate leads to slow convergence while a high learning rate can cause divergence. Also, frequent parameter updates with high variance in SGD can cause fluctuations, which makes finding the (local) minimum for SGD even more difficult. To identify an optimal learning rate, we can test different learning rates empirically with a learning rate range test. Inspired by the best practices I picked up from the fast.ai course, I recommend using a learning rate finder before starting the actual training. Sylvain Gugger from fast.ai wrote a really good summary about this problem. The code that I will show you is based on Tanjid Hasan Tonmoy’s pytorch-lr-finder, which is an implementation of the learning rate range test from Leslie Smith. I only slightly modified the code and included a progressbar (yes, I like them)." }, { "code": null, "e": 6342, "s": 6072, "text": "Let’s perform such a learning rate range test. Since our dataset is rather small (96 images), we’ll perform some extra steps (1000). The upper progressbar displays the number of epochs and the lower progressbar shows the number of steps we perform on the current epoch." }, { "code": null, "e": 6378, "s": 6342, "text": "Let’s plot the results of the test:" }, { "code": null, "e": 6462, "s": 6378, "text": "0.01 seems to be a good learning rate. We’ll take it. Let’s train for 100 epochs..." }, { "code": null, "e": 6603, "s": 6462, "text": "...and visualize the training and validation loss. For that I will use matplotlib and write a function that I can add to the visual.py file." }, { "code": null, "e": 6709, "s": 6603, "text": "Let’s see what the function plot_training() will output when we pass in our losses and the learning rate." }, { "code": null, "e": 6730, "s": 6709, "text": "Training looks good!" }, { "code": null, "e": 6771, "s": 6730, "text": "We can then save our model with PyTorch:" }, { "code": null, "e": 6883, "s": 6771, "text": "# save the modelmodel_name = 'carvana_model.pt'torch.save(model.state_dict(), pathlib.Path.cwd() / model_name)" }, { "code": null, "e": 7536, "s": 6883, "text": "In this part, we performed training with a sample of the Carvana dataset by creating a simple training loop. The progress of this training loop can be visualized with a progressbar and the result of training can be plotted with matplotlib. We noticed that training was painfully slow because our data was picked up very slowly by our custom data generator. Because of that, we changed it in a way so that data is only read once and then picked up from memory when needed. We also made use of multiprocessing for that case. Additionally, we added a learning rate range finder, to determine an optimal learning rate which we then used for model training." } ]